1. 概述
spring mvc中使用@RequestMapping時凡傅,支持常用方法參數(shù)類型和返回類型捻激。
常用的方法參數(shù)類型有:
- 1 PathVariable
- 2 RequestParam
- 3 RequestBody
- 4 HttpEntity
- 5 CookieValue
- 6 RequestHeader
- 7 自動封裝form表單請求到對象中
- 8 HttpServletRequest HttpServletResponse
- 9 RequestMapping 參數(shù)配置params headers
常用的返回類型有:
1 返回一個頁面的地址
2 ResponseBody
3 ResponseEntity
4 ModelAndView
2. 前提條件
代碼工程名稱:mvc
測試PO類
ModelAttributeVO
public class ModelAttributeVO {
private String name;
private String value;
private Date date;
// set/get方法略
}
VO
public class VO {
private String name;
private String value;
private Date date;
// set/get方法略
}
3. @RequestMapping支持的方法參數(shù)類型
3.1. RequestParameterController
以下代碼都在RequestParameterController類中
@Controller: 表示此類對外提供url服務(wù) @RequestMapping:此注解不僅可以作用在方法上,也可以作用在類上坛缕。如果作用在類上秋茫,則表示此值是類中的所有@RequestMapping方法的URL的前綴
@Controller
@RequestMapping(value = "/request") // 全局URL
public class RequestParameterController {
....
}
3.2. 使用的jsp
下面用到j(luò)sp的頁面如下工猜,都在META-INF\resources\WEB-INF\page\reqparameter目錄下:
showInput.jsp
打印內(nèi)容
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Request Parameter</title>
</head>
<body>
${map}
</body>
</html>
formModel.jsp
測試form表單
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="myform" method="post" action="formModel">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="name" value="fisr name" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="value" value="lastName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form>
</body>
</html>
httpEntityForm.jsp
測試form表單
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="myform" method="post" action="httpEntity">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" value="name" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" value="lastName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form>
</body>
</html>
3.3. @PathVariable
作用:可以注入URL中的變量值,可以注入一個或者多個
單個 @PathVariable值
代碼:
@RequestMapping(value="/path/{ownerId}")
public String pathVariable(@PathVariable String ownerId, Model model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/path/1
返回結(jié)果:
{ownerId=1}
多個 @PathVariable值
作用: 可以注入URL中的變量值币狠,可以注入一個或者多個
代碼:
@RequestMapping(value="/path/{ownerId}/pet/{petId}")
public String pathVariable2(@PathVariable String ownerId, @PathVariable String petId, Model model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
map.put("petId", petId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/path/1/pet/1234
返回結(jié)果:
{petId=1234, ownerId=1}
3.4. @RequestParam
通過@RequestParam注入單個值
作用:可以從請求參數(shù)中獲取參數(shù)值
代碼:
@RequestMapping(value="/requestParam", method = RequestMethod.GET)
public String requestParam(@RequestParam("ownerId") int ownerId, ModelMap model) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestParam?ownerId=223
返回結(jié)果:
{ownerId=223}
通過@RequestParam注入多個值
作用: 可以從請求參數(shù)中獲取多個參數(shù)值
代碼:
@RequestMapping(value="/requestParam2", method = RequestMethod.GET)
public String requestParam2(@RequestParam Map<String,Object> map, ModelMap model) {
// Map<String,Object> map = new HashMap<String,Object>();
// map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestParam2?ownerId=223&a=4&c=5
返回結(jié)果:
{ownerId=223, a=4, c=5}
@RequestParam: required游两、defaultValue
作用:設(shè)置@RequestParam自定義參數(shù):如設(shè)置默認(rèn)值(defaultValue),是否必須(required)等等
代碼:
@RequestMapping("/requestParam3")
public String requestParam3(@RequestParam(value="inputStr", required=true, defaultValue="noInput") String inputStr,
ModelMap model) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("inputStr",inputStr );
model.addAttribute("map",map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestParam3?inputStr=myInput
此URL有inputStr值漩绵,則其值為myInput值
返回結(jié)果:
{inputStr=myInput}
訪問URL:
http://localhost:8100/request/requestParam3
此URL沒有inputStr值贱案,則其值為默認(rèn)值,即noInput
返回結(jié)果:
{inputStr=noInput}
3.5. @RequestBody
作用:@RequestBody: 獲取請求的內(nèi)容止吐。請求內(nèi)容為JSON宝踪,因為本工程設(shè)置請求為json,所以demo為:{“a”:1} 代碼:
@RequestMapping(value = "/requestBody", method = RequestMethod.POST)
public String requestBody(@RequestBody String body, ModelMap model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("body",body );
model.addAttribute("map",map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestBody
內(nèi)容為{“a”:1}
此請求為POST碍扔,需要使用postman等模擬POST請求
返回結(jié)果:
{body={"a":1}}
3.6. HttpEntity
作用:HttpEntity瘩燥,可以操作更原始的請求方法 代碼:
@RequestMapping(value="/httpEntity", method = RequestMethod.GET)
public String httpEntity(ModelMap model){
return "reqparameter/httpEntityForm";
}
@RequestMapping("/httpEntity")
public String httpEntity2(HttpEntity<byte[]> requestEntity, ModelMap model){
// 獲取header
String acceptLanguage = requestEntity.getHeaders().getFirst("Accept-Language");
// 獲取內(nèi)容:獲取body的內(nèi)容為空,暫時不知道原因
byte[] requestBody = requestEntity.getBody();
Map<String,Object> map = new HashMap<String,Object>();
map.put("acceptLanguage", acceptLanguage);
// map.put("content", new String(requestBody));
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/httpEntity
返回結(jié)果: 輸入上面URL不同,進入form表單颤芬,填寫內(nèi)容后,會轉(zhuǎn)到新的頁面如下
{acceptLanguage=zh-CN,zh;q=0.9,zh-TW;q=0.8}
3.7. @CookieValue
作用:獲取cookie里的值 代碼:
@RequestMapping("/cookieValue")
public String cookieValue(@CookieValue("JSESSIONID") String cookie,ModelMap model) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("cookie", cookie);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/cookieValue
返回結(jié)果:
{cookie=38EDB55B71BB4CCA6EF1A2CDA7F1BCC0}
3.8. @RequestHeader
作用:操作http header的值
獲取指定header里的值
代碼:
@RequestMapping("/requestHeader")
public String requestHeader (
@RequestHeader ("User-Agent") String userAgent,
@RequestHeader ("Host") String host,
@RequestHeader ("Cache-Control") String cacheControl,
ModelMap model) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("User-Agent", userAgent);
map.put("Host", host);
map.put("Cache-Control", cacheControl);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestHeader
此請求刷新需求刷新多次
返回結(jié)果:
{Cache-Control=max-age=0, User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, Host=127.0.0.1:8080}
獲取所有header封裝到Map
代碼:
@RequestMapping("/requestHeaderMap")
public String requestHeaderMap (@RequestHeader Map<String,String> map,
ModelMap model) {
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/requestHeaderMap
返回結(jié)果:
{host=127.0.0.1:8080, connection=keep-alive, user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, upgrade-insecure-requests=1, accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8, accept-encoding=gzip, deflate, br, accept-language=zh-CN,zh;q=0.9,zh-TW;q=0.8, cookie=JSESSIONID=38EDB55B71BB4CCA6EF1A2CDA7F1BCC0}
3.9. 自動封裝form表單請求到對象中
作用: 代碼:
@RequestMapping(value="/formModel", method = RequestMethod.GET)
public String form(){
return "reqparameter/formModel";
}
@RequestMapping("/formModel")
public String formPost(VO vo, ModelMap model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", vo.getName());
map.put("value", vo.getValue());
map.put("date", vo.getDate());
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/request/formModel
此URL進入form表單套鹅,我們填寫內(nèi)容后站蝠,會提交到formPost方法,此時時會自動封裝值到VO對象中卓鹿,打印內(nèi)容如下
返回結(jié)果:
{date=Sun Nov 12 22:11:22 CST 2017, name=fisr name, value=lastName}
3.10. HttpServletRequest + HttpServletResponse
作用:直接操作原始的HttpServletRequest 和 HttpServletResponse 代碼:
@RequestMapping("/httpServlet")
public void formPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String userAgent = request.getHeader("User-Agent");
String host = request.getHeader("Host");
String cacheControl = request.getHeader("Cache-Control");
PrintWriter pw = response.getWriter();
pw.println("User-Agent :"+ userAgent);
pw.println("Host :" + host);
pw.println("Cache-Control :" + cacheControl);
}
訪問URL:
http://localhost:8100/request/httpServlet
返回結(jié)果:
User-Agent :Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36
Host :127.0.0.1:8080
Cache-Control :null
3.11. @RequestMapping 參數(shù)配置params菱魔、headers
@RequestMapping 參數(shù)配置params
作用:通過params過濾請求,如下面的代碼吟孙,只有URL帶上myParam=myValue才能進入
代碼:
@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, params="myParam=myValue")
public String reqParameters(@PathVariable String ownerId, Model model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
t";
}
訪問URL:http://localhost:8100/request/reqparameters/1?myParam=myValue 可以進入到這個方法澜倦,
但是以下URL無法進入這個方法:http://localhost:8100/request/reqparameters/1
備注: 其他條件聚蝶,也可以這樣: “myParam”, “!myParam”, or “myParam=myValue”
@RequestMapping 參數(shù)配置headers
作用:通過headers過濾請求,請求頭里必須帶上myParam藻治,且值為myValue
代碼:
@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, headers="myParam=myValue")
public String headerParameters(@PathVariable String ownerId, Model model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
訪問URL:
http://localhost:8100/reqparameters/1
如果使用POST請求碘勉,請使用postman,并在請求頭里必須帶上myParam桩卵,且值為myValue
4. @RequestMapping支持的返回類型
4.1. ResponseParameterController
以下代碼都在此類中
@Controller
@RequestMapping(value = "/response")
public class ResponseParameterController {
...
}
4.2. 使用到JSP
下面用到j(luò)sp的頁面如下验靡,都在META-INF\resources\WEB-INF\page\resparameter目錄下:
showInput.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Request Parameter</title>
</head>
<body>
${map}
</body>
</html>
4.3. 返回一個頁面的地址
默認(rèn)情況下,返回一個字符串雏节,表示轉(zhuǎn)到一個指定頁面胜嗓,上面的demo都是這個模式
@RequestMapping(value="/path/{ownerId}")
public String pathVariable(@PathVariable String ownerId, Model model){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", ownerId);
model.addAttribute("map", map);
return "reqparameter/showInput";
}
4.4. @ResponseBody
@ResponseBody: 直接返回字符串內(nèi)容
作用:此注解注解的方法返回字符串
代碼:
@RequestMapping(value = "/responseBody", method = RequestMethod.GET)
@ResponseBody
public String responseBodyString() {
return "Hello World";
}
訪問URL:
http://localhost:8100/response/responseBody
返回結(jié)果:
"Hello World"
@ResponseBody:方法返回對象,系統(tǒng)自動轉(zhuǎn)化為json
作用:方法返回對象钩乍,返回客戶端時系統(tǒng)自動轉(zhuǎn)化為json
代碼:
@RequestMapping(value = "/responseBodyMode", method = RequestMethod.GET)
@ResponseBody
public VO responseBodyMode() {
return new VO();
}
訪問URL:
http://localhost:8100/response/responseBodyMode
返回結(jié)果:
{ "date":1510497345620, "name":"name", "value":"value" }
4.5. ResponseEntity
作用:返回一個ResponseEntity 代碼:
@RequestMapping("/responseEntity")
public ResponseEntity<String> responseEntity(){
// do something with request header and body
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
訪問URL:
http://localhost:8100/response/responseEntity
返回結(jié)果:
"Hello World"
4.6. ModelAndView
作用:返回ModelAndView 代碼:
public ModelAndView modelAndView(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("ownerId", "1");
map.put("petId", "23");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("resparameter/showInput");
modelAndView.addObject("map", map);
return modelAndView;
}
訪問URL:
http://localhost:8100/response/modelAndView
返回結(jié)果:
{petId=23, ownerId=1}