Table of Contents
1. Obtain request parameters
1) Basic type parameters:
2) POJO type parameters:
3) Array type parameters
4) Collection type parameters
2. The problem of garbled request
3. Parameter binding annotation @RequestParam
4. Get Restful style parameters
7.文件上传
Home Java javaTutorial How to get request data in SpringMVC?

How to get request data in SpringMVC?

May 09, 2023 pm 10:04 PM
java springmvc

    1. Obtain request parameters

    The format of client request parameters is: name=value&name=value... The server needs to obtain the requested parameters, sometimes Data also needs to be encapsulated. SpringMVC can receive the following types of parameters:

    1) Basic type parameters:

    The parameter name of the business method in the Controller must be consistent with the name of the request parameter. Values ​​are automatically mapped and matched.

    1

    2

    3

    4

    5

    6

    7

    //http://localhost:8080/project/quick9?username=zhangsan&age=12

    @RequestMapping("/quick9")

    @ResponseBody

    public void quickMethod9(String username,int age) throws IOException {

        System.out.println(username);

        System.out.println(age);

    }

    Copy after login

    2) POJO type parameters:

    The attribute name of the POJO parameter of the business method in the Controller is consistent with the name of the request parameter, and the parameter value will be automatically mapped and matched.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    //http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12

    public class User {

        private String username;

        private int age;

        getter/setter…

    }

    @RequestMapping("/quick10")

    @ResponseBody

    public void quickMethod10(User user) throws IOException {

        System.out.println(user);

    }

    Copy after login

    3) Array type parameters

    The name of the business method array in the Controller is consistent with the name of the request parameter, and the parameter values ​​will be automatically mapped and matched.

    1

    2

    3

    4

    5

    6

    //http://localhost:8080/project/quick11?strs=111&strs=222&strs=333

    @RequestMapping("/quick11")

    @ResponseBody

    public void quickMethod11(String[] strs) throws IOException {

        System.out.println(Arrays.asList(strs));

    }

    Copy after login

    4) Collection type parameters

    When obtaining collection parameters, you must wrap the collection parameters into a POJO.

    1

    2

    3

    4

    5

    6

    7

    <form action="${pageContext.request.contextPath}/quick12" method="post">

     <input type="text" name="userList[0].username"><br>

     <input type="text" name="userList[0].age"><br>

     <input type="text" name="userList[1].username"><br>

     <input type="text" name="userList[1].age"><br>

     <input type="submit" value="提交"><br>

    </form>

    Copy after login

    1

    2

    3

    4

    5

    @RequestMapping("/quick12")

    @ResponseBody

    public void quickMethod12(Vo vo) throws IOException {

        System.out.println(vo.getUserList());

    }

    Copy after login

    When submitting using ajax, you can specify the contentType as json, then use @RequestBody in the method parameter position to directly receive the collection data without using POJO for packaging.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    <script>

    //模拟数据

    var userList = new Array();

    userList.push({username: "zhangsan",age: "20"});

    userList.push({username: "lisi",age: "20"});

    $.ajax({

    type: "POST",

    url: "/itheima_springmvc1/quick13",

    data: JSON.stringify(userList),

    contentType : &#39;application/json;charset=utf-8&#39;

    });

    </script>

    Copy after login

    1

    2

    3

    4

    5

    6

    @RequestMapping("/quick13")

    @ResponseBody

    public void quickMethod13(@RequestBody List<User> userList) throws

    IOException {

        System.out.println(userList);

    }

    Copy after login

    Note: Through the Google developer tool packet capture, it was found that the jquery file was not loaded. The reason is that the url-pattern of the SpringMVC front-end controller DispatcherServlet is configured with /, which means that all resources are filtered. , we can specify the released static resources in the following two ways: • Specify the released resources in the spring-mvc.xml configuration file

    1

    <mvc:resources mapping="/js/**" location="/js/"/>

    Copy after login

    • Or use the tag

    2. The problem of garbled request

    When a post request is made, the data will be garbled. We can set a filter in web.xml to filter the encoding.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    <!--资源过滤器-->

        <filter>

            <filter-name>CharacterEncodingFilter</filter-name>

            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

            <init-param>

                <param-name>encoding</param-name>

                <param-value>UTF-8</param-value>

            </init-param>

        </filter>

        <filter-mapping>

            <filter-name>CharacterEncodingFilter</filter-name>

            <url-pattern>/*</url-pattern>

        </filter-mapping>

    Copy after login

    When the requested parameter name is inconsistent with the Controller's business method parameter name, you need to display the binding through the @RequestParam annotation.

    1

    2

    3

    4

    <form action="${pageContext.request.contextPath}/quick14" method="post">

     <input type="text" name="name"><br>

     <input type="submit" value="提交"><br>

    </form>

    Copy after login

    3. Parameter binding annotation @RequestParam

    The annotation @RequestParam also has the following parameters that can be used:

    value: Request parameter name
    required:Whether the specified request parameter must be included, the default is true, if there is no such parameter when submitting, an error will be reported
    defaultValue: When no request parameters are specified, the specified default value is used for assignment

    1

    2

    3

    4

    5

    6

    @RequestMapping("/quick14")

    @ResponseBody

    public void quickMethod14(@RequestParam(value="name",required =

    false,defaultValue = "defaultname") String username) throws IOException {

    System.out.println(username);

    }

    Copy after login

    4. Get Restful style parameters

    Restful is a software architectural style and design style, not a standard. It just provides a set of design principles and constraints. It is mainly used for client-server interactive software. Software designed based on this style can be simpler, more layered, and easier to implement caching mechanisms.

    Restful style requests use "url request method" to indicate the purpose of a request. The four verbs in the HTTP protocol indicating the operation method are as follows:

    ##DELETE:Delete the resource##PUT:POST:##For example:
    GET: Get the resource
    Update resources
    New resource

    /user/1 GET: Get the user with id = 1/user/1 DELETE: Delete user/user/1 with id = 1 PUT:Update useruser with id = 1 POST :Add new user1 in the above url address/user/1 is the request parameter to be obtained, and placeholders can be used in SpringMVC Perform parameter binding. The address /user/1 can be written as /user/{id}, and the placeholder {id} corresponds to the value of 1. In the business method, we can use the @PathVariable annotation to obtain placeholder matching.

    1

    2

    3

    4

    5

    6

    //http://localhost:8080/itheima_springmvc1/quick19/zhangsan

    @RequestMapping("/quick19/{name}")

    @ResponseBody

    public void quickMethod19(@PathVariable(value = "name",required = true) String name){

    System.out.println(name);

    }

    Copy after login
    5. Custom type converter

    Although SpringMVC has provided some commonly used type converters by default, such as converting a string submitted by the client into an int type Make parameter settings.
    • But not all data types provide converters. If they are not provided, you need to customize the converter. For example, date type data requires a custom converter.
    • Development steps for custom type converters:
    ① Define the converter class to implement the Converter interface

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    public class DateConverter implements Converter<String, Date> {

        @Override

        public Date convert(String source) {

            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");

            Date date = null;

            try {

                date = format.parse(source);

            } catch (ParseException e) {

                e.printStackTrace();

            }

            return date;

        }

    }

    Copy after login

    ② Configure in spring-mvc.xml Declare the converter

    1

    2

    3

    4

    5

    6

    7

    8

    <!--配置自定义转换器-->

        <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">

            <property name="converters">

                <list>

                    <bean class="converter.DateConverter"/>

                </list>

            </property>

        </bean>

    Copy after login

    in the file ③ Reference the converter

    1

    2

    <!--注解驱动-->

       <mvc:annotation-driven conversion-service="conversionService"/>

    Copy after login

    in 6. Obtain the request header

    @RequestHeader

    Use @RequestHeader to obtain the request header information, which is equivalent to request.getHeader(name) learned in the web stage. The attributes annotated by @RequestHeader are as follows:

    value The name of the request headerrequiredWhether this request header must be carried

    1

    2

    3

    4

    5

    6

    @RequestMapping("/quick17")

    @ResponseBody

    public void quickMethod17(@RequestHeader(value = "User-Agent",required = false) String

    headerValue){

        System.out.println(headerValue);

    }

    Copy after login

    @CookieValue

    使用@CookieValue可以获得指定Cookie的值 @CookieValue注解的属性如下:

    value指定cookie的名称
    required是否必须携带此cookie

    1

    2

    3

    4

    5

    @RequestMapping("/quick18")

    @ResponseBody

    public void quickMethod18(@CookieValue(value = "JSESSIONID",required = false) String jsessionid){

        System.out.println(jsessionid);

    }

    Copy after login

    7.文件上传

    文件上传客户端三要素:

    • 表单项type=“file”

    • 表单的提交方式是post

    • 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

    1

    2

    3

    4

    5

    6

    <form action="${pageContext.request.contextPath}/quick20" method="post"

    enctype="multipart/form-data">

    名称:<input type="text" name="name"><br>

    文件:<input type="file" name="file"><br>

     <input type="submit" value="提交"><br>

    </form>

    Copy after login

    文件上传步骤

    ① 在pom.xml导入fileupload和io坐标

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    <!--文件下载-->

        <dependency>

          <groupId>commons-fileupload</groupId>

          <artifactId>commons-fileupload</artifactId>

          <version>1.4</version>

        </dependency>

        <dependency>

          <groupId>commons-io</groupId>

          <artifactId>commons-io</artifactId>

          <version>2.6</version>

        </dependency>

    Copy after login

    ② 配置文件上传解析器

    1

    2

    3

    4

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

            <property name="defaultEncoding" value="UTF-8"/>

            <property name="maxUploadSize" value="500000"/>

        </bean>

    Copy after login

    ③ 编写文件上传代码

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    @RequestMapping("/quick8")

        @ResponseBody

        public void save8(String name, MultipartFile uploadfile) {

            System.out.println("save8 running...");

            System.out.println(name);

            String filename = uploadfile.getOriginalFilename();

            try {

                uploadfile.transferTo(new File("D:\\upload\\"+filename));

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    Copy after login

    The above is the detailed content of How to get request data in SpringMVC?. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    See all articles