学习@RequestMapping注解,参考Spring API
[email protected]可以修饰在类类型和方法上
①.修饰在类定义上: 提供初步的URL映射,相对于web应用根目录。
②.修饰在方定义法上: 提供更细致的URL映射,若类定义上有注解,则相对于类定义上的URL映射。否则相对于web应用根目录映射
代码1:
只在方法上加@RequestMapping:
1: @Controller2: public class TestRequestMapping {3: @RequestMapping("/testMethod")4: public String testMethod() {5: System.out.println("testMethod");6: return "success";7: }8: }URL:
1: <a href="testMethod">testMethod</a>
代码2:
在类和方法上加@RequestMapping:
1: @RequestMapping("/testClass")2: @Controller3: public class TestRequestMapping {4: @RequestMapping("/testMethod")5: public String testClassAndMethod() {6: System.out.println("testClassAndMethod");7: return "success";8: }9: }URL:
1: <a href="testClass/testMethod">testClassAndMethod</a>
代码3:
只在类上加@RequestMapping:
1: @RequestMapping("/testClass")2: @Controller3: public class TestRequestMapping {4:5: public String testClassAndMethod() {6: System.out.println("testClass");7: return "success";8: }9: }URL:
1: <a href="testClass">testClass</a>
运行时,发出Tomcat警告: No mapping found for HTTP request with URI [/mvc02/testClass] in DispatcherServlet with name ‘dispatcherServlet‘。
也就说在类上加注解后,必须在方法上也加注解。查看api,发现开头第一句 Annotation for mapping web requests onto specific handler classes and/or handler methods
好吧没仔细看api,classes and/or handler methods。(⊙﹏⊙)b
[email protected]有7个参数,value,method,headers,params之间是与的关系:
String[] value URL路径:"/myPath/myMethod" RequestMethod[] method 请求方式:GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE String[] headers 请求头,用法与params类似,支持简单表达式 String[] params 请求参数,支持简单表达式
params={"name"}:参数中必须包含名为name的参数
params={"!name"}:参数中不能包含名为name的参数
params={"name!=xx"}:参数中若包含了名为name的参数,
则name!=xx。参数中也可以不包含名为name的参数
params={"name=xx"}:参数中必须包含名为name的参数,
且name=xx。String[] produces 指定哪些媒体类型可以不需要 String[] consumes 指定哪些媒体类型可以额外 添加 String name 映射名称
method——代码:
1: @RequestMapping("/testClass")2: @Controller3: public class TestRequestMapping {4: @RequestMapping(value = "/testMethod_GET", method = RequestMethod.GET)5: public String testMethod_GET() {6: System.out.println("method running....");7: return "success";8: }9:10: @RequestMapping(value = "/testMethod_POST", method = RequestMethod.POST)11: public String testMethod_POST() {12: System.out.println("method running....");13: return "success";14: }15:16: }URL:
1: <form action="testClass/testMethod_POST" method="post">2: <input type="submit" value="testMethod_POST"/>3: </form>4: <br/><br/>5:6: <a href="testClass/testMethod_GET">testMethod_GET</a>
时间: 2024-10-12 22:07:29