[SpringMVC] Multiple ways to get -request parameters-

insert image description here

Personal brief introduction: New star creator in the Java field; Alibaba cloud technology blogger, star blogger, expert blogger; on the way of learning Java, recording the learning process~ Personal homepage: .29.'s blog
Learning community
: Go in and have a stroll~

insert image description here



1. Get it through the native Servlet API


  • It will be HttpServletRequestused as the formal parameter of the controller method. At this time, the parameter of type HttpServletRequest represents the object that encapsulates the request message of the current request
/**
 * @author .29.
 * @create 2023-03-05 10:13
 */
@Controller
public class ParamController {
    
    

    //通过原生ServletAPI方式获取请求参数
    @RequestMapping(value = "testServletAPI")
    //形参位置的request表示当前请求
    public String testServletAPI(HttpServletRequest request){
    
    
        //通过当前请求对象request获取请求路径中传递的参数
        String user = request.getParameter("user");
        String ageStr = request.getParameter("age");
        //字符串 转 整形
        int age = Integer.parseInt(ageStr);
        System.out.println("user:"+user+",age:"+age);
        return "success";
    }
}



2. Acquisition through the formal parameters of the controller method


  • In the formal parameter position of the controller method, set the formal parameter with the same name as the request parameter. When the browser sends a request and matches the request mapping, the request parameter will be assigned to the corresponding formal parameter in DispatcherServlet.
/**
 * @author .29.
 * @create 2023-03-05 10:13
 */
@Controller
public class ParamController {
    
    

    //SpringMVC方式:通过控制器方法的形参获取请求参数
    @RequestMapping(value = "/testParam")
    /*
    * 当前形参的参数名 与 请求路径传递参数的参数名保持一致,就会自动获取到参数值(如果参数名不一致,将无法获取)
    * 当然,若参数名不一致,依旧可以借助 @RequestParam("对应参数名")注解来建立映射关系,获取请求路径中传递参数的值
    * 当标识了注解 @RequestParam("对应参数名"),这个参数就必须要被传输,否则报400错误
    * 必须传输参数的设定,可通过required = false 参数使其失效 :@RequestParam("对应参数名",required = false)
    * 若required = false,则会赋默认值,默认值可修改:defaultValue = "设定的默认值"
    */
    //注:当请求路径传递参数有多个重名参数,这里的形参即可使用String[]类型接收,也可使用String类型接收(接收的结果自动用','隔开)
    public String testParam(@RequestParam("username") String user, String password,
                            @RequestHeader(value = "Host",required = false) String host){
    
    
        System.out.println("user:"+user+",password:"+password);
        return "success";
    }


}

  • @RequestParam 注解: @RequestParam is to create a mapping relationship between the request parameter and the formal parameter of the controller method

  • @RequestHeader 注解: @RequestHeader creates a mapping relationship between the request header information and the formal parameters of the controller method

  • @CookieValue 注解: @CookieValue is to create a mapping relationship between cookie data and formal parameters of the controller method

Three attributes and their usage (the attributes are common to the above annotations) :

  1. value : Specify the parameter name of the request parameter assigned as the formal parameter

  2. required : Set whether this request parameter must be transmitted, the default value is true

If set to true, the current request must transmit the request parameter specified by value. If the request parameter is not transmitted and the defaultValue attribute is not set, the page will report an error 400: Required String parameter 'xxx' is not present;
——If
set is false, the current request does not have to transmit the request parameter specified by value, if not transmitted, the value of the formal parameter identified by the annotation is null

  1. defaultValue : Regardless of the value of the required attribute is true or false, when the request parameter specified by value is not transmitted or the transmitted value is "", the default value is used to assign the formal parameter



3. Obtain request parameters through entity class (POJO)


  • You can set a formal parameter of entity class type in the formal parameter position of the controller method. At this time, if the parameter name of the request parameter transmitted by the browser is consistent with the attribute name in the entity class, then the request parameter will assign a value to this attribute
/**
 * @author .29.
 * @create 2023-03-05 10:13
 */
@Controller
public class ParamController {
    
    

    //SpringMVC方式:通过POJO获取请求参数
    @RequestMapping(value = "/testpojo")
    //只需要实体类的属性名 与 请求参数的参数名一致,SpringMVC就能自动获取映射,读取请求参数为属性赋值
    public String POJO(User user){
    
    
        /*
        * 处理乱码问题:
        * GET请求方式的乱码:来源于TomCat,需要设置Tomcat配置文件,设置UTF-8;
        * Post请求方式的乱码:需要在获取请求参数之前,设置编码字符集
         */

        System.out.println(user);
        return "success";
    }
    
}

请求参数

<form th:action="@{/testpojo}" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    性别:<input type="radio" name="sex" value=""><input type="radio" name="sex" value=""><br>
    年龄:<input type="text" name="age"><br>
    邮箱:<input type="text" name="email"><br>
    <input type="submit" value="使用pojo获取请求参数">
</form>

实体类

/**
 * @author .29.
 * @create 2023-03-05 14:28
 */
public class User {
    
    
    String username;
    String password;
    String sex;
    String age;
    String email;

    public String getUsername() {
    
    
        return username;
    }

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

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    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 getEmail() {
    
    
        return email;
    }

    public void setEmail(String email) {
    
    
        this.email = email;
    }

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


insert image description here

Guess you like

Origin blog.csdn.net/ebb29bbe/article/details/129365924