value:定义处理方法的请求的URL地址。(重点)
method:定义处理方法的httpmethod类型,如GET、POST等。(重点)
params:定义请求的URL中必须包含的参数。或者不包含某些参数。(了解)
headers:定义请求中RequestHeaders必须包含的参数。或者不包含某些参数。(了解)
@RequestMapping有两种标注方式,一种是标注在类级别上,一种是标注在方法级别上。标注在方法上时,value表示访问该方法的URL地址。标注在类上时,value相当于一个命名空间,即访问该Controller下的任意方法都需要带上这个命名空间。例如:
Java代码
1@Controller 2@RequestMapping("/example") 3publicclassExampleController{ 4 5@RequestMapping 6publicStringexecute(){ 7return"example_page"; 8} 9 10@RequestMapping("/todo") 11publicStringdoSomething(){ 12return"example_todo_page"; 13} 14 15}1:/example.action:执行的是execute()方法。execute()方法的@RequestMapping注解缺省value值,在这种情况下,当访问命名空间时默认执行的是这个方法。方法级别上的@RequestMapping标注是必须的,否则方法无法被正确访问。
2:/example/todo.action执行的是doSomething()方法。类级别上的@RequestMapping标注不是必须的,在不写的情况下,方法上定义的URL都是绝对地址,否则,方法上定义的URL都是相对于它所在的Controller的。
method的值一旦指定,那么,处理方法就只对指定的httpmethod类型的请求进行处理。这里方法/register只能使用get请求,使用post请求无法访问
1@RequestMapping(value="/register",method=RequestMethod.GET) 2publicStringregister1(){ 3return"example_register_get_page"; 4} 5 6@RequestMapping(value="/register",method=RequestMethod.POST) 7publicStringregister2(){ 8return"example_register_post_page"; 9}可以为多个方法映射相同的URI,不同的httpmethod类型,SpringMVC根据请求的method类型是可以区分开这些方法的。当/example/register.action是以GET的方式提交的时候,SpringMVC调用register1()来处理请求;若是以POST的方式提交,则调register2()来处理提交的请求。
method若是缺省没指定,并不是说它默认只处理GET方式的请求,而是它可以处理任何方式的httpmethod类型的请求。指定method是为了细化映射(缩小处理方法的映射范围),在method没有指定的情况下,它的映射范围是最大的。
与method相类似,作用是为了细化映射。只有当URL中包含与params值相匹配的参数的请求,处理方法才会被调用。
1@RequestMapping(value="/find",params="target") 2publicStringfind1(){ 3return"example_find1_page"; 4} 5 6@RequestMapping(value="/find",params="!target") 7publicStringfind2(){ 8return"example_find2_page"; 9} 10 11@RequestMapping(value="/search",params="target=product") 12publicStringsearch1(){ 13return"example_search1_page"; 14} 15 16@RequestMapping(value="/search",params="target!=product") 17publicStringsearch2(){ 18return"example_search2_page"; 19}find1():请求的URL中必须要有target参数,才能够到达此方法。如/example/find.action?target或/example/find.action?target=x等
find2():请求的URL中必须不能有target参数,才能够到达此方法。如/example/find.action或/example/find.action?q=x等
search1():请求的URL中必须要有target=product参数,才能够到达此方法。如/example/search.action?target=product等
*search2():请求的URL中必须不能有target=product参数,才能够到达此方法。如/example/search.action?target=article等*
headers的作用也是用于细化映射。只有当请求的RequestHeaders中包含与heanders值相匹配的参数,处理方法才会被调用。
1@RequestMapping(value="/specify",headers="accept=text/*") 2publicStringspecify(){ 3return"example_specify_page"; 4}请求的RequestHeaders中Accept的值必须匹配text/*(如text/html),方法才会被调用。
本文内容总结:@RequestMapping参数说明,@RequestMapping的用法,@RequestMapping(method):指定页面请求方式,@RequestMapping(params),@RequestMapping(headers),@RequestMapping支持Ant风格的通配符,
原文链接:https://www.cnblogs.com/caoyc/p/5635173.html