Spring MVC requests and responses

Spring MVC requests and responses

1, Response of spring MVC

The data response methods of spring MVC are as follows:

  1. Page Jump
    1. Return string directly
    2. Return via ModelAndView object
  2. Write back data
    1. Return string directly
    2. Returns an object or collection

1. Page Jump

1.1. Directly return string

In the code for getting started with spring MVC, the direct return string is used to realize the jump of the page

    @RequestMapping(value = "/quick", method = RequestMethod.GET, params = {"username"})   //Request mapping
    public String quickMethod(){
        System.out.println("quickMethod running.......");
        //return: the view to jump to
        //Add a / to indicate the current web directory
        return "quick";
    }

1.2. Return through ModelAndView object

ModelAndView represents M and V in spring MVC

The main function is to set the steering address, store the obtained data, and then transfer the data to the View

The stored data can be used in jsp files through EL expressions

The main methods are as follows:

  • setViewName(String viewName): set the view name of this ModelAndView, which is resolved by DispatcherServlet through ViewResolver
  • addObject(String attributeName, Object attributeValue): bind data through key/value

There are two ways to create ModelAndView:

  • Create a ModelAndView object by itself
  • ModelAndView is automatically created by the spring MVC framework as a parameter
    @RequestMapping(value = "/quick3")   //Request mapping
    public ModelAndView quickMethod3(ModelAndView modelAndView){
        //The ModelAndView object is created by the spring MVC framework as a formal parameter
        modelAndView.setViewName("quick");
        modelAndView.addObject("username", "Pleasant Sheep");
        return modelAndView;
    }

    @RequestMapping(value = "/quick2")   //Request mapping
    public ModelAndView quickMethod2(){
        //Create your own ModelAndView object
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("quick");
        modelAndView.addObject("username", "Xiao Ming");
        return modelAndView;
    }

1.3 others

You can store the data in the domain through the HttpServletRequest object of Java Web, then forward it to the corresponding view, and then display it with EL expression

You can also use Model objects to store data

    @RequestMapping(value = "/quick5")   //Request mapping
    public String quickMethod5(HttpServletRequest request){
        request.setAttribute("username", "Red Wolf");
        return "quick";
    }


    @RequestMapping(value = "/quick4")   //Request mapping
    public String quickMethod4(Model model){
        model.addAttribute("username", "Grey Wolf");
        return "quick";
    }

2. Write back data

2.1. Directly return string

Writeback data has also been learned in the Java Web phase, using the response object for writeback

    @RequestMapping(value = "/quick6")   //Request mapping
    public void quickMethod6(HttpServletResponse response) throws IOException {
        response.getWriter().println("Hello kang");
    }

This method is not commonly used in development. You can use the @ ResponseBody annotation to tell the spring MVC framework that the string returned by the method is not a jump, but directly returned in the http response body (the name of the view is returned by default without writing this annotation)

    @RequestMapping(value = "/quick8")   //Request mapping
    @ResponseBody
    public String quickMethod8() throws IOException {
        //Writeback json
        return "{\"username\":\"zhangsan\",\"age\":18}";
    }

    @RequestMapping(value = "/quick7")   //Request mapping
    @ResponseBody
    public String quickMethod7(HttpServletResponse response) throws IOException {
        //Writeback string
        return "Hello quick7";
    }

Generally, there are many operations to return json in development, but it is troublesome to write json manually. Therefore, Java provides a tool class for converting Java objects to json objects

  • Use JSON Tojsonstring (object) needs to import dependencies

        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.62</version>
        </dependency>
    
  • Use objectmapper Writevalueasstring() also needs to import dependencies

        <!--jackson-->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.9.0</version>
        </dependency>
    
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.9.0</version>
        </dependency>
        
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.9.0</version>
        </dependency>
    
    @RequestMapping(value = "/quick10")   //Request mapping
    @ResponseBody
    public String quickMethod10() throws IOException {
        User user = new User();
        user.setName("lisi");
        user.setAge(20);
        return JSON.toJSONString(user);
    }

    @RequestMapping(value = "/quick9")   //Request mapping
    @ResponseBody
    public String quickMethod9() throws IOException {
        User user = new User();
        user.setName("lisi");
        user.setAge(20);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(user);
    }

2.2. Return object or set

In addition to the above manual conversion of Java objects into JSON objects, spring MVC will automatically help us convert objects or collections into JSON strings and write back

This requires us to configure the message conversion parameter for the processor adapter and specify jackson to convert objects or collections. Therefore, we need to configure the following in spring MVC (the purpose of configuration is to tell spring MVC that the returned objects need to be converted by this json converter)

(pay attention to adding mvc space)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.kang.controller">
        <!--scanning com.kang.controller Under the bag Controller annotation-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Configure internal resource view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--Configure prefix-->
        <property name="prefix" value="/jsp/"></property>
        <!--Configuration suffix-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--Configure processor mapper-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!--to configure json Conversion tool-->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
    </bean>

</beans>

After the configuration is completed, do not return strings, but directly return objects or collections. The spring MVC framework will automatically help us complete the conversion and writeback of Json objects

    @RequestMapping(value = "/quick11")   //Request mapping
    @ResponseBody
    public User quickMethod11() throws IOException {
        User user = new User();
        user.setName("liu");
        user.setAge(20);
        return user;
    }

2.3. Lifting (important)

Configure spring mvc The processor mapper in XML is used to convert java objects into json objects, but there will be many such configuration operations, so we can use mvc annotation driven to simplify the above operations

    <!--Annotation driven-->
    <mvc:annotation-driven/>

Among the various components of spring MVC, processor mapper, processor adapter and view parser become the three major components of spring MVC. The automatic loading of RequestMappingHandlerMapping (processing mapper) and RequestMappingHandlerAdapter (processing adapter) can be used in spring XML XML configuration files are used to replace the configuration of annotation processors and adapters. At the same time, using the default bottom layer will integrate jackson to convert the json format string of objects or collections.

2, Spring MVC gets the requested data

Generally speaking, the data requested by the client is in this format: name = XXX & password = XXX

In the Java Web stage, these request data need to be encapsulated and processed by the program

However, in the spring MVC framework, these corresponding encapsulation can be completed by the framework

Spring MVC can accept the following types of parameters:

  • Basic type parameters
  • POJO type parameters
  • Array type parameter
  • Set type parameter

1. Basic type parameters

The parameter name of the business method in the Controller should be consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically by the Spring framework.

    @RequestMapping(value = "/quick12")   //Request mapping
    @ResponseBody
    public void quickMethod12(String username, int age){
        System.out.println(username);
        System.out.println(age);
    }
http://localhost:8080/SpringMVC/quick12?username=zhangsan&age=12

2. POJO type parameters

The property 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 mapped and matched automatically.

    public class User {
    	private String name;
    	private int age;
    	get/set
    }
    
    
    @RequestMapping(value = "/quick13")   //Request mapping
    @ResponseBody
    public void quickMethod13(User user){
        System.out.println(user.getName());
        System.out.println(user.getAge());
    }
http://localhost:8080/SpringMVC/quick13?username=zhangsan&age=12

3. Array type parameter

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

    @RequestMapping(value = "/quick14")   //Request mapping
    @ResponseBody
    public void quickMethod14(String[] strs){
        System.out.println(Arrays.asList(strs));
    }
http://localhost:8080/SpringMVC/quick14?strs=111&strs=222&strs=333

4. Set type parameter

There are two ways to get the request data of a collection

  • Wrap the collection parameters into a POJO class
  • Submit using ajax

4.1. Package set parameters into a POJO class (understand)

  • First, let's wrap the collection into a POJO class

    package com.kang.poj;
    
    import java.util.List;
    
    public class Vo {
        List<User> userList;
    
        public List<User> getUserList() {
            return userList;
        }
    
        public void setUserList(List<User> userList) {
            this.userList = userList;
        }
    
        @Override
        public String toString() {
            return "Vo{" +
                    "userList=" + userList +
                    '}';
        }
    }
    
  • Write Controller

        @RequestMapping(value = "/quick15")   //Request mapping
        @ResponseBody
        public void quickMethod15(Vo vo){
            System.out.println(vo);
        }
    
  • Write the corresponding jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/user/quick15" method="post">
            <input type="text" name="userList[0].name"><br>
            <input type="text" name="userList[0].age"><br>
            <input type="text" name="userList[1].name"><br>
            <input type="text" name="userList[1].age"><br>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    

In this way, the data submitted by the form will be submitted to quick15, and the corresponding Controller business method contains a POJO class

Then, the location of the corresponding set will be matched according to the name of the input tag, and then the data will be stored in it, so as to complete the packaging of the set type parameters

But this method is not recommended

4.2. Submit using ajax

When submitting with ajax, you can specify the content type as json, so using @ RequestBody in the method parameter position can directly receive the collection data without using POJO for packaging.

${pageContext.request.contextPath} is to obtain the corresponding virtual address, that is, the address of spring MVC

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="js/jquery-3.6.0.js"></script>
<script>
    var userList = new Array();
    userList.push({name: "zhangsan", age: "20"});
    userList.push({name: "lisi", age: "18"});
    $.ajax({
        type: "POST",
        url: "${pageContext.request.contextPath}/user/quick16",
        data: JSON.stringify(userList),
        contentType: 'application/json;charset=utf-8'
    });
</script>
</body>
</html>

But when accessing this jsp file, I found jquery-3.6.0 JS is not loaded

This is because the URL pattern of DispatcherServlet, the front-end controller of spring MVC, is configured with /, which represents the operation of all resources

That is to say, the original request was to find JS / jquery-3.6.0 J this file, but spring MVC thinks it is to find a resource similar to @ RequestMapping(value = "/ quick15"), so the match cannot be found

Therefore, you can specify the release of static resources in the following two ways:

  • In spring MVC Specify the released resources in the XML configuration file
<mvc:resources mapping="/js/**" location="/js/"/>
  • Hand it over to tomcat for processing

    <mvc:default-servlet-handler/>
    
    • This xml configuration means that when looking for resources, first find the matching address in @ RequestMapping. If it cannot be found, then give it to the original container tomcat. tomcat does not intercept, so the corresponding static resources can be found
    @RequestMapping(value = "/quick16")   //Request mapping
    @ResponseBody
    public void quickMethod16(@RequestBody List<User> userList){
        System.out.println(userList);
    }

5. Request data garbled

When using post request, if the input is Chinese, the console output will be garbled. At this time, we can XML sets a filter to filter the encoding

  <!--Configuring global filtering filter-->
  <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>
        <!--Works for any resource-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

6. Parameter binding annotation @ requestParam

In projects where the front and back ends are separated, it is inevitable that the name given to an input by the front-end engineer is different from the formal parameter name given to the corresponding Controller by the back-end engineer

At this time, @ requestParam can be used for parameter binding

  • value: request parameter name
  • required: whether the specified request parameters are included. The default is true. If there is no such parameter during submission, an error will be reported
  • defaultValue: when no request parameter is specified, the specified default value is used for assignment
    @RequestMapping(value = "/quick17")   //Request mapping
    @ResponseBody
    public void quickMethod17(@RequestParam(value = "name", required = false, defaultValue = "kang") String userName){
        System.out.println(userName);
    }

7. Get Restful style parameters (understand)

Restful is a software architecture style and design style, not a standard, but provides a set of design principles and constraints. It is mainly used for the interactive software between client and server. The software designed based on this style can be more concise, more hierarchical, and easier to implement the cache mechanism.

Restful style requests use "url + request method" to express a purpose. The four verbs in HTT protocol to express the operation mode are as follows:

  • GET: used to GET resources
  • POST: used to create a new resource
  • PUT: used to update resources
  • DELETE: used to DELETE resources

For example:

  • /user/1 GET: get user with id=1
  • /user/1 DELETE: delete the user with id=1
  • /user/1 PUT: update user with id=1
  • /user POST: new user

1 in the above url address / user/1 is the request parameter to be obtained. In spring MVC, placeholders can be used for 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 match and obtain placeholders.

    @RequestMapping(value = "/quick18/{username}")   //Request mapping
    @ResponseBody
    public void quickMethod18(@PathVariable(value = "username") String userName){
        System.out.println(userName);
    }

8. Custom type converter

Spring MVC has provided some common type converters by default, such as converting the string submitted by the client into int for parameter setting.

However, not all data types are provided with converters. If not, custom converters are required. For example, custom converters are required for date type data.

Development steps of custom type converter:

  1. Define the Converter class and implement the Converter interface

    package com.kang.converter;
    
    import org.springframework.core.convert.converter.Converter;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @ClassName DataConverter
     * @Description TODO
     * @Author kang
     * @Date 2022/2/27 2:18 PM
     * @Version 1.0
     */
    public class DataConverter implements Converter<String, Date> {
        @Override
        public Date convert(String s) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = simpleDateFormat.parse(s);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
    }
    
  2. Declare converter in configuration file

        <!--The converter is declared in the configuration file-->
        <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <bean class="com.kang.converter.DataConverter"></bean>
                </list>
            </property>
        </bean>
    
  3. Reference the converter in < annotation driven >

    <!--Annotation driven-->
    <mvc:annotation-driven conversion-service="converterService"/>

9. Get request header

9.1, @RequestHeader

Using @ RequestHeader, you can get the request header information, which is equivalent to the request learned in the web stage The attributes of the getheader (name) @ RequestHeader annotation are as follows:

  • value: the name of the request header
  • required: whether this request header must be carried
    @RequestMapping(value = "/quick21")   //Request mapping
    @ResponseBody
    public void quickMethod21(@RequestHeader(value = "User-Agent", required = false) String userAgent){
        System.out.println(userAgent);
    }

9.2, @CookieValue

Use @ Cookie value to get the value of the specified Cookie. The properties of @ Cookie value annotation are as follows:

  • value: Specifies the name of the cookie
  • required: do you have to carry this cookie
    @RequestMapping(value = "/quick22")   //Request mapping
    @ResponseBody
    public void quickMethod22(@CookieValue(value = "JSESSIONID", required = false) String cookie){
        System.out.println(cookie);
    }

10. Implementation of file upload

We can often see files that need to be uploaded in the web page

Principle of file upload:

  • When the form is modified to a multi part form, request Getparameter() will fail.

  • When enctype = "application/x-www-form-urlencoded", the format of the body content of the form is:

    key=value&key=value&key=value

  • When the enctype value of the form is mutilpart / form data, the content of the request body becomes multi part:

When it is set as a multi part form, it is no longer in the form of key value pairs, so data cannot be obtained through the getParameter() method

10.1 upload steps of single file

  • Import fileupload and io coordinates
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
  • Profile upload parser
    <!--File upload parser-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--Total size of uploaded files-->
        <property name="maxInMemorySize" value="5242800"/>
        <!--Upload the size of a single file-->
        <property name="maxUploadSizePerFile" value="5242800"/>
        <!--Code type of uploaded file-->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
  • Write file upload code
    @RequestMapping(value = "/quick23")   //Request mapping
    @ResponseBody
    public void quickMethod23(String name, MultipartFile uploadFile) throws IOException {
        //Get file name
        String originalFilename = uploadFile.getOriginalFilename();
        //Save file
        uploadFile.transferTo(new File("F:\\Note taking\\File upload test\\" + originalFilename));
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
        name<input type="text" name="username"><br>
        file<input type="file" name="uploadFile"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

10.2 realization of multi file upload

You can use arrays to implement

    @RequestMapping(value = "/quick24")   //Request mapping
    @ResponseBody
    public void quickMethod24(String name, MultipartFile[] uploadFile) throws IOException {
        for (MultipartFile multipartFile : uploadFile) {
            //Get file name
            String originalFilename = multipartFile.getOriginalFilename();
            //Save file
            multipartFile.transferTo(new File("F:\\Note taking\\File upload test\\" + originalFilename));
        }
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/quick24" method="post" enctype="multipart/form-data">
        name<input type="text" name="username"><br>
        File 1:<input type="file" name="uploadFile"><br>
        Document 2:<input type="file" name="uploadFile"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Keywords: Java Spring Back-end Spring MVC SSM

Added by robin339 on Fri, 04 Mar 2022 15:45:35 +0200