Spring series SpringMVC request and data response

SpringMVC data response

The way the data responds

Y The following cases are deployed on Tomcat and implemented using a browser to access a simple success.jsp page

The success.jsp page code

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<H1>Success</H1>
</body>
</html>
Copy the code

1. Page jump directly returns string to return Model and View Model

2. Write back data directly return string returns object or collection

Configure the internal view resource parser in spring-mVC.xml

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/web/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property></bean>
Copy the code

1. The page is displayed

1.1 Directly Returns a character string

This is the easy one

@Controller
public class Usercontroller {
    @RequestMapping(value = "/quick2")
    public String save2(a){
        System.out.println("Controller save running!!);
        return "/success.jsp"; }}Copy the code

The results of

1.2 Return to Model and View models

Methods a

@Controller
public class Usercontroller {
   @RequestMapping(value = "/quick3")
    public ModelAndView save3(a){
        /* Create Modelandview object */
        /* * model is used to encapsulate data * view model is used to display data * */
        ModelAndView modelAndView = new ModelAndView();
        /* Encapsulates data */
        modelAndView.addObject("Data"."This is data" );
       /* Sets the view name */
        modelAndView.setViewName("success");
        /* Return model and View*/
        returnmodelAndView; }}Copy the code

The success.jsp page code

<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > title < / title > < / head > < body > < % - to obtain the model encapsulates the Data - % > < H1 > Success ${Data} < / H1 > < / body > < / HTML >Copy the code

Effect of the page

Method two is automatically injected by the Spring framework

The difference between this method and the previous one is that instead of creating the ModelandView object ourselves, the Spring framework will inject it for us

@Controller
public class Usercontroller {
   @RequestMapping(value = "/quick4")
    public ModelAndView save4(ModelAndView modelAndView){

        /* Encapsulates data */
        modelAndView.addObject("Data"."This is data" );
        /* Sets the view name */
        modelAndView.setViewName("success");
        /* Return model and View*/
        returnmodelAndView; }}Copy the code

Method three uses the native HttpServletRequest object directly

@Controller
public class Usercontroller {
  
   @RequestMapping(value = "/quick5")
    public String save4(HttpServletRequest request){
        /* Encapsulates data */
       request.setAttribute("Data"."This is data");
        return "success"; }}Copy the code

1.3 Writing Back A String Does not Jump

Method 1: The Response object injected by SpringMVC framework uses Response.getwriter ().print(” Hello world “) to write back data, without view jump.

@Controller
public class Usercontroller {
  @RequestMapping(value = "/quick6")
    public void save6(HttpServletResponse response) throws IOException {
        response.getWriter().println("This is save write"); }}Copy the code

Method 2: Return the string that needs to be written back directly, but in this case, the @responseBody annotation tells the SpringMVC framework that the string returned by the method is not a jump but is returned directly from the BODY of the HTTP response

@Controller
public class Usercontroller {
  @RequestMapping(value = "/quick6")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save6(HttpServletResponse response) throws IOException {
       return  "This is save write"; }}Copy the code

Results:

4. Write back a string in JSON formatManual concatenation of JSON-formatted strings is very troublesome. In development, complex Java objects are often converted into JSON-formatted strings. We can use Jackson, the JSON conversion tool we learned in the Web stage, to convert JSON-formatted strings and write back strings

@Controller
public class Usercontroller {
   @RequestMapping(value = "/quick7")
   /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public String save7(a) throws IOException {
        User user = new User();
        user.setAge(11);
        user.setName("Lisi");
        // Use the Jason conversion tool to convert the object to JSON format
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        returnjson; }}Copy the code

5.SpringMVC’s data response – writes back data – returns an object or collection

The following configuration is done in spring-mVC.xml using the configuration file

<bean class="org.springframework.web.servlet.mvc.method.annotation .RequestMappingHandlerAdapter"> 
                <property name="messageConverters">       
                 <list>           
                  <bean class="org.springframework.http.converter.json .MappingJackson2HttpMessageConverter">
            </bean>    
                </list>  
                  </property>
                  </bean>
Copy the code
@RequestMapping("/quick8")
@ResponseBodypublic User quickMethod8(a) throws IOException
 {   
  User user = new User();  
   user.setUsername("zhangsan");   
    user.setAge(18);    
    returnuser; }Copy the code

Adding @responseBody to the annotated method returns a JSON string, but this configuration is cumbersome and requires a lot of code, so we can use MVC annotated driver instead.

In the various components of SpringMVC, the processor mapper, processor adapter, and view parser are called the three components of SpringMVC. Using MVC: annotation – driven automatic loading RequestMappingHandlerMapping mapper (processing) and RequestMappingHandlerAdapter adapter (processing), You can use MVC :annotation-driven instead of the annotation processor and adapter configuration in the spring-xml. XML configuration file. With MVC: Annotation-Driven, the default underlying layer integrates Jackson to convert objects or collections to JSON-formatted strings.

The way SpringMVC gets data requests

The format of the client request parameters is: name= Value&Name =value… …

In order for the server side to obtain the parameters of the request, and sometimes to encapsulate the data,SpringMVC can receive the following types of parameters: basic type parameters POJO type parameters array type parameters collection type parameters

支那

1. Get the parameters of the base data type

** : The parameter name of the business method must be the same as the name of the request parameter, and the parameter value will be mapped automatically

Case: access url: http://localhost:8080/spring/quick8? username=zhangsan&age=14

Business method code

@RequestMapping(value = "/quick8")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save8(String username,int age) throws IOException {
        System.out.println(username);
        System.out.println(age);
    }
Copy the code

Server output The request parameters were successfully obtained

支那

2.POJO type parameters

* * POJO business method parameters of the Controller of the property name in accordance with the request parameter name, parameter values will automatically map matching, automatically wrapped in an entity class to access the url path of: http://localhost:8080/spring/quick8? Username =zhangsan&age=14 Entity class code

package com.pjh.User;

public class User {
    private int age;
    private String name;

    public User(a) {}@Override
    public String toString(a) {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\' ' +
                '} ';
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

Business method code in the Controller class code

@RequestMapping(value = "/quick9")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save9(User user) throws IOException {
        System.out.println(user);
    }
Copy the code

Server side output

Array of business method type parameters of the Controller parameter names should be in line with the request parameter name, parameter will automatically map matching sample access url: http://localhost:8080/spring/quick10? str=aaa&str=bbb&str=ccc

Business method code in Controller

 @RequestMapping(value = "/quick10")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save10(String [] str) throws IOException {
       
        System.out.println(Arrays.asList(str));
    }
Copy the code

Server output

支那

3. Set type parameters

** The collection parameters are captured in a POJO

Use a form submission example to demonstrate JSP page user submission data

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/quick11" 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="Submit the form">
</form>
</body>
</html>
Copy the code

The user class code

package com.pjh.User;

public class User {
    private int age;
    private String username;

    @Override
    public String toString(a) {
        return "User{" +
                "age=" + age +
                ", username='" + username + '\' ' +
                '} ';
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username; }}Copy the code

Vo class code that encapsulates List

package com.pjh.User;

import java.util.List;

public class VO {
    private List<User> userList;

    @Override
    public String toString(a) {
        return "VO{" +
                "userList=" + userList +
                '} ';
    }

    public List<User> getUserList(a) {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList; }}Copy the code

Business methods in Controller

@RequestMapping(value = "/quick11")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save11(VO vo) throws IOException {
        System.out.println(vo);
    }
Copy the code

Information submitted in the browser

Client output

支那

4. Garbled characters will appear when we submit Chinese data with the form. At this time, we need to configure a filter for encoding filtering, which is also configured in web.xml

** configuration code

<! <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <! -- Configuration parameter encoding type --> <init-param>
        <param-name>encoding</param-name>
        <param-value>utf- 8 < /param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name> <! -- Filter at any time of access --> <url-pattern/ * < / >url-pattern>
    </filter-mapping>
Copy the code

支那

5. When submitting with Ajax, you can specify the contentType as JSON, so using @RequestBody in the method argument position accepts the collection data directly without wrapping it with a POJO

支那

Before the filtering

The filtered

Business method code in the Controller class

@RequestMapping(value = "/quick13")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save13(@RequestBody List<User> userList) throws IOException {
        System.out.println(userList);
    }
Copy the code

JSP code to access the business method

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> </title> <% --%> <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
    <script>
        var array = new  Array();
        array.push({username:"zhangsan",age:"14"});
        array.push({username:"lisi",age:"12"});
        $.ajax({
           type:"POST",
            url:"${pageContext.request.contextPath}/quick13",
            data:JSON.stringify(array),
            contentType:'application/json; charset=utf-8'
        });
    </script>
</head>
<body>
<h1>ajax2</h1>
</body>
</html>
Copy the code

If you want to use another version of jquery, you can find it at www.jq22.com/jquery-info… If your script does not jump to the specified business method, it is probably due to jquery problems. Use Google developer tools to see if the status is 200

When static resources need to be loaded, such as jquery files, if the url pattern of SpringMVC’s DispatcherServlet is set to /, which means that all resources are filtered, we can specify static resources in the following two ways:

Method 2: Specify the permitted resources in the spring-mVC.xml configuration file

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

Method 1: Let Tomcat find the files for us

<mvc:default-servlet-handler/>
Copy the code

支那

The use of @requestParam annotations

** @requestParam also has the following parameters to use: value: specifies the name of the request parameter. When this is configured, the parameter name in the method can be configured at will, and does not need to be the name of the request parameter required: DefaultValue: when no request parameter is specified, an example is assigned using the defaultValue specified

 @ResponseBody
    public void save14(@requestParam (value = "name", Required = false,defaultValue = "wang ") String username) throws IOException {
        System.out.println(username);
    }
Copy the code

支那

Restful style parameters

支那

Restful is an architectural style. Restful is a design style, not a standard, but provides a set of design principles and constraints. Mainly used for client and server interaction class software, based on this style of design software can be more concise, more hierarchical, easier to implement caching mechanisms, etc

A Restful request uses URL + request mode to indicate the purpose of a request. In HTTP, there are four verbs that indicate the operation mode: GET: to obtain resources. POST: to create resources

For example, /user/1 GET: obtains the user/ user/1 whose ID is 1. DELETE: deletes the user/ user/1 whose ID is 1. PUT: updates the user/ user whose ID is 1

Gets restful style parameters

The 1 in the url /user/1 above is the request parameter to get, which can be bound using placeholders in SpringMVC. The address /user/1 can be written as /user/{id}, and the placeholder {id} corresponds to the value of 1. In business methods we can use the @pathVariable annotation for placeholder matching retrieval

 @RequestMapping(value = "/quick15/{name}")
    /* Tells the SpringMvc framework that the string returned by the method is not a jump but returns */ directly in the BODY of the HTTP response
    @ResponseBody
    public void save15(@PathVariable(value = "name" ,required = false) String username) throws IOException {
        System.out.println(username);
    }
Copy the code

{name} in the above code is the placeholder, and the value in the @pathVariable annotation should be the same as the name in the placeholder

支那

7. Custom type converter

支那

SpringMVC already provides some common type converters by default, such as converting client-submitted strings to ints for parameter Settings. However, not all data types provide converters, and those that do not need a custom converter, for example, date-type data requires a custom converter.

The development steps of a custom Converter are as follows: 1. Define Converter classes to implement Converter interface 2. Declare converters in configuration files. 3. Reference converters in

1. Define Converter classes to implement the Converter interface

package com.pjh.Converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DataConvert implements Converter<String.Date> {
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        returnparse; }}Copy the code

2. Declare the converter in the configuration file

<bean id="ConversionServiceConverter" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.pjh.Converter.DataConvert"/>
        </list>
    </property>
    </bean>
Copy the code

3. Reference the converter in

 <mvc:annotation-driven conversion-service="ConversionServiceConverter"/>
Copy the code

支那

8. Get the request header

支那

The @cookievalue annotation has the following attributes: value: Specifies the name of the Cookie required: Specifies whether the Cookie must be carried

Get cookies, annotated specifically

RequestMapping("/quick18")
@ResponseBody
public void quickMethod18( @CookieValue(value = "JSESSIONID",required = false) String jsessionid)
{    
System.out.println(jsessionid);
}
Copy the code

Obtaining user-agent No

@RequestMapping("/quick17")
@ResponseBody
public void quickMethod17(        @RequestHeader(value = "User-Agent",required = false) String headerValue)
{    
System.out.println(headerValue);
}
Copy the code

This is the second chapter of SpringMVC series, which focuses on the operation of SpringMVC request and data response. I will continue to update SpringMVC series courses in the future. This blog mainly focuses on data structure, algorithm and Java development. Meet is fate, we see high