SpringMVC data request

5. SpringMVC data request

5.1-SpringMVC request-obtain request parameters-request parameter type (understanding)

The format of the client request parameter is: name=value&name=value...

To obtain the requested parameters on the server side, sometimes data encapsulation is required. SpringMVC can receive the following types of parameters

  • primitive type parameters

  • POJO type parameters

  • Array type parameter

  • collection type parameters

5.2-SpringMVC request - get request parameters - get basic type parameters (application)

The parameter name of the business method in the Controller must be consistent with the name of the request parameter, and the parameter value will be automatically mapped and matched. And can automatically do type conversion;

Automatic type conversion refers to the conversion from String to other types

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

    @RequestMapping(value="/login11")
    @ResponseBody
    public void login11(String uname,int age) throws IOException {
    
    
        System.out.println(name);
        System.out.println(age);
    }

5.3-SpringMVC request - get request parameters - get POJO type parameters (application)

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.

public class User {
    
    

    private String username;
    private int age;

    public String getUsername() {
    
    
        return username;
    }

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

    public int getAge() {
    
    
        return age;
    }

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

    @Override
    public String toString() {
    
    
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}
//获取请求数据
@RequestMapping(value="/login12")
    @ResponseBody
    public void login12(User user) throws IOException {
    
    
        System.out.println(user);
    }

5.4-SpringMVC request-get request parameters-get array type parameters (application)

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

@RequestMapping(value="/login13")
    @ResponseBody
    public void login13(String[] strs) throws IOException {
    
    
        System.out.println(Arrays.asList(strs));
    }

5.5-SpringMVC request-get request parameters-get collection type parameter 1 (application)

When obtaining the collection parameters, it is only possible to wrap the collection parameters into a POJO.

<form action="${pageContext.request.contextPath}/user/login14" method="post">
        <%--表明是第一个User对象的username age--%>
        <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="提交">
    </form>
import java.util.List;

public class VO {
    
    

    private 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 +
                '}';
    }
}
//获取请求数据
@RequestMapping(value="/login14")
    @ResponseBody
    public void login14(VO vo) throws IOException {
    
    
        System.out.println(vo);
    }

5.6-SpringMVC request-get request parameters-get collection type parameter 2 (application)

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

<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
    <script>
        var userList = new Array();
        userList.push({
      
      username:"zhangsan",age:18});
        userList.push({
      
      username:"lisi",age:28});

        //ajax请求
        $.ajax({
      
      
            type:"POST",
            url:"${pageContext.request.contextPath}/user/login15",
            data:JSON.stringify(userList),
            contentType:"application/json;charset=utf-8"
        });

    </script>
//获取请求数据
@RequestMapping(value="/login15")
    @ResponseBody
    public void login15(@RequestBody List<User> userList) throws IOException {
    
    
        System.out.println(userList);
    }

5.7-SpringMVC request-obtain request parameters-open static resource access (application)

When there are static resources that need to be loaded, such as jquery files, it is found that the jquery files are not loaded through Google developer tools. The reason is that the url-pattern configuration of SpringMVC's front controller DispatcherServlet is /, which means that all resources For filtering operations, we can specify the release of static resources in the following two ways:

• Specify released resources in the spring-mvc.xml configuration file

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

• Use <mvc:default-servlet-handler/>labels

 <!--开放资源的访问权限
    mapping:是服务端访问资源的地址
    location:是具体资源的路径
    -->
    <!--<mvc:resources mapping="/js/**" location="/js/"/>-->

    <!--springMVC找不到资源,就交给原始的容器的内部机制找资源-->
    <mvc:default-servlet-handler/>

5.8-SpringMVC request-obtain request parameters-configure global garbled filter (application)

When the post request, the data will be garbled, we can set a filter to filter the encoding.

<!--配置全局过滤的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>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

5.9-SpringMVC request-obtain request parameters-parameter binding annotation @RequestParam (application)

When the parameter name of the request is inconsistent with the name of the business method parameter of the Controller, the binding displayed by the @RequestParam annotation is required

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

@RequestMapping(value="/login16")
    @ResponseBody
    public void login16(@RequestParam(value="name",required = false,defaultValue = "NanYu") String username) throws IOException {
    
    
        System.out.println(username);
    }

5.10-SpringMVC request-obtain request parameters-obtain restful style parameters (application)

Restful is a software architectural style and design style, not a standard, but a set of design principles and constraints. It is mainly used for software that interacts between client and server. Software designed based on this style can be more concise, 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 that indicate the operation method are as follows:

  • GET: used to obtain resources

  • POST: used to create new resources

  • PUT: used to update resources

  • DELETE: used to delete resources

For example:

  1. /user/1 GET : get user with id = 1

  2. /user/1 DELETE: delete user with id = 1

  3. /user/1 PUT: update user with id = 1

  4. /user POST: add new user

The 1 in the above url address /user/1 is the request parameter to be obtained. In SpringMVC, 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 the placeholder.

http://localhost:8080/NanYu/login17/zhangsan

@RequestMapping(value="/login17/{name}")
@ResponseBody
 public void login17(@PathVariable(value="name") String username) throws IOException {
    
    
        System.out.println(username);
 }

5.11-SpringMVC request-obtain request parameters-custom type converter (application)

SpringMVC has provided some commonly used type converters by default, such as converting the string submitted by the client to int type for parameter setting.

However, not all data types provide converters, and those that are not provided need custom converters. For example, data of date type requires custom converters.

public class DateConverter implements Converter<String, Date> {
    
    
    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;
    }
}
@RequestMapping(value="/login18")
    @ResponseBody
    public void login18(Date date) throws IOException {
    
    
        System.out.println(date);
    }

5.12-SpringMVC request - get request parameters - get Servlet related API (application)

SpringMVC supports injection using the original ServletAPI object as a parameter of the controller method. The commonly used objects are as follows:

  • HttpServletRequest

  • HttpServletResponse

  • HttpSession

@RequestMapping(value="/login19")
    @ResponseBody
    public void login19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
    
    
        System.out.println(request);
        System.out.println(response);
        System.out.println(session);
    }

5.13-SpringMVC request - get request parameters - get request header information (application)

Use @RequestHeader to get request header information, which is equivalent to request.getHeader(name) learned in the web stage

  • The attributes of the @RequestHeader annotation are as follows:

  • value: the name of the request header

  • required: Whether this request header must be carried

@RequestMapping(value="/login20")
    @ResponseBody
    public void login20(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
    
    
        System.out.println(user_agent);
    }

Use @CookieValue to get the value of the specified cookie

  • The attributes of the @CookieValue annotation are as follows:

  • value: specifies the name of the cookie

  • required: whether to carry this cookie

 @RequestMapping(value="/login21")
    @ResponseBody
    public void login21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
    
    
        System.out.println(jsessionId);
    }

Guess you like

Origin blog.csdn.net/qq_64071654/article/details/128422820