spring rest 中的 注解使用
[url]http://hi.baidu.com/china8jie/blog/item/492b367f09d5ac052a388a62.html
[/url]
@RequestMapping @RequestParam @PathVariable @ModelAttributes @SessionAttributes @CookieValue @RequestHeader 都是Spring MVC REST中的注释方法,这几种注释方法的用法如下:
1#Controller 示例
URL示例: POST /users/query?userId=1234
@Controller
public class <SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=Java">Java</SPAN>BlogerController {
@Autowired
JavaBlogerService serviceLayer;
@RequestMapping
public String delete(@RequestParam String userId ){
serviceLayer.query (userId);
return "redirect:list";
}
}
2#CookieValue 示例
@RequestMapping ("/userList")
public String delete(@CookieValue("JSESSIONID") String sessionId ){
}
注释表明,CookieValue方法的参数可以绑定到HTTP的Cookie。支持在Servlet和Portlet环境注明处理方法。
3#RequestHeader示例
显示结果
User-Agent: Mozilla/0 (Windows; U; Windows NT 1; en-GB; rv:9.0.11)
Gecko/2009060215 Firefox/0.11 (.NET CLR 30729)
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Keep-Alive: 300
@RequestMapping("/showJavaBlogerInfo")
public void showHeadInfo(
@RequestHeader("User-Agent"),String userAgent,
@RequestHeader("Accept-Encoding"),String encoding,
@RequestHeader("Keep-Alive"),long keepAlive, ){
}
4#HiddenHttpMethodFilter 示例
·Allows HTML browsers to emulate PUT and DELETE requests HTML forms only support GET/POST natively
·Special hidden parameter determines RequestMethod
上面2句话需要翻译一下
<[email=%@taglib]%@taglib[/email] prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form method="delete">
<input value="Delete" type="submit">
</form:form>
@RequestMapping (metthod=RequestMethod.DELETE)
public void delete (@RequestParam String userId) {
System.out.println(userId);
}
5#/** 分页信息装载 */ 示例
@RequestMapping(value = "/page/{pageNo}", method = RequestMethod.GET)
public String pageLoad(@PathVariable int pageNo) {
String mapping = "mainPage";
System.out.println(pageNo);
return mapping;
}
6#SessionAttributes 示例
@Controller
@SessionAttributes( "currentUser " )
public class GreetingController {
@RequestMapping
public void hello(@ModelAttribute( "currentUser " ) User user) {
// user.sayHello()
}
//
}
使用@ModelAttribute 需要访问 Session 属性的 controller 上加上 @SessionAttributes,然后在 action 需要的 User 参数上加上 @ModelAttribute,并保证两者的属性名称一致。SpringMVC 就会自动将 @SessionAttributes 定义的属性注入到 ModelMap 对象,在 setup action 的参数列表时,去 ModelMap 中取到这样的对象,再添加到参数列表。只要我们不去调用 SessionStatus 的 setComplete() 方法,这个对象就会一直保留在 Session 中,从而实现 Session 信息的共享。