SpirngMVC3.0实现rest风格

SpirngMVC3.0实现rest风格
2010年11月26日 星期五 23:01
@RequestMapping @RequestParam @PathVariable @ModelAttributes @SessionAttributes @CookieValue @RequestHeader 都是Spring MVC REST中的注释方法,这几种注释方法的用法如下:
1#Controller 示例
URL示例: POST /users/query?userId=1234
@Controller
public class 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句话需要翻译一下
<taglib 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 信息的共享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值