Spring MVC learning summary (two): Spring MVC parameter acquisition method

One, @RequestMapping annotation

     RequestMapping is an annotation used to process request address mapping. Spring MVC uses the @RequestMapping annotation to specify which URL requests can be processed by the controller. When the DispatcherServlet intercepts the request, it determines the processing method corresponding to the request through the mapping information provided by @RequestMapping on the controller.

      Use location: in the controller's class definition and method

     Class definition office : Provides preliminary request mapping information. Relative to the root directory of the web application, it means that all methods in the class that respond to requests use this address as the parent path.

      Method : Provide further subdivision mapping information. Relative to the URL where the class is defined. If @RequestMapping is not marked in the class definition, the URL marked in the method is relative to the root directory of the web application.

@RequestMapping has six attributes, which are described as follows:

(1) Value: Specify the actual address of the request, the specified address can be a specific address, it can be dynamically obtained by RestFul, or it can be set by regular.

@Controller
@RequestMapping(value = "/user")        //RequestMapping用来类上
public class UserController {
    //RequestMapping用来方法上
    @RequestMapping(value = "/login")
    public void  login(){

    }
}

(2) Method: Specify the method type of the request, such as GET, POST, PUT, DELETE, etc. as follows:

    /**
     *  请求的method必须是get
     */
    @RequestMapping(value = "/test01", method = RequestMethod.GET)
    public void test01(){
        System.out.println("get方式访问");
    }
    /**
     *  请求的method必须是delete
     */
    @RequestMapping(value = "/test02", method = RequestMethod.DELETE)
    public void test02(){
        System.out.println("delete方式访问");
    }

(3) params: specifies the parameter values ​​that must be included in the request when the page initiates a request.

Some simple expression operations on params:

param: The request parameter of param must be included in the request.

!param: The request parameter of param must not be included in the request.

param!=value; the value of param in the request must not be value.

{"Param1=value1","param2"}: The request must contain the request parameters of param1 and param2, and the value of param1 must be value1.

Examples are as follows:

    @RequestMapping(value = "/paramTest01", params = "username")
    public void paramTest01(){
        System.out.println("参数中必须包含username的请求参数");
    }
    @RequestMapping(value = "/paramTest02", params = "username=tom")
    public void paramTest02(){
        System.out.println("参数中必须包含username的请求参数,并且值必须为tom");
    }
    @RequestMapping(value = "/paramTest03", params = "!address")
    public void paramTest03(){
        System.out.println("参数中必须不包含address的请求参数");
    }
    @RequestMapping(value = "/paramTest04", params = {"username=tom","age"})
    public void paramTest04(){
        System.out.println("参数中必须包含username和age的两个请求参数,并且username的值必须为tom");
    }

(4) headers: specifies the header values ​​that must be included in the request when the page initiates a request.

      Example: Use User-Agent to specify that the browser can be accessed only when the browser is Firefox.

    @RequestMapping(value = "/testHeader", headers = {"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0"})
    public void testHeader(){
        System.out.println("火狐浏览器才能访问");
    }

(5) Consumes: Specify the content type (Content-Type) of the submitted processing request, such as application/json, text/html.

(6) Produces: Specify the type of content returned, and only return if the specified type is included in the (Accept) type in the request header.

Second, get the annotations of request parameters in Spring

1. @PathVariable annotation

(1) Introduction: @PathVariable is a new feature of Spring3.0, which is used to receive the value of the placeholder in the request path. It only supports one attribute value, the type is String, which represents the name of the bound attribute. When it is not passed by default, it is bound to a formal parameter with the same name. 

(2) Syntax: @PathVariable("xxx") Through @PathVariable, the placeholder parameter {xxx} in the URL can be bound to the method parameter of the processor class

(3) Case

<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/pathVariable01/3">@PathVariable指定URL变量名</a>
<a href="${pageContext.request.contextPath}/pathVariable01/tom/18k">@PathVariable定义多个URL变量</a>
</body>
</html>

 

    /**
     * @PathVariable指定URL变量名
     * @param id
     * @return
     */
    @RequestMapping(value = "/pathVariable01/{id}")
    public String pathVariable01(@PathVariable("id") Integer id){
        System.out.println(id);
        return "success";
    }

    /**
     * 定义多个URL变量
     * @param name
     * @param age
     * @return
     */
    @RequestMapping(value = "/pathVariable01/{name}/{age}")
    public String pathVariable02(@PathVariable(value = "name") String name, @PathVariable(value = "age") Integer age){
        System.out.println("name is : " + name + ", age is : " + age);
        return "success";
    }

 note:

a. The url requested in index.jsp should be written as:

      <a href="${pageContext.request.contextPath}/pathVariable01/3">@PathVariable指定URL变量名</a>

      Wrong wording:

      <a href="${pageContext.request.contextPath}/pathVariable01/{3}">@PathVariable指定URL变量名</a>

b. The value of PathVariable must be the same as the input parameter name of the method.

2. @RequestParam annotation

(1) Introduction : This annotation is used in Spring MVC to receive the parameter information carried when the user initiates a request, and is used in the method of processing the request in the controller.

(2) Grammar :

@RequestParam(value = "parameter name", required = true/false, defaultValue = "default value"

Equivalent to request.getParameter("parameter name") in Servlet;

Parameter introduction:

value: parameter name

required: Whether this parameter is required when the user initiates a request, true means that this parameter must be carried, and false means that it is not necessary. The default value is true.

defaultValue: The default value of this parameter, or null if it is not specified.

Example:

@RequestParam(value = "name", required = false, defaultValue = "tom"

Equivalent to: username = request.getParameter("name");

Note: The user needs to carry the name parameter when initiating a request, but it can also be omitted. When the value is not assigned, the default value is tom.

(3) Case

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/request01?name=tom">用户请求携带name参数</a>
<a href="${pageContext.request.contextPath}/request02?name=Jerry">name参数必须有</a>
<a href="${pageContext.request.contextPath}/request03?name=Mack">系统默认方式获取参数</a>
</body>
</html>

RequestTestController:

@Controller
public class RequestTestController {

    /**
     * 普通写法:用户发起请求时携带name参数
     * @param name 用户名
     * @return
     */
    @RequestMapping(value = "/request01")
    public String request01(@RequestParam("name") String name){
        System.out.println(name);
        return "success";
    }

    /**
     * 用户发起请求时必须携带name参数,如果name为null,则其默认值为tom
     * @param username
     * @return
     */
    @RequestMapping(value = "/request02")
    public String request02(@RequestParam(value = "name", required = true, defaultValue = "tom") String username){
        System.out.println(username);
        return "success";
    }
    /**
     * 系统默认方式获取请求参数:直接给方法的入参上写一个和请求参数名称相同的变量,这个变量就用来接收请求参数的值
     * 若有值则为用户指定的值,若无值则为Null。
     * @param name
     * @return
     */
    @RequestMapping(value = "/request03")
    public String request03(String name){
        System.out.println(name);
        return "success";
    }
}

Note: The system defaults to obtain the request parameter. You can directly write a variable with the same name as the request parameter to the input parameter of the method to get this value. If the RequestParam annotation is used, the input parameter of the method and the parameter name of the request can be inconsistent. Refer to the requesto2 method in the above example.

(4) The difference between RequestParam and PathVariable

Similarities : Both RequestParam and PathVariable are used to process the request parameters passed by the front end.
Differences: RequestParam processes the request parameters, mapping the request parameter values ​​under the corresponding request path to the processor parameters. PathVariable deals with path variables, and maps the value of the requested path variable to the processor parameters.

for example:

If the request is /user?name=tom, the key-value after? Is obtained by RequestParam, and the parameter value is obtained by entering the parameter in the Controller.

If the request is /user/{name}, PathVariable gets the value of the placeholder on the path, which is the value of {name}.

3. @RequestHeader annotation

(1) Introduction: Get the header information of the request.

(2) Grammar:

@RequestHeader(value = "parameter name", required = true/false, defaultValue = "default value"

Equivalent to request.getHeader("parameter name") in Servlet;

Example:

@RequestHeader("User-Agent")

Equivalent to: userAgent = request.getHeader("User-Agent");

Parameter introduction:

value: parameter name

required: Whether this parameter is required when the user initiates a request, true means that this parameter must be carried, and false means that it is not necessary. The default value is true.

defaultValue: The default value of this parameter, or null if it is not specified.

(3) Case

<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/requestHeader01">@RequestHeader使用1</a>
<a href="${pageContext.request.contextPath}/request02">@RequestHeader使用2</a>
</body>
</html>
    @RequestMapping(value = "/requestHeader01")
    public String requestHeader01(@RequestHeader("User-Agent") String userAgent){
        System.out.println(userAgent);
        return "success";
    }
    @RequestMapping(value = "/requestHeader02")
    public String requestHeader02(@RequestHeader(value = "User-Agent", required = false) String userAgent){
        System.out.println(userAgent);
        return "success";
    }

 4. @CookieValue annotation

(1) Introduction: Map the requested cookie data to the parameters of the function processing method.

(2) Grammar

@CookieValue(value = "parameter name", required = true/false, defaultValue = "default value"

Writing in Servlet:

Cookie[] cookies = request.getCookies();
for(Cookie c : cookies){
    if(c.getName().equals("cookieName")){
        String value = c.getValue();
    }
}

Example:

@CookieValue("JSESSIONID")

Equivalent to:

Cookie[] cookies = request.getCookies();
for(Cookie c : cookies){
    if(c.getName().equals("JSESSIONID")){
        String value = c.getValue();
    }
}

Parameter introduction:

value: parameter name

required: Whether this parameter is required when the user initiates a request, true means that this parameter must be carried, and false means that it is not necessary. The default value is true.

defaultValue: The default value of this parameter, or null if it is not specified.

(3) Case

<a href="${pageContext.request.contextPath}/getCookie">@CookieValue使用</a>
    @RequestMapping(value = "/getCookie")
    public String getCookie(@CookieValue("JSESSIONID") String cookieVal){
        System.out.println(cookieVal);
        return "success";
    }

 5. The use of POJO objects in Spring MVC

      I introduced several ways to obtain parameters in Spring MVC, but when there are too many parameters, this one-to-one correspondence will appear to be messy in the code. To solve this problem, you need to use POJO for multi-parameter encapsulation. Spring MVC will automatically match the request parameter name and the POJO attribute name, and automatically fill in the attribute value for the object (through the set method of the attribute) . Use as follows:

(1) Create a form in index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/pojoUse">
    姓名: <input type="text" name="name"><br>
    性别: <input type="text" name="sex"><br>
    年龄: <input type="text" name="age"><br>
    电话: <input type="text" name="tel"><br>
    家庭住址: <input type="text" name="address"><br>
    <input type="submit" value="提交"><br>
</form>
</body>
</html>

 Note: The type of the submit button in the form should be submit. If the type is button, the background cannot be accessed. I was tossing here for a long time because of my own mistakes, only to discover the problem later.

(2) Create a Teacher object.

public class Teacher {
    private String name;
    private String sex;
    private String age;
    private String tel;
    private String address;

    public Teacher() {
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

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

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddress() {
        return address;
    }


    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age='" + age + '\'' +
                ", tel='" + tel + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

(3) Use POJO objects in Controller

    @RequestMapping(value = "/pojoUse", method = RequestMethod.POST)
    public String pojoUse(Teacher teacher){
        System.out.println(teacher);
        return "success";
    }

In addition, Spring MVC also supports cascading attributes . Now modify the above code.

(1) Add book information in the form.

<form method="post" action="${pageContext.request.contextPath}/pojoUse">
    姓名: <input type="text" name="name"><br>
    性别: <input type="text" name="sex"><br>
    年龄: <input type="text" name="age"><br>
    电话: <input type="text" name="tel"><br>
    家庭住址: <input type="text" name="address"><br>
    书名: <input type="text" name="book.bName"><br>
    作者: <input type="text" name="book.bAuthor"><br>
    价格: <input type="text" name="book.bPrice"><br>
    <input type="submit" value="提交"><br>
</form>

(2) Create the Book class.

public class Book {
    private String bName;
    private String bAuthor;
    private Double bPrice;

    public Book() {
    }

    public String getbName() {
        return bName;
    }

    public void setbName(String bName) {
        this.bName = bName;
    }

    public String getbAuthor() {
        return bAuthor;
    }

    public void setbAuthor(String bAuthor) {
        this.bAuthor = bAuthor;
    }

    public Double getbPrice() {
        return bPrice;
    }

    public void setbPrice(Double bPrice) {
        this.bPrice = bPrice;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bName='" + bName + '\'' +
                ", bAuthor='" + bAuthor + '\'' +
                ", bPrice=" + bPrice +
                '}';
    }
}

(3) Add Book property to Teacher, provide get and set methods, and override toSring().


    private Book book;


    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age='" + age + '\'' +
                ", tel='" + tel + '\'' +
                ", address='" + address + '\'' +
                ", book=" + book +
                '}';
    }
}

note:

a. There must be a non-parameter structure in the entity class.

b. The request parameter name must be consistent with the attribute name in the object.

c. In the above form, if you enter Chinese, the data received in the background will appear garbled.

Solution: Configure character encoding filter in web.xml.

  <!--   字符编码过滤器  -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--  encoding:指定一个具体的字符集  -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!-- forceEncoding:处理 response中的字符编码  -->
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
  </init-param>

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113005667