Spring MVC @RequestParam annotation

Posted by sspphp on Mon, 03 Jan 2022 09:49:45 +0100

org. springframework. web. bind. The @ RequestParam annotation under the annotation package is used to assign the specified request parameter to the formal parameter in the method. So what are the attributes of the @ RequestParam annotation? It has four attributes, which will be introduced one by one below:
1. name attribute
The type of this attribute is String, which can specify the name of the request header binding;

2. value attribute
The type of this attribute is String, which can be set as an alias of the name attribute;

3. required attribute
The type of this attribute is boolean, which can set whether the specified parameter must be bound;

4. DefaultValue property
The type of this property is String, which can be set. If no parameters are passed, the default value can be used.

 

The optional types of request processing method parameters are 8 basic data types and String of Java. The following example pseudo code:

@RequestMapping(value="/hello")
public ModelAndView hello(
    @RequestParam("loginname") String loginname,
    @RequestParam("password") String password) {
    return...;
}

Suppose the request is as follows: http://localhost:8088/springmvc -comment1/login? loginname=qianch&password=123456
The above code will assign the value "qianch" of the loginname parameter in the request to the loginname variable and the value "123456" of the password parameter to the password variable.

 

The following will demonstrate the application of @ RequestMapping and @ RequestParam annotations through a case.
Create a package under "src/main/java" of the project. The package is called "com.qianchunhua.domain". Create a User class under the package. This class is a domain object, which is mainly used to encapsulate the data transmitted from the foreground page. The following code:

package com.qianchunhua.domain;

import java.io.Serializable;
// Domain object that implements the serialization interface
public class User implements Serializable{

    // Private field
    private String loginname;
    private String password;
    private String username;

    // Common constructor
    public User() {
        super();
    }

    // set/get method
    public String getLoginname() {
        return loginname;
    }
    public void setLoginname(String loginname) {
        this.loginname = loginname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

}

Create a UserController class under the "com.qianchunhua.controller" package just created. This class mainly simulates user registration. The code is as follows:

 

package com.qianchunhua.controller;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.qianchunhua.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

// Controller Annotations are used to indicate that the class is a controller that can handle multiple request actions at the same time
@Controller
// RequestMapping Can be used to annotate a controller class, where all methods are mapped to requests relative to the class level, 
// Indicates that all requests processed by the controller are mapped to value Property
@RequestMapping(value="/user")
public class UserController {   
    // static state List<User>Collection, which is used to save the registered user information instead of the database
    private static List<User> userList; 
    // UserController Class constructor, initialization List<User>aggregate
    public UserController() {
        super();
        userList = new ArrayList<User>();
    }
    // Static log class LogFactory
    private static final Log logger = LogFactory
            .getLog(UserController.class);

    // The request mapped by this method is http://localhost:8088/springmvc-comment1/user/register,This method supports GET request
    @RequestMapping(value="/register",method=RequestMethod.GET)
     public String registerForm() {
         logger.info("register GET Method called...");
         // Jump to the registration page
         return "registerForm";
     }

    // The request mapped by this method is http://localhost:8088/springmvc-comment1/user/register,This method supports POST request
     @RequestMapping(value="/register",method=RequestMethod.POST)
     // Place the in the request loginname The value of the parameter is assigned to loginname variable,password and username Same treatment
     public String register(
             @RequestParam("loginname") String loginname,
             @RequestParam("password") String password,
             @RequestParam("username") String username) {
         logger.info("register POST Method called...");
         // establish User object
         User user = new User();
         user.setLoginname(loginname);
         user.setPassword(password);
         user.setUsername(username);
         // Simulated database storage User information
         userList.add(user);
         // Jump to login page
         return "loginForm";
     }

    // The request mapped by this method is http://localhost:8088/springmvc-comment1/user/login
     @RequestMapping("/login")
     public String login(
            // Place the in the request loginname The value of the parameter is assigned to loginname variable,password Same treatment
             @RequestParam("loginname") String loginname,
             @RequestParam("password") String password,
             Model model) {
         logger.info("Login name:"+loginname + " password:" + password);
         // Find out whether the user exists in the collection. This is used to simulate database authentication
         for(User user : userList){
             if(user.getLoginname().equals(loginname) && user.getPassword().equals(password)) {
                 model.addAttribute("user",user);
                 return "welcome";
             }
         }
         return "loginForm";
     }

}

 

The code of UserController class is explained as follows:
(1) The UserController class uses the @ Controller annotation, which is a Controller class;
(2) The @ RequestMapping(value = "/ user") annotation is used on the UserController class to indicate that all requests processed by the controller are mapped to the user path;
(3) Originally, the database was not used to store user registration information, so a static List set userList was defined to store user data instead of the database;
(4) The registerForm method uses the @ RequestMapping(value = "/ register", method=RequestMethod.GET) annotation, indicating that the request mapped by this method is http://localhost:8088/springmvc-comment1/user/register, and only GET requests are supported. This method returns the string "registerForm", refer to springmvc config According to the configuration information in XML, you can know that this method just jumps to registerForm JSP registration page;
(5) The register method uses the @ RequestMapping(value = "/ register", method=RequestMethod.POST) annotation, indicating that the request mapped by this method is http://localhost:8088/springmvc-comment1/user/register, and only POST requests are supported. This method uses the @ RequestParam annotation to assign the specified request parameters to the formal parameters in the method, then creates a User object to save the registration information passed by the User, and finally stores the User object in the userList set. The subsequent login page can go to the userList set to judge the User login business logic. This method returns the string "loginForm" and jumps to loginForm JSP login page;
(6) The login method uses the @ RequestMapping("/ login") annotation to indicate that the request mapped by this method is http://localhost:8088/springmvc-comment1/user/login , the method property is not set here, which means that all requests are supported. The method also uses the @ RequestParam annotation to assign the specified request to the formal parameter in the method. After that, find out whether the user exists in the collection, which is used to simulate database authentication. In the login method, CNOOC has a parameter Model object. Call the addAttribute method of this object to add data to the request. Finally, if the user logs in successfully, it returns the string "loginForm" and jumps to loginForm JSP page.

We need to create a registerform under the content folder of the project jsp. The following code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration page</title>
</head>
<body>
<h3>Registration page</h3>
<form action="register" method="post">
     <table>
         <tr>
            <td><label>Login name: </label></td>
             <td><input type="text" id="loginname" name="loginname" ></td>
         </tr>
         <tr>
            <td><label>password: </label></td>
             <td><input type="password" id="password" name="password"></td>
         </tr>
         <tr>
            <td><label>Real name: </label></td>
             <td><input type="text" id="username" name="username" ></td>
         </tr>
         <tr>
             <td><input id="submit" type="submit" value="register"></td>
         </tr>
     </table>
</form>
</body>
</html>

registerForm.jsp is a registration page. Users can enter login name, password and real name. The form is submitted to the register request. Note that the POST mode is used here, and the response request is the register method of the UserController class.

 

 

 

 

 

REF

https://blog.csdn.net/qq_42223653/article/details/90486584