SpringMVC笔记(2):@RequestMapping注解/请求参数

目录

1、@RequestMapping注解

1、@RequestMapping注解的功能

2、@RequestMapping注解的位置

3、@RequestMapping注解的value属性

4、@RequestMapping注解的method属性

5、@RequestMapping注解的params属性(了解)

6、@RequestMapping注解的headers属性(了解)

7、SpringMVC支持ant风格的路径

8、SpringMVC支持路径中的占位符(重点)

2、SpringMVC获取请求参数

1、通过ServletAPI获取

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

3、@RequestParam

4、@RequestHeader

5、@CookieValue

6、通过POJO获取请求参数

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


1、@RequestMapping注解

1、@RequestMapping注解的功能

从注解名称上我们可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系

SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求。

2、@RequestMapping注解的位置

  • @RequestMapping标识一个类:设置映射请求的请求路径的初始信息
  • @RequestMapping标识一个方法:设置映射请求请求路径的具体信息
@Controller
@RequestMapping("/test")
public class RequestMappingController {

    //此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
    @RequestMapping("/testRequestMapping")
    public String testRequestMapping(){
        return "success";
    }

}

3、@RequestMapping注解的value属性

@RequestMapping注解的value属性通过请求的请求地址匹配请求映射

@RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求

@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射

<a th:href="@{/testRequestMapping}">测试@RequestMapping的value属性-->/testRequestMapping</a><br>
<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>

@RequestMapping(
        value = {"/testRequestMapping", "/test"}
)
public String testRequestMapping(){
    return "success";
}

4、@RequestMapping注解的method属性

  • @RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射
  • @RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求
  • 若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错405:Request method ‘POST’ not supported。
  • 不设置method时,可以是get、post都可以
<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>

<form th:action="@{/test}" method="post">
    <input type="submit">
</form>

@RequestMapping(
        value = {"/testRequestMapping", "/test"},
        method = {RequestMethod.GET, RequestMethod.POST}
)
public String testRequestMapping(){
    return "success";
}注:

1、对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解

  • 处理get请求的映射–>@GetMapping
  • 处理post请求的映射–>@PostMapping
  • 处理put请求的映射–>@PutMapping
  • 处理delete请求的映射–>@DeleteMapping

2、常用的请求方式有get,post,put,delete

  • 但是目前浏览器只支持get和post,若在form表单提交时,为method设置了其他请求方式的字符串(put或delete),则按照默认的请求方式get处理
  • 若要发送put和delete请求,则需要通过spring提供的过滤器HiddenHttpMethodFilter,在RESTful部分会讲到

5、@RequestMapping注解的params属性(了解)

  • @RequestMapping注解的params属性通过请求的请求参数匹配请求映射
  • 如果params属性的多个值,必须都满足
  • @RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系
    • “param”:要求请求映射所匹配的请求必须携带param请求参数
    • “!param”:要求请求映射所匹配的请求必须不能携带param请求参数
    • “param=value”:要求请求映射所匹配的请求必须携带param请求参数且param=value
    • “param!=value”:要求请求映射所匹配的请求必须携带param请求参数但是param!=value
<a th:href="@{/test(username='admin',password=123456)">测试@RequestMapping的params属性-->/test</a><br>

@RequestMapping(
        value = {"/testRequestMapping", "/test"}
        ,method = {RequestMethod.GET, RequestMethod.POST}
        ,params = {"username","password!=123456"}
)
public String testRequestMapping(){
    return "success";
}
注:
  • 若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时页面回报错400:Parameter conditions “username, password!=123456” not met for actual request parameters: username={admin}, password={123456}

6、@RequestMapping注解的headers属性(了解)

@RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射

@RequestMapping注解的headers属性是一个字符串类型的数组,可以通过四种表达式设置请求头信息和请求映射的匹配关系

  • “header”:要求请求映射所匹配的请求必须携带header请求头信息
  • “!header”:要求请求映射所匹配的请求必须不能携带header请求头信息
  • “header=value”:要求请求映射所匹配的请求必须携带header请求头信息且header=value
  • “header!=value”:要求请求映射所匹配的请求必须携带header请求头信息且header!=value

注:

  •   若当前请求满足@RequestMapping注解的value和method属性,但是不满足headers属性,此时页面显示404错误,即资源未找到
@RequestMapping(
        value = {"/a", "/b"},
        method = {RequestMethod.POST, RequestMethod.GET},
        params = {"username", "password"},
        headers = {"Host=localhost:8081"}
)
public String success(){
    return "success";
}

7、SpringMVC支持ant风格的路径

  • ?:表示任意的单个字符
  • *:表示任意的0个或多个字符
  • **:表示任意的一层或多层目录

表示请求的value中的三种格式。


    @RequestMapping("/a?a/testAnt")
    public String testAnt(){
        return "success";
    }

成功:     http://localhost:8080/SpringMVC/a1a/testAnt

注意:在使用 ** 时,只能使用 /**/xxx 的方式

8、SpringMVC支持路径中的占位符(重点)

原始方式:/deleteUser?id=1

rest方式:/deleteUser/1

        SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参

<a th:href="@{/testRest/1/admin}">测试路径中的占位符-->/testRest</a><br>

@RequestMapping("/testRest/{id}/{username}")
public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){
    System.out.println("id:"+id+",username:"+username);
    return "success";
}
//最终输出的内容为-->id:1,username:admin

2、SpringMVC获取请求参数

1、通过ServletAPI获取(基本不用)

将HttpServletRequest作为控制器方法的形参,此时HttpServletRequest类型的参数表示封装了当前请求的请求报文的对象

@Controller
public class HelloController {

     @RequestMapping("/param")
    public String param(){
        return "test_param";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>

<a th:href="@{/testServletAPI(username='admin',password=123456)}">测试使用servlet获取请求参数</a><br/>
</body>
</html>
@Controller
public class TestServletAPI {

    /**
     * 返回视图
     * @return
     */
    @RequestMapping("/testServletAPI")
    public String index(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + ":" + password);
        return "success";
    }

}

结果:

SpringMVC提供的方式:通过行参获取

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

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

<a th:href="@{/testParam(username='admin',password=123456)}">测试获取请求参数-->/testParam</a><br>

@RequestMapping("/testParam")
public String testParam(String username, String password){
    System.out.println("username:"+username+",password:"+password);
    return "success";
}注:
  • 若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串数组或者字符串类型的形参接收此请求参数。
  • 若使用字符串数组类型的形参,此参数的数组中包含了每一个数据。[a,b,c]
  • 若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果。a,b,c
@Controller
public class HelloController {

    @RequestMapping("/param")
    public String param(){
        return "test_param";
    }

    @RequestMapping("/testSpringMVC")
    public String param(String username, String password, String[] hobby){
        //System.out.println("username: " + username + "password:" + password + "hobby:" + hobby);   //a,b,c
        System.out.println("username: " + username + "password:" + password + "hobby:" + Arrays.toString(hobby));   //[a,b,c]
        return "success";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>

<form th:action="@{/testSpringMVC}" method="get">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    爱好:<input type="checkbox" name="hobby" value="a">a<br/>
          <input type="checkbox" name="hobby" value="b">b<br/>
         <input type="checkbox" name="hobby" value="c">c<br/>
    <input type="submit" value="提交">
</form>

</body>
</html>

3、@RequestParam结果: 

3、@RequestParam

  • @RequestParam是将请求参数和控制器方法的形参创建映射关系
  • @RequestParam注解一共有三个属性:
    • value:指定为形参赋值的请求参数的参数名
    • required:设置是否必须传输此请求参数,默认值为true
  • 若设置为true时,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置defaultValue属性,则页面报错400:Required String parameter ‘xxx’ is not present;
  • 若设置为false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为null;
  • defaultValue:不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值。

4、@RequestHeader

@RequestHeader是将请求头信息和控制器方法的形参创建映射关系

@RequestHeader注解一共有三个属性:value、required、defaultValue,同@RequestParam

    @RequestMapping("/testSpringMVC")
    public String testParam(
            @RequestParam(value = "user_name", required = false, defaultValue = "aa") String username,
            String password,
            String[] hobby,
            @RequestHeader("Host") String host){
        System.out.println("username: " + username + "password:" + password + "hobby:" + Arrays.toString(hobby));
        System.out.println(host);
        return "success";
        //username: aapassword:123hobby:[b, c]
        //localhost:8080
    }

5、@CookieValue

@CookieValue是将cookie数据和控制器方法的形参创建映射关系

@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam

先将session传给浏览器,则cookie先存在于response headers

在从浏览器传给服务器时cookie存在于request headers中。

 @RequestMapping("/testSpringMVC")
    public String testParam(
            @RequestParam(value = "user_name", required = false, defaultValue = "aa") String username,
            String password,
            String[] hobby,
            @RequestHeader("Host") String host,
            @CookieValue("JSESSIONID")String JSESSIONID){
        System.out.println("username: " + username + "password:" + password + "hobby:" + Arrays.toString(hobby));
        System.out.println("host:" + host);
        System.out.println("JSESSIONID:" + JSESSIONID);
        return "success";
        //username: aa password:123hobby:[b, c]
        //host:localhost:8080
        //JSESSIONID:46138602E1591E00BF0D1888B0E0198C
    }

6、通过POJO获取请求参数

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

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

@RequestMapping("/testpojo")
public String testPOJO(User user){
    System.out.println(user);
    return "success";
}
//最终结果-->User{id=null, username='张三', password='123', age=23, sex='男', email='123@qq.com'}

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

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

<!--配置springMVC的编码过滤器-->
<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>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

注:
  SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效。
其中get请求的乱码问题通过tomcat的配置文件已经解决。上述用于解决post乱码问题。

 post乱码解决办法:

dispatcherServlet获取请求参数在前,然后通过自己手动设置编码。此时手动设置的编码失效

故需要在dispatcherServlet获取请求参数之前设置编码。

        dispatcherServlet在服务器启动时已经加载。

        加载顺序:监听器 (ServletContextListener)、过滤器(Filter)、servlet(DispatcherServlet)

其中ServletContextListener可以监听ServletContext的创建和销毁。

只要请求的路径满足过滤器路径设置,就会先经过过滤器处理,在交给DispatcherServlet处理。

参数设置原理:看源码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值