search
HomeJavajavaTutorialHow to get request data in SpringMVC?

How to get request data in SpringMVC?

May 09, 2023 pm 10:04 PM
javaspringmvc

    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.

    //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);
    }

    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.

    //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);
    }

    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.

    //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));
    }

    4) Collection type parameters

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

    <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>
    @RequestMapping("/quick12")
    @ResponseBody
    public void quickMethod12(Vo vo) throws IOException {
        System.out.println(vo.getUserList());
    }

    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.

    <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>
    @RequestMapping("/quick13")
    @ResponseBody
    public void quickMethod13(@RequestBody List<User> userList) throws 
    IOException {
        System.out.println(userList);
    }

    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

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

    • 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.

    <!--资源过滤器-->
        <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>

    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.

    <form action="${pageContext.request.contextPath}/quick14" method="post">
     <input type="text" name="name"><br>
     <input type="submit" value="提交"><br>
    </form>

    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
    @RequestMapping("/quick14")
    @ResponseBody
    public void quickMethod14(@RequestParam(value="name",required = 
    false,defaultValue = "defaultname") String username) throws IOException {
    System.out.println(username);
    }

    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.
    //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);
    }
    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

    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;
        }
    }

    ② Configure in spring-mvc.xml Declare the converter

    <!--配置自定义转换器-->
        <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <bean class="converter.DateConverter"/>
                </list>
            </property>
        </bean>

    in the file ③ Reference the converter

     <!--注解驱动-->
        <mvc:annotation-driven conversion-service="conversionService"/>

    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
    @RequestMapping("/quick17")
    @ResponseBody
    public void quickMethod17(@RequestHeader(value = "User-Agent",required = false) String 
    headerValue){
        System.out.println(headerValue);
    }

    @CookieValue                         

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

    value 指定cookie的名称
    required 是否必须携带此cookie
    @RequestMapping("/quick18")
    @ResponseBody
    public void quickMethod18(@CookieValue(value = "JSESSIONID",required = false) String jsessionid){
        System.out.println(jsessionid);
    }

    7.文件上传

    文件上传客户端三要素:

    • 表单项type=“file”

    • 表单的提交方式是post

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

    <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>

    文件上传步骤

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

    <!--文件下载-->
        <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>

    ② 配置文件上传解析器

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="UTF-8"/>
            <property name="maxUploadSize" value="500000"/>
        </bean>

    ③ 编写文件上传代码

    @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();
            }
        }

    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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

    JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

    Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

    Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

    Java Platform Independence Explained: A Comprehensive GuideJava Platform Independence Explained: A Comprehensive GuideMay 07, 2025 pm 04:53 PM

    JavaachievesplatformindependencethroughbytecodeandtheJVM.1)Codeiscompiledintobytecode,notmachinecode.2)TheJVMinterpretsbytecodeonanyplatform,ensuring"writeonce,runanywhere."3)Usecross-platformlibraries,becautiouswithnativecode,andtestonmult

    How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

    Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

    What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

    JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

    Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

    ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

    What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

    Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

    What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

    Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

    See all articles

    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

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software