参注解的使用
-
@PathVariable
路径变量
获取请求路径里的变量,将key和value都写在一起并都写在url上。
如果不在括号里写指定获取哪个参数的值,那么就是获取全部参数的值,用map<String,String>来接收这个值。必须是String,String类型@PathVariable(“id”)里的id与{id}保持一致。如果{id}变成了{ids},那么@PathVariable(“id”)变为@PathVariable(“ids”)
@GetMapping("/id/{id}/username/{username}") public Map test1(@PathVariable("id") int id, @PathVariable("username") String username, @PathVariable Map<String,String> allPath){ Map<String, Object> map = new HashMap(); map.put("id", id); map.put("username", username); map.put("allPath", allPath); return map; }
<a href="/id/1/username/lisi">path variable</a>
{"allPath":{"id":"1","username":"lisi"},"id":1,"username":"lisi"}
-
@RequestHeader
获取请求头
将请求头的信息都可以获取出来,如果写key就是获取指定的信息,如果没有参数就是全部的信息,用map<String,String>来接收这个值。必须是String,String类型@GetMapping("/id/{id}/username/{username}") public Map test2(@RequestHeader("Host") String host, @RequestHeader("User-Agent") String agent, @RequestHeader Map<String,String> allPara){ Map<String, Object> map = new HashMap(); map.put("host", host); map.put("User-Agent", agent); map.put("allPara", allPara); return map; }
{ "host":"localhost:8081", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36", "allPara":{ "host":"localhost:8081", "connection":"keep-alive", "cache-control":"max-age=0", "sec-ch-ua":"\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"", "sec-ch-ua-mobile":"?0", "upgrade-insecure-requests":"1", "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36", "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "sec-fetch-site":"same-origin", "sec-fetch-mode":"navigate", "sec-fetch-user":"?1", "sec-fetch-dest":"document", "referer":"http://localhost:8081/", "accept-encoding":"gzip, deflate, br", "accept-language":"zh-CN,zh;q=0.9" } }
-
@RequestParam
获取请求参数@GetMapping("/user") public Map test3(@RequestParam("id") int id, @RequestParam("name") String username, @RequestParam("inters") List<String> inters, @RequestParam Map<String,String> allPara){ Map<String, Object> map = new HashMap(); map.put("id", id); map.put("username", username); map.put("inters", inters); map.put("allPara", allPara); return map; }
请求的url: http://localhost:8081/user?id=1&name=renshuai&inters=hhhh&inters=3333
{ "inters":[ "hhhh", "3333" ], "id":1, "allPara":{ "id":"1", "name":"renshuai", "inters":"hhhh" }, "username":"renshuai" }
-
@CookieValue
获取cookie值
如果不加参数就是获取cookie的所有信息,用Cookie来接收@GetMapping("/user") public Map test3(@RequestParam("id") int id, @RequestParam("name") String username, @RequestParam("inters") List<String> inters, @RequestParam Map<String,String> allPara, @CookieValue Cookie cookie){ Map<String, Object> map = new HashMap(); map.put("id", id); map.put("username", username); map.put("inters", inters); map.put("allPara", allPara); map.put("cookie", cookie); return map; }
-
@RequestBody
获取请求体(POST)
当在处理post请求的时候,用该注解,将表单里所有的参数以及值都获取到@PostMapping("/addUser") public Map test4(@RequestBody String content){ Map<String, Object> map = new HashMap(); map.put("content", content); return map; }
<form method="post" action="/addUser"> <input type="text" name="name"> <input type="text" name="inters"> <input type="text" name="country"> <input type="submit" value="Submit"> </form>
{ "content":"name=111&inters=222&country=333" }
-
@RequestAttribute
获取request域属性
sendRequest方法接收ask请求,接收之后设置了一些属性后转发给success请求。
getMethod方法接收success请求,用注解@RequestAttribute获取请求里的attribute,在括号里指定key,得到对应的value
这里必须指定key了,如果不指定请求会接收不到public class RequestController { @RequestMapping("/ask") public String sendRequest(HttpServletRequest request){ request.setAttribute("msg","Success"); request.setAttribute("code", 200); return "forward:success"; } @ResponseBody @GetMapping("/success") public Map getMethod(@RequestAttribute("msg") String msg, @RequestAttribute("code") int code){ Map<String, Object> map = new HashMap<>(); map.put("msg",msg); map.put("code", code); return map; } }
{"msg":"Success","code":200}
-
@MatrixVariable
矩阵变量
url的格式为:
/param1;key1=value;key2=value2;key2=value3/param2;key1=value1…
相当于param1里的数据是key1=value;key2=value2;key2=value3
如果是集合类型,有两种表达方式:
- key1=value1;key1=value2
- key1=value1,value2springBoot里,默认是禁用矩阵变量的。禁用的原理是:
在WebMvcAutoConfiguration类中有一个configurePathMatch方法,里面有UrlPathHelper 这个类,这个类里有一个属性removeSemicolonContent ,表示如果在url里遇到;时,将;后面的数据都抹掉,这个值默认是true,所以这种方式与矩阵变量特有的url访问方式冲突public void configurePathMatch(PathMatchConfigurer configurer) { if (this.mvcProperties.getPathmatch().getMatchingStrategy() == MatchingStrategy.PATH_PATTERN_PARSER) { configurer.setPatternParser(new PathPatternParser()); } configurer.setUseSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseSuffixPattern()); configurer.setUseRegisteredSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern()); this.dispatcherServletPath.ifAvailable((dispatcherPath) -> { String servletUrlMapping = dispatcherPath.getServletUrlMapping(); if (servletUrlMapping.equals("/") && this.singleDispatcherServlet()) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setAlwaysUseFullPath(true); configurer.setUrlPathHelper(urlPathHelper); } }); }
public class UrlPathHelper { public static final String PATH_ATTRIBUTE = UrlPathHelper.class.getName() + ".PATH"; static final boolean servlet4Present = ClassUtils.hasMethod(HttpServletRequest.class, "getHttpServletMapping", new Class[0]); private static final String WEBSPHERE_URI_ATTRIBUTE = "com.ibm.websphere.servlet.uri_non_decoded"; private static final Log logger = LogFactory.getLog(UrlPathHelper.class); @Nullable static volatile Boolean websphereComplianceFlag; private boolean alwaysUseFullPath = false; private boolean urlDecode = true; private boolean removeSemicolonContent = true; private String defaultEncoding = "ISO-8859-1"; private boolean readOnly = false; public static final UrlPathHelper defaultInstance = new UrlPathHelper(); public static final UrlPathHelper rawPathInstance;
要想可以使用矩阵变量,就得自定义UrlPathHelper 里的属性值,有两种方式。
方式一:实现WebMvcConfigurer 接口,重写configurePathMatch方法,将 urlPathHelper.setRemoveSemicolonContent(false)
package com.study.springboot2.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.HiddenHttpMethodFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.util.UrlPathHelper; @Configuration(proxyBeanMethods = false) public class WebConfig implements WebMvcConfigurer { public HiddenHttpMethodFilter hiddenHttpMethodFilter(){ HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); methodFilter.setMethodParam("_m"); return methodFilter; } @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } }
方式二:
注入一个WebMvcConfigurer@Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer() { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } }; }
设置完之后就可以使用矩阵变量了。
/test/1;userid=123;username=abc,desd,asd/2;userid=444;username=2wew;username=54gdf
需要注意的是:
controller的映射路径得写成{path1}这种格式才可以,在下一个/之前,也就是userid=123;username=abc,desd,asd,这些都是1的数据
userid=444;username=2wew;username=54gdf,这些都是2的数据想获取1路径下的userid,得加pathVar,这里的值与@GetMapping("/test/{path1}/{path2}")这里的路径名保持一致
//请求的url:http://localhost:8081/test/1;userid=123;username=abc,desd,asd/2;userid=444;username=2wew;username=54gdf @GetMapping("/test/{path1}/{path2}") public Map test5(@MatrixVariable(value = "userid",pathVar = "path1") Integer id , @MatrixVariable(value = "username",pathVar = "path1") List<String> username , @MatrixVariable(value = "userid",pathVar = "path2") Integer id1 , @MatrixVariable(value = "username",pathVar = "path2") List<String> username1){ Map<String, Object> map = new HashMap(); map.put("id", id); map.put("id1", id1); map.put("username", username); map.put("username1", username1); return map; } //请求的url:http://localhost:8081/test1/test1;userid=123;username=abc,desd,asd @GetMapping("/test1/{path1}") public Map test6(@MatrixVariable(value = "userid") Integer id , @MatrixVariable(value = "username") List<String> username){ Map<String, Object> map = new HashMap(); map.put("id", id); map.put("username", username); return map; }