• SpringMVC获取请求参数


    目录

    一、通过ServletAPI获取

    二、通过控制器方法的形参获取请求参数

    三、@RequestParam

    ⚪@RequestParam注解的三个属性

    1.value

    2.required

    3.defaultValue

    🐕@RequestParam的源码

    四、@RequestHeader

    🐕@RequestHeader源码 

    五、@CookieValue

    🐕@CookieValue源码 

    六、通过POJO(控制器方法的实体类类型的形参)获取请求参数

    七、解决获取请求参数的乱码问题

    🐕CharacterEncodingFilter源码


    一、通过ServletAPI获取

    只需要在控制器方法的形参位置上设置HttpServletRequest 类型的形参,就可以在控制器方法中使用request对象获取请求参数

    1. import org.springframework.stereotype.Controller;
    2. import org.springframework.web.bind.annotation.RequestMapping;
    3. import javax.servlet.http.HttpServletRequest;
    4. @Controller
    5. public class TestParamController {
    6. @RequestMapping("/param/servletAPI")
    7. //request表示当前需要处理的请求对象
    8. public String getParamByServletAPI(HttpServletRequest request){
    9. String username = request.getParameter("username");
    10. String password = request.getParameter("password");
    11. System.out.println("username: " + username +",password :" + password);
    12. return "success";
    13. }
    14. }

    二、通过控制器方法的形参获取请求参数

    在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在 DispatcherServlet中就会将请求参数赋值给相应的形参(不一致时获取不到)

    1. <form th:action="@{/param}" method="post">
    2. 用户名:<input type="text" name="username">
    3. 密码:<input type="password" name="password">
    4. <input type="submit" value="登录">
    5. form>
    1. @RequestMapping("/param")
    2. public String getParam(String username,String password){
    3. System.out.println("username: " + username +",password :" + password);
    4. return "success";
    5. }

    三、@RequestParam

    作用 : 将请求参数和控制器方法的形参创建映射关系

    ⚪@RequestParam注解的三个属性

    1.value

    设置和形参绑定的请求参数的名字

    2.required

    设置是否必须传输value所对应的请求参数,默认值为true

    • 若设置为true,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置 defaultValue属性,则页面报错400:Required String parameter 'xxx' is not present;
    • 若设置为 false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为 null

    3.defaultValue

    不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值 

    🐕@RequestParam的源码

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package org.springframework.web.bind.annotation;
    6. import java.lang.annotation.Documented;
    7. import java.lang.annotation.ElementType;
    8. import java.lang.annotation.Retention;
    9. import java.lang.annotation.RetentionPolicy;
    10. import java.lang.annotation.Target;
    11. import org.springframework.core.annotation.AliasFor;
    12. @Target({ElementType.PARAMETER})
    13. @Retention(RetentionPolicy.RUNTIME)
    14. @Documented
    15. public @interface RequestParam {
    16. @AliasFor("name")
    17. String value() default "";
    18. @AliasFor("value")
    19. String name() default "";
    20. boolean required() default true;
    21. String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
    22. }

    测试

    1. <form th:action="@{/param}" method="post">
    2. 用户名:<input type="text" name="userName">
    3. 密码:<input type="password" name="password">
    4. <input type="submit" value="登录">
    5. form>
    1. @RequestMapping("/param")
    2. public String getParam(
    3. @RequestParam(
    4. value = "userName",
    5. required = false,
    6. defaultValue = "hello")
    7. String username, String password){
    8. System.out.println("username: " + username +",password :" + password);
    9. return "success";
    10. }

    四、@RequestHeader

    作用:将请求头信息和控制器方法的形参创建映射关系

    @RequestHeader注解一共有三个属性

    value、required、defaultValue,用法同@RequestParam

    🐕@RequestHeader源码 

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package org.springframework.web.bind.annotation;
    6. import java.lang.annotation.Documented;
    7. import java.lang.annotation.ElementType;
    8. import java.lang.annotation.Retention;
    9. import java.lang.annotation.RetentionPolicy;
    10. import java.lang.annotation.Target;
    11. import org.springframework.core.annotation.AliasFor;
    12. @Target({ElementType.PARAMETER})
    13. @Retention(RetentionPolicy.RUNTIME)
    14. @Documented
    15. public @interface RequestHeader {
    16. @AliasFor("name")
    17. String value() default "";
    18. @AliasFor("value")
    19. String name() default "";
    20. boolean required() default true;
    21. String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
    22. }

    测试

    1. @RequestMapping("/param")
    2. public String getParam(
    3. @RequestParam(
    4. value = "userName",
    5. required = false,
    6. defaultValue = "hello") String username,
    7. String password,
    8. @RequestHeader(
    9. value = "referer",
    10. required = false,
    11. defaultValue = "123456") String referer){
    12. System.out.println("referer: " + referer);
    13. System.out.println("username: " + username +",password :" + password);
    14. return "success";
    15. }

    运行结果 

    五、@CookieValue

    作用:将cookie数据和控制器方法的形参创建映射关系

    @CookieValue注解一共有三个属性:

    value、required、defaultValue,用法同@RequestParam

    🐕@CookieValue源码 

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package org.springframework.web.bind.annotation;
    6. import java.lang.annotation.Documented;
    7. import java.lang.annotation.ElementType;
    8. import java.lang.annotation.Retention;
    9. import java.lang.annotation.RetentionPolicy;
    10. import java.lang.annotation.Target;
    11. import org.springframework.core.annotation.AliasFor;
    12. @Target({ElementType.PARAMETER})
    13. @Retention(RetentionPolicy.RUNTIME)
    14. @Documented
    15. public @interface CookieValue {
    16. @AliasFor("name")
    17. String value() default "";
    18. @AliasFor("value")
    19. String name() default "";
    20. boolean required() default true;
    21. String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
    22. }

    测试

    1. @Controller
    2. public class TestParamController {
    3. @RequestMapping("/param/servletAPI")
    4. //request表示当前需要处理的请求对象
    5. public String getParamByServletAPI(HttpServletRequest request){
    6. HttpSession session = request.getSession();
    7. String username = request.getParameter("username");
    8. String password = request.getParameter("password");
    9. System.out.println("username: " + username +",password :" + password);
    10. return "success";
    11. }
    12. @RequestMapping("/param")
    13. public String getParam(
    14. @RequestParam(
    15. value = "userName",
    16. required = false,
    17. defaultValue = "hello") String username,
    18. String password,
    19. @RequestHeader(
    20. value = "referer",
    21. required = false,
    22. defaultValue = "123456") String referer,
    23. @CookieValue("JSESSIONID") String jsessionId){
    24. System.out.println("jsessionId: " + jsessionId);
    25. System.out.println("referer: " + referer);
    26. System.out.println("username: " + username +",password :" + password);
    27. return "success";
    28. }
    29. }

    先访问http://localhost:8080/SpringMVC/ param/servletAPI创建Cookie

    发送请求参数: 

    六、通过POJO(控制器方法的实体类类型的形参)获取请求参数

    可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值

    1. package com.atguigu.pojo;
    2. public class User {
    3. private Integer id;
    4. private String username;
    5. private String password;
    6. public User() {
    7. }
    8. public User(Integer id, String username, String password) {
    9. this.id = id;
    10. this.username = username;
    11. this.password = password;
    12. }
    13. @Override
    14. public String toString() {
    15. return "User{" +
    16. "id=" + id +
    17. ", username='" + username + '\'' +
    18. ", password='" + password + '\'' +
    19. '}';
    20. }
    21. public Integer getId() {
    22. return id;
    23. }
    24. public void setId(Integer id) {
    25. this.id = id;
    26. }
    27. public String getUsername() {
    28. return username;
    29. }
    30. public void setUsername(String username) {
    31. this.username = username;
    32. }
    33. public String getPassword() {
    34. return password;
    35. }
    36. public void setPassword(String password) {
    37. this.password = password;
    38. }
    39. }
    1. <form th:action="@{/param/pojo}" method="post">
    2. 用户名:<input type="text" name="username">
    3. 密码:<input type="password" name="password">
    4. <input type="submit" value="登录">
    5. form>
    1. @RequestMapping("/param/pojo")
    2. public String getParamByPojo(User user){
    3. System.out.println(user);
    4. return "success";
    5. }

    七、解决获取请求参数的乱码问题

    解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是必须在web.xml中进行注册

    1. <filter>
    2. <filter-name>CharacterEncodingFilterfilter-name>
    3. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    4. <init-param>
    5. <param-name>encodingparam-name>
    6. <param-value>UTF-8param-value>
    7. init-param>
    8. <init-param>
    9. <param-name>forceEncodingparam-name>
    10. <param-value>trueparam-value>
    11. init-param>
    12. filter>
    13. <filter-mapping>
    14. <filter-name>CharacterEncodingFilterfilter-name>
    15. <url-pattern>/*url-pattern>
    16. filter-mapping>

    注意: SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效

    如果怕配置错误,可以打开CharacterEncodingFilter的源码查看:

     

    🐕CharacterEncodingFilter源码

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package org.springframework.web.filter;
    6. import java.io.IOException;
    7. import javax.servlet.FilterChain;
    8. import javax.servlet.ServletException;
    9. import javax.servlet.http.HttpServletRequest;
    10. import javax.servlet.http.HttpServletResponse;
    11. import org.springframework.lang.Nullable;
    12. import org.springframework.util.Assert;
    13. public class CharacterEncodingFilter extends OncePerRequestFilter {
    14. @Nullable
    15. private String encoding;
    16. private boolean forceRequestEncoding;
    17. private boolean forceResponseEncoding;
    18. public CharacterEncodingFilter() {
    19. this.forceRequestEncoding = false;
    20. this.forceResponseEncoding = false;
    21. }
    22. public CharacterEncodingFilter(String encoding) {
    23. this(encoding, false);
    24. }
    25. public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
    26. this(encoding, forceEncoding, forceEncoding);
    27. }
    28. public CharacterEncodingFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
    29. this.forceRequestEncoding = false;
    30. this.forceResponseEncoding = false;
    31. Assert.hasLength(encoding, "Encoding must not be empty");
    32. this.encoding = encoding;
    33. this.forceRequestEncoding = forceRequestEncoding;
    34. this.forceResponseEncoding = forceResponseEncoding;
    35. }
    36. public void setEncoding(@Nullable String encoding) {
    37. this.encoding = encoding;
    38. }
    39. @Nullable
    40. public String getEncoding() {
    41. return this.encoding;
    42. }
    43. public void setForceEncoding(boolean forceEncoding) {
    44. this.forceRequestEncoding = forceEncoding;
    45. this.forceResponseEncoding = forceEncoding;
    46. }
    47. public void setForceRequestEncoding(boolean forceRequestEncoding) {
    48. this.forceRequestEncoding = forceRequestEncoding;
    49. }
    50. public boolean isForceRequestEncoding() {
    51. return this.forceRequestEncoding;
    52. }
    53. public void setForceResponseEncoding(boolean forceResponseEncoding) {
    54. this.forceResponseEncoding = forceResponseEncoding;
    55. }
    56. public boolean isForceResponseEncoding() {
    57. return this.forceResponseEncoding;
    58. }
    59. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    60. String encoding = this.getEncoding();
    61. if (encoding != null) {
    62. if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
    63. request.setCharacterEncoding(encoding);
    64. }
    65. if (this.isForceResponseEncoding()) {
    66. response.setCharacterEncoding(encoding);
    67. }
    68. }
    69. filterChain.doFilter(request, response);
    70. }
    71. }

  • 相关阅读:
    简单钟表动画
    volatile关键字 和 i = i + 1过程
    2022 年 25 大 Java 8 面试问题和答案 - 从基础到有经验
    深入浅出(五)JsonCpp库
    SpringBoot怎么自定义一个Starter?
    【LeetCode热题100】--560.和为K的子数组
    洛谷千题详解 | P1009 [NOIP1998 普及组] 阶乘之和【C++、Java、Python、Pascal语言】
    李沐动手学深度学习V2-bert预训练数据集和代码实现
    kubernetes(K8S)学习笔记P3:集群 YAML 文件(部署)
    UnityPackageManager相关
  • 原文地址:https://blog.csdn.net/m0_52982868/article/details/126125653