在使用springMVC时,离不开使用注解,注解的正确使用也会时代码简洁很多,今天抽了点时间整理了一些常用的注解。
- 1、@Controller
Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将视图呈现给用户。SpringMVC使用 @Controller定义控制器,它还允许自动检测定义在类路径下的组件并自动注册。如果想自动检测生效,需要在XML头文件中引入spring-context:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
<!-- ... --></beans>
- 2、@RequestMapping
详解:
@RequestMapping 注解用来映射请求路径,如果标注在某个 controller 的类级别上,则表明访问此路径下的方法都要加上其配置的路径,最长用的是标注在方法上,表明哪个具体的方法接受处理某次请求。
@Controller
@RequestMapping(value="/book")
public class BookController {
@RequestMapping(value="/title")
public String getTitle(){
return "title";
}
@RequestMapping(value="/content")
public String getContent(){
return "content";
}
}
由于BookController类加了value=”/book”的“@RequestMapping”的注解,所有相关路径都要加上”/book”,即请求的url分别为:
http://localhost:8080/book/title
http://localhost:8080/book/content
“@RequestMapping”的value值前后是否有“/”对请求的路径没有影响,即value=”book” 、”/book”、”/book/”其效果是一样的
属性:
vale:指定请求的实际 url
1)、指定具体值,例如前面的 value=”/book”
2)、含变量的一类值:
@RequestMapping(value="/get/{bookId}")
public String getBookById(@PathVariable String bookId,Model model){
model.addAttribute("bookId", bookId);
return "book";
}
路径中的 bookId 是变量,@PathVariable 注解即提取路径中的变量值
3、ant风格的值
ant风格是什么? 使用以下通配符来匹配路径。
a、? 匹配任何单字符
b、* 匹配0或者任意数量的字符
c、** 匹配0或者更多的目录
例如:
@RequestMapping(value=”/get/id?”):可匹配“/get/id1”或“/get/ida”,但不匹配“/get/id”或“/get/idaa”;
@RequestMapping(value=”/get/id*”):可匹配“/get/idabc”或“/get/id”,但不匹配“/get/idabc/abc”;
@RequestMapping(value=”/get/id/*”):可匹配“/get/id/abc”,但不匹配“/get/idabc”;
@RequestMapping(value=”/get/id/**/{id}”):可匹配“/get/id/abc/abc/123”或“/get/id/123”,也就是Ant风格和URI模板变量风格可混用;
4. 含正则表达式的一类值
@RequestMapping(value=”/get/{idPre:\d+}-{idNum:\d+}”):可以匹配“/get/123-1”,但不能匹配“/get/abc-1”,这样可以设计更加严格的规则。
可以通过@PathVariable 注解提取路径中的变量(idPre,idNum)
5. 或关系
例如:@RequestMapping(value={“/get”,”/fetch”} )即 /get或/fetch都会映射到该方法上
method:指定请求的 method类型, GET、POST、PUT、DELETE等;
例如:@RequestMapping(value=”/get/{bookid}”,method={RequestMethod.GET,RequestMethod.POST})
params:指定请求参数包含内容
例如:@RequestMapping(params=”action=del”),请求参数包含“action=del”,如:http://localhost:8080/book?action=del
headers:指定请求头
例如:@RequestMapping(value=”/header/id”, headers = “Accept=application/json”):表示请求的URL必须为“/header/id 且 请求头中必须有“Accept =application/json”参数即可匹配。
3、@PathVariable
详解:@PathVariable用于绑定 URL路径上添加的参数
例如:
@RequestMapping(value="/get/{bookId}")
public String getBookById(@PathVariable String bookId,Model model){
model.addAttribute("bookId", bookId);
return "book";
}
也可以绑定多个参数:
例如:
@RequestMapping(value="/get/{bookId}/{username}")
public String getBookById(@PathVariable String bookId,@PathVariable String username,Model model){
model.addAttribute("bookId", bookId);
return "book";
}
@PathVariable中的参数可以是任意的简单类型,如int, long, Date等等。Spring会自动将其转换成合适的类型或者抛出 TypeMismatchException异常。当然,我们也可以注册支持额外的数据类型。
如果@PathVariable使用Map
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
6、@ResponseBody
详解:
@ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。@ResponseBody在输出JSON格式的数据时
7、@RestController
详解:
注:4.1以后出现的新特性
注解本身使用@Controller和@ResponseBody注解。使用了这个注解的类会被看作一个controller-使用@RequestMapping的方法有一个默认的@ResponseBody注解。 即使用了@RestController 无需再在每个方法前添加@ResponseBody了。
8、@ModelAttribute
详解:
@ModelAttribute可以作用在方法或方法参数上,当它作用在方法上时,标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。控制器中的@ModelAttribute方法会在@RequestMapping方法调用之前而调用。
该注解有两个用法,一个是用于方法上,一个是用于参数上;
用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;
要绑定的值来源于:
A) @SessionAttributes 启用的attribute 对象上;
B) @ModelAttribute 用于方法上时指定的model对象;
C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
例如:
用到方法上@ModelAttribute的示例代码:
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);
用在参数上的@ModelAttribute示例代码:
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
}
首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。
详细使用方法参考:http://blog.csdn.net/xiejx618/article/details/43638537
9、@SessionAttributes:
详解:
该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。
该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;
例如:
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}
10、@RequestHeader
详解:
@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。
例如:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}
上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。
11、@CookieValue
详解:
@CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。
示例:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}
即把JSESSIONID的值绑定到参数cookie上。
未完待续。。。。。欢迎留言提示!