SpringMVC获取请求参数

15 篇文章 1 订阅

目录

一、通过ServletAPI获取

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

三、@RequestParam

⚪@RequestParam注解的三个属性

1.value

2.required

3.defaultValue

🐕@RequestParam的源码

四、@RequestHeader

🐕@RequestHeader源码 

五、@CookieValue

🐕@CookieValue源码 

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

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

🐕CharacterEncodingFilter源码


一、通过ServletAPI获取

只需要在控制器方法的形参位置上设置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";
}

三、@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的源码

//
// 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

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

@RequestHeader注解一共有三个属性

value、required、defaultValue,用法同@RequestParam

🐕@RequestHeader源码 

//
// 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";
}

运行结果 

五、@CookieValue

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

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

value、required、defaultValue,用法同@RequestParam

🐕@CookieValue源码 

//
// 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

发送请求参数: 

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

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

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中进行注册

<!-- 配置Spring编码过滤器 -->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <!-- 自定义编码 -->
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <!-- 设置请求&响应的编码 -->
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

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

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

 

🐕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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

elk-zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值