SpringMVC中常用注解(案例讲解)

SpringMVC中常用注解

RequestParam

说明

==作用:==
把请求中指定名称的参数给控制器中的形参赋值。
==属性:==
value:请求参数中的名称。
required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。

代码示例

==jsp代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%--
Created by IntelliJ IDEA.
User: Keafmd
Date: 2021/1/25
Time: 10:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>

<!-- requestParams 注解的使用 -->
<a href="anno/testRequestParam?name=keafmd">RequestParam</a><br/>

</body>
</html>

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Date;
import java.util.Map;

/**
* Keafmd
*
* @ClassName: AnnoConteoller
* @Description: 注解的控制器
* @author: 牛哄哄的柯南
* @date: 2021-01-25 10:50
*/
@Controller
@RequestMapping("/anno")
public class AnnoConteoller {

/**
* requestParams 注解的使用
* @param username
* @return
*/
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value="name") String username){
// @RequestParam(value="name") 必须传name,required:请求参数中是否必须提供此参数,默认值是true,必须提供
// 获得当前类名
String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();

System.out.println("执行了:"+clazz+" - "+method);
System.out.println("username:"+username);
return "success";
}

}

==输出结果:==

1
2
执行了:com.Keafmd.controller.AnnoConteoller - testRequestParam
username:keafmd

这样我们在href中传入name就会赋值给username。

RequestBody

说明

==作用:==
用于获取请求体内容。直接使用得到是 key=value&key=value…结构的数据。
get 请求方式不适用。
==属性:==
required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null。

代码示例

==jsp代码:==

1
2
3
4
5
6
<form action="anno/testRequestBody" method="post">
用户姓名:<input type="text" name="uname" /><br/>
用户年龄:<input type="text" name="age" /><br/>
用户生日:<input type="text" name="birthday" /><br/>
<input type="submit" value="提交">
</form>

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
/**
* 获取到请求体的内容 RequestBody
*/

@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
System.out.println("body:"+body);
return "success";
}

==输出结果:==

1
2
执行了: testRequestBody
body:uname=Keafmd&age=21&birthday=2000-01-01

PathVaribale

先了解下REST 风格 URL

REST(英文:Representational State Transfer,简称 REST)描述了一个架构样式的网络系统,比如 web 应用程序。值得注意的是 REST 并没有一个明确的标准,而更像是一种设计的风格。
在这里插入图片描述

说明

==作用:==
用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。
==属性:==
value:用于指定 url 中占位符名称。
required:是否必须提供占位符。

代码示例

==jsp代码:==

1
<a href="anno/testPathVariable/10">testPathVariable</a><br/>

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* PathVariable
* @param id
* @return
*/
@RequestMapping("/testPathVariable/{sid}")
public String testPathVariable(@PathVariable(name="sid") String id){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
System.out.println("id:"+id);
return "success";
}

==输出结果:==

1
2
执行了: testPathVariable
id:10

RequestHeader

说明

==作用:==
用于获取请求消息头。
==属性:==
value:提供消息头名称
required:是否必须有此消息头
==提示:==
在实际开发中一般不常用

代码示例

==jsp代码:==

1
<a href="anno/testRequestHeader">testRequestHeader</a><br/>

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* RequestHeader获取请求头的值 不常用
* @param head
* @return
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept") String head){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);

System.out.println("head:"+head);
return "success";
}

==输出结果:==

1
2
执行了: testRequestHeader
head:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3

CookieValue

说明

==作用:==
用于把指定 cookie 名称的值传入控制器方法参数。
==属性:==
value:指定 cookie 的名称。
required:是否必须有此 cookie。

代码示例

==jsp代码:==

1
<a href="anno/testCookieValue">testCookValue</a><br/>

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* CookieValue 不常用
* @param cookievalue
* @return
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookievalue){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);

System.out.println("cookievalue:"+cookievalue);
return "success";
}

==输出结果:==

1
2
执行了: testCookieValue
cookievalue:DCCFE2C1F975AC04D4F55973ADA5C89C

ModelAttribute

说明

==作用:==
该注解是 SpringMVC4.3 版本以后新加入的。它可以用于修饰方法和参数。
出现在方法上,表示==当前方法会在控制器的方法执行之前,先执行==。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。
出现在参数上,获取指定的数据给参数赋值。
==属性:==
value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。
==应用场景:==
当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。

代码示例

==jsp代码:==

1
2
3
4
5
<form action="anno/testModelAttribute" method="post">
用户姓名:<input type="text" name="uname" /><br/>
用户年龄:<input type="text" name="age" /><br/>
<input type="submit" value="提交">
</form>

修饰的方法有返回值

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* ModelAttribute
* @return
*/

@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
System.out.println(user);
return "success";
}

//有返回值
@ModelAttribute
public User showUser(String uname){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
User user = new User();
user.setUname(uname);
user.setAge(20);
user.setBirthday(new Date());
return user;
}

==输出结果:==

1
2
执行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:34:46 CST 2021}

修饰的方法没有返回值

==注意==:没有返回值的时候利用Map把参数传回去,testModelAttribute的参数User前加上@ModelAttribute(“abc”)接收Map传回的数据。

==控制器代码:==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* ModelAttribute
* @return
*/

@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute("abc")User user){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
System.out.println(user);
return "success";
}

//无返回值
@ModelAttribute
public void showUser(String uname, Map<String,User> map){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);
User user = new User();
user.setUname(uname);
user.setAge(20);
user.setBirthday(new Date());
map.put("abc",user);
}

==输出结果:==

1
2
执行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:32:20 CST 2021}

SessionAttribute

说明

==作用:==
用于多次执行控制器方法间的参数共享。
==属性:==
value:用于指定存入的属性名称
type:用于指定存入的数据类型。

代码示例

==jsp代码:==

1
2
3
<a href="anno/testSessionAttributes">存入SessionAttributes</a><br/>
<a href="anno/getSessionAttributes">获取SessionAttributes</a><br/>
<a href="anno/delSessionAttributes">清除SessionAttributes</a><br/>

==控制器代码:==

注意:需要在类的上面添加@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Date;
import java.util.Map;

/**
* Keafmd
*
* @ClassName: AnnoConteoller
* @Description: 注解的控制器
* @author: 牛哄哄的柯南
* @date: 2021-01-25 10:50
*/
@Controller
@RequestMapping("/anno")
@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中
public class AnnoConteoller {

/**
* SessionAttributes注解,存入msg
* @return
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Model model){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);

//底层会存到Request域中
model.addAttribute("msg","牛哄哄的柯南");

return "success";
}

/**
* 获取
* @param modelMap
* @return
*/
@RequestMapping("/getSessionAttributes")
public String getSessionAttributes(ModelMap modelMap){
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);

//从session域中取出来
String msg = (String)modelMap.get("msg");
System.out.println(msg);
return "success";
}

/**
* 清除
* @param sessionStatus
* @return
*/
@RequestMapping("/delSessionAttributes")
public String delSessionAttributes(SessionStatus sessionStatus) {
// 获得当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("执行了:"+" "+method);

//从session域中清除
sessionStatus.setComplete();
return "success";
}


}

依次点击存入->获取->清除->获取。

==输出结果:==

1
2
3
4
5
6
执行了: testSessionAttributes
执行了: getSessionAttributes
牛哄哄的柯南
执行了: delSessionAttributes
执行了: getSessionAttributes
null

在success.jsp可以通过${msg}和${sessionScope}获取到在类上面把msg存入到session域的内容:牛哄哄的柯南和{msg=牛哄哄的柯南}
在success.jsp可以通过${requestScope}获取到在testSessionAttributes方法中存入Request域中的内容。

以上就是SpringMVC中常用注解(案例讲解)的全部内容。