目录
六、通过POJO(控制器方法的实体类类型的形参)获取请求参数
只需要在控制器方法的形参位置上设置HttpServletRequest 类型的形参,就可以在控制器方法中使用request对象获取请求参数
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.http.HttpServletRequest;
-
- @Controller
- public class TestParamController {
- @RequestMapping("/param/servletAPI")
- //request表示当前需要处理的请求对象
- public String getParamByServletAPI(HttpServletRequest request){
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
- }
在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在 DispatcherServlet中就会将请求参数赋值给相应的形参(不一致时获取不到)
- <form th:action="@{/param}" method="post">
- 用户名:<input type="text" name="username">
- 密码:<input type="password" name="password">
- <input type="submit" value="登录">
- form>
- @RequestMapping("/param")
- public String getParam(String username,String password){
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
作用 : 将请求参数和控制器方法的形参创建映射关系
设置和形参绑定的请求参数的名字
设置是否必须传输value所对应的请求参数,默认值为true
不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值
- //
- // Source code recreated from a .class file by IntelliJ IDEA
- // (powered by FernFlower decompiler)
- //
-
- package org.springframework.web.bind.annotation;
-
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import org.springframework.core.annotation.AliasFor;
-
- @Target({ElementType.PARAMETER})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface RequestParam {
- @AliasFor("name")
- String value() default "";
-
- @AliasFor("value")
- String name() default "";
-
- boolean required() default true;
-
- String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
- }
测试
- <form th:action="@{/param}" method="post">
- 用户名:<input type="text" name="userName">
- 密码:<input type="password" name="password">
- <input type="submit" value="登录">
- form>
- @RequestMapping("/param")
- public String getParam(
- @RequestParam(
- value = "userName",
- required = false,
- defaultValue = "hello")
- String username, String password){
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
作用:将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性
value、required、defaultValue,用法同@RequestParam
- //
- // Source code recreated from a .class file by IntelliJ IDEA
- // (powered by FernFlower decompiler)
- //
-
- package org.springframework.web.bind.annotation;
-
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import org.springframework.core.annotation.AliasFor;
-
- @Target({ElementType.PARAMETER})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface RequestHeader {
- @AliasFor("name")
- String value() default "";
-
- @AliasFor("value")
- String name() default "";
-
- boolean required() default true;
-
- String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
- }
测试
- @RequestMapping("/param")
- public String getParam(
- @RequestParam(
- value = "userName",
- required = false,
- defaultValue = "hello") String username,
- String password,
- @RequestHeader(
- value = "referer",
- required = false,
- defaultValue = "123456") String referer){
- System.out.println("referer: " + referer);
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
运行结果
作用:将cookie数据和控制器方法的形参创建映射关系
@CookieValue注解一共有三个属性:
value、required、defaultValue,用法同@RequestParam
- //
- // Source code recreated from a .class file by IntelliJ IDEA
- // (powered by FernFlower decompiler)
- //
-
- package org.springframework.web.bind.annotation;
-
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import org.springframework.core.annotation.AliasFor;
-
- @Target({ElementType.PARAMETER})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface CookieValue {
- @AliasFor("name")
- String value() default "";
-
- @AliasFor("value")
- String name() default "";
-
- boolean required() default true;
-
- String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
- }
测试
- @Controller
- public class TestParamController {
- @RequestMapping("/param/servletAPI")
- //request表示当前需要处理的请求对象
- public String getParamByServletAPI(HttpServletRequest request){
- HttpSession session = request.getSession();
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
-
- @RequestMapping("/param")
- public String getParam(
- @RequestParam(
- value = "userName",
- required = false,
- defaultValue = "hello") String username,
- String password,
- @RequestHeader(
- value = "referer",
- required = false,
- defaultValue = "123456") String referer,
- @CookieValue("JSESSIONID") String jsessionId){
- System.out.println("jsessionId: " + jsessionId);
- System.out.println("referer: " + referer);
- System.out.println("username: " + username +",password :" + password);
- return "success";
- }
- }
先访问http://localhost:8080/SpringMVC/ param/servletAPI创建Cookie
发送请求参数:
可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值
- package com.atguigu.pojo;
-
- public class User {
- private Integer id;
- private String username;
- private String password;
-
- public User() {
- }
-
- public User(Integer id, String username, String password) {
- this.id = id;
- this.username = username;
- this.password = password;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "id=" + id +
- ", username='" + username + '\'' +
- ", password='" + password + '\'' +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- 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;
- }
- }
- <form th:action="@{/param/pojo}" method="post">
- 用户名:<input type="text" name="username">
- 密码:<input type="password" name="password">
- <input type="submit" value="登录">
- form>
- @RequestMapping("/param/pojo")
- public String getParamByPojo(User user){
- System.out.println(user);
- return "success";
- }
解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是必须在web.xml中进行注册
- <filter>
- <filter-name>CharacterEncodingFilterfilter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
- <init-param>
-
- <param-name>encodingparam-name>
- <param-value>UTF-8param-value>
- init-param>
- <init-param>
-
- <param-name>forceEncodingparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>CharacterEncodingFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
注意: SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效
如果怕配置错误,可以打开CharacterEncodingFilter的源码查看:
- //
- // Source code recreated from a .class file by IntelliJ IDEA
- // (powered by FernFlower decompiler)
- //
-
- package org.springframework.web.filter;
-
- import java.io.IOException;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.lang.Nullable;
- import org.springframework.util.Assert;
-
- public class CharacterEncodingFilter extends OncePerRequestFilter {
- @Nullable
- private String encoding;
- private boolean forceRequestEncoding;
- private boolean forceResponseEncoding;
-
- public CharacterEncodingFilter() {
- this.forceRequestEncoding = false;
- this.forceResponseEncoding = false;
- }
-
- public CharacterEncodingFilter(String encoding) {
- this(encoding, false);
- }
-
- public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
- this(encoding, forceEncoding, forceEncoding);
- }
-
- public CharacterEncodingFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
- this.forceRequestEncoding = false;
- this.forceResponseEncoding = false;
- Assert.hasLength(encoding, "Encoding must not be empty");
- this.encoding = encoding;
- this.forceRequestEncoding = forceRequestEncoding;
- this.forceResponseEncoding = forceResponseEncoding;
- }
-
- public void setEncoding(@Nullable String encoding) {
- this.encoding = encoding;
- }
-
- @Nullable
- public String getEncoding() {
- return this.encoding;
- }
-
- public void setForceEncoding(boolean forceEncoding) {
- this.forceRequestEncoding = forceEncoding;
- this.forceResponseEncoding = forceEncoding;
- }
-
- public void setForceRequestEncoding(boolean forceRequestEncoding) {
- this.forceRequestEncoding = forceRequestEncoding;
- }
-
- public boolean isForceRequestEncoding() {
- return this.forceRequestEncoding;
- }
-
- public void setForceResponseEncoding(boolean forceResponseEncoding) {
- this.forceResponseEncoding = forceResponseEncoding;
- }
-
- public boolean isForceResponseEncoding() {
- return this.forceResponseEncoding;
- }
-
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
- String encoding = this.getEncoding();
- if (encoding != null) {
- if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
- request.setCharacterEncoding(encoding);
- }
-
- if (this.isForceResponseEncoding()) {
- response.setCharacterEncoding(encoding);
- }
- }
-
- filterChain.doFilter(request, response);
- }
- }