Section Xi - obtaining request data

1, The type of data that can be obtained from the client

  1. Basic type parameters
  2. POJO type parameter (JavaBean)
  3. Array type

2, Method of obtaining data

I. Basic data type - the parameter name of the business method in the controller is consistent with the parameter name sent, and MVC automatically matches the input
  1. Edit UserController.class in the main java study controller directory and define a method
@RequestMapping("/quick1")
    @ResponseBody
    public void show1(String name,int age) {
        System.out.println(name+age);
    }
  1. Start tomcat and access http://localhost:8080/demo03_ war/quick1? Name = qwe & age = 12, data obtained successfully
II. POJO data type - the parameter passed in is the attribute name of the class, and MVC automatically matches it into an object
  1. Define a student class. The properties of the class include name and age, and both getter and setter methods are defined
  2. The request parameter of a method in UserController.class is student type
@RequestMapping("/quick1")
    @ResponseBody
    public void show1(Student student) {
        System.out.println(student);
    }
  1. Start tomcat and access http://localhost:8080/demo03_ war/quick1? Name = qwe & age = 12, MVC successfully encapsulates the data into a Student object
III. array type - automatic matching
  1. The request parameter of a method in UserController.class is a string array and the name is str
  2. Start tomcat, pass in continuous parameters whose names are STR, and mvc will be automatically encapsulated into an array. URL: quick1? str=a&str=b&str=c
Ⅳ. Set type - by defining a class in which a list array of student type is defined, the parameter passed in by the client needs to indicate the attribute in the array
  1. Define a Vo class
public class VO {
    private List<Student> vo_list;

    public List<Student> getVo_list() {
        return vo_list;
    }

    public void setVo_list(List<Student> vo_list) {
        this.vo_list = vo_list;
    }

    @Override
    public String toString() {
        return "VO{" +
                "vo_list=" + vo_list +
                '}';
    }
}
  1. Define controller
@RequestMapping("/quick1")
    @ResponseBody
    public void show1(VO vo) {
        System.out.println(vo);
    }
  1. Define a test.jsp and pass the array through the table tag inside
<form action="${pageContext.request.contextPath}/quick1" method="post">
    <input type="text" name="vo_list[0].name" value="qwe"><br/>
    <input type="text" name="vo_list[0].age" value="12"><br/>
    <input type="text" name="vo_list[1].name" value="asd"><br/>
    <input type="text" name="vo_list[1].age" value="13"><br/>
    <input type="submit" value="Submit">
</form>
  1. Open tomcat, visit the jsp/test.jsp page, click the submit button to obtain the data
  2. Because quick1 needs the data of VO object, VO needs a list array of student type, and the array name is vo_list, so you need to specify consistent array names and attribute values when submitting data
V. collection type - when submitting using ajax, the json specified as contentType is obtained by MVC through @ RequestBody
  1. Create a new js directory under the webapp directory, and import jquery-3.3.1 into the js directory
  2. Edit spring-mvc.xml and add jquery
<mvc:resources mapping="/js/**" location="/js/"/>
perhaps
<mvc:default-servlet-handler/>
  1. Modify test.jsp
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
    <script>
        var user_list = new Array();
        user_list.push({username:"qwe",age:12})
        user_list.push({username:"asd",age:13})
        $.ajax({
           type:"POST",url:"${pageContext.request.contextPath}/quick1",
            data:JSON.stringify(vo_list),
            contentType:"application/json;charset=utf-8"
        });
    </script>
</head>
<body>
</body>
</html>
  1. Accept ajax data with @ RequestBody annotation
@RequestMapping("/quick1")
    @ResponseBody
    public void show1(@RequestBody List<Student> user_list) {
        System.out.println(user_list);
    }
Vi. solve the problem of garbled code in Chinese after POST
  1. Edit web.xml
<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>
VII. Use @ RequestParam annotation to solve the inconsistency between submission parameter name and method parameter
  1. Modify controller
@RequestMapping("/quick1")
    @ResponseBody
    public void show1(@RequestParam(value = "username") String name) {
        System.out.println(name);
    }
  1. When the page submits the username parameter, MVC converts it to name for encapsulation

3, Get data - Restful

  1. graphic

  2. Parameters submitted when accessing URL: http://localhost:8080/demo03_war/quick1/zhangsan

  3. Modify controller

@RequestMapping("/quick1/{name}")
    @ResponseBody
    public void show1(@PathVariable(value = "name",required = true) String username) {
        System.out.println(username);
    }
  1. Start tomcat access http://localhost:8080/demo03_war/quick1/zhangsan validation data

4, Get data - Custom conversion type

Premise: Although string can be converted to int, date and other data cannot be converted automatically and need to be configured manually

  1. Create DateConverter.class in the main java study converter directory
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date =null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
  1. Configure spring-mvc.xml
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="study.converter.DateConverter"/>
            </list>
        </property>
    </bean>
  1. Edit controller
@RequestMapping(value = "/quick1")
    @ResponseBody
    public void show1(Date date) {
        System.out.println(date);
    }
  1. Start tomcat and access: quick1?date=2021-10-04

Tags: Java Tomcat mvc

Posted on Mon, 04 Oct 2021 23:18:33 -0400 by maxf