前面我们学习了Spring MVC最最基本的使用步骤及如何引用静态资源。
Spring MVC提供了一个基于注释的编程模型,今天,我们来学习一下Annotated Controllers(注释的解析器),官网地址
@Controller和@RestController构成了使用注释来表达请求映射,请求输入,异常处理等等。带注释的控制器具有灵活的方法参数,不必扩展基类,也不必实现特定接口。
//@RestController 定义接口,返回数据(不需要再处理方法上定义@responseBody)
@RequestMapping:
作用:标注用于请求映射到控制器的方法
属性:可以通过
URL(path=value)、
HTTP方法(method)、
请求参数(params)、
请求参数的条件(
produces)、
标头(headers)
和
提交内容类型(consumes)
进行匹配
范围:在类级别上用于表示共享映射(如同struts2 @namespace) 或 在方法级缩小特定的端点映射(如同struts2 @action)
@Controller
@RequestMapping(value = "/rmc")// 可以相当于struts2中的namespace
public class RequestMappingController {
@RequestMapping(value = "req")//相当于struts2中的action
public String reqm(){
return "index";
}
}
下面是属性的详解:
HTTP方法(method)具体快捷的变种:
@
GetMapping
*[相当于=@RequestMapping(method={RequestMethod.GET})]
@PostMapping*[相当于=@RequestMapping(method={RequestMethod.POST})]
@PutMapping
@DeleteMapping
@PatchMapping
URL模式(value=path):
? 匹配一个字符
* 匹配路径段中的零个或多个字符
** 匹配零个或多个路径段
* 匹配路径段中的零个或多个字符
** 匹配零个或多个路径段
实例:(该实例的类名就是上面代码中的类:RequestMappingController,路径为:/rmc)
/**
* 访问请求:http://localhost:8080/rmc/reqq?
* ?代表匹配一个任意字符
* @return 返回的视图
*/
@GetMapping(value ="reqq?")
public String reqQues(){
return "index";
}
/**
* 访问请求:http://localhost:8080/rmc/reqq*
* *代表匹配零个或多个字符
*/
@GetMapping(value ="reqs*")
public String reqStar(){
return "index";
}
/**
* 访问请求:http://localhost:8080/rmc/reqs/1/1/1/q
* **匹配零个或多个路径段
*/
@GetMapping(path ="reqs/**/q")
public String reqTwoStar(){
return "index";
}
请求参数(params)
/**
* 请求路径:http://localhost:8080/rmc/reqp?id=10001
* @return
*/
@RequestMapping(value = "reqp",params ={"id=10001"})
public String reqParams(){
return "index";
}
当请求路径没有带这个参数时就会报错抛出异常:
提交内容类型(consumes):
RequestMappingController类:
// 相当于@RequestMapping(value = "reqcs",method = RequestMethod.POST,consumes = {"text/plain"})
@PostMapping(value = "reqcs",consumes = {"text/plain"})
public String reqcs(){
return "index";
}
index.jsp页面:
<h1>requestMapping:</h1>
<form action="${pageContext.request.contextPath}/rmc/reqcs" method="post" enctype="text/plain">
<input type="text">
<input type="submit" value="sub">
</form>
如果index.jsp页面的enctype和类中的consumes提交类型不一致时就会报错,抛出异常:
标头(headers):
我们可以F12看看发送请求后,headers有哪些内容:
/**
* 加上该标头就表明:只能是Host为localhost:8080的请求才能够访问
*/
@RequestMapping(value = "reqh",headers = {"Host=localhost:8080"})
public String reqHeaders(){
return "index";
}