spring的几个传参方法

1.@PathVariable

通过URI template 样式映射时,使用@PathVariable

<script type="text/javascript">
$('#setButton').click(function() {   $("#removeId").val(spId);   $("#toolBarForm").attr("action","/test/"+$("#id").val());   $("#toolBarForm").submit(); });
</script>

Controller层接收

    @RequestMapping( value = "/test/{id}", method = RequestMethod.POST )   
    public String test(String removeId,@PathVariable String id,HttpServletRequest request,HttpServletResponse response,Model model) {      
        return this.listLoad(request, response, model);    
    }

有一个地方需要注意的是 id必须是不带符号的字符串,如果是中间带逗号的字符串,后台接收时会出错


2.@RequestParam

通过在url用?挂参数来传参

<script type="text/javascript">$('#setButton').click(function() {
  $("#removeId").val(spId);
  $("#toolBarForm").attr("action","/test2?id="+$("#id").val());
  $("#toolBarForm").submit();
});</script>

Controller接收

    @RequestMapping( value = "/test2", method = RequestMethod.POST )   
    public String batchSet(String removeId,@RequestParam String id,HttpServletRequest request,HttpServletResponse response,Model model) {      
       return this.listLoad(request, response, model);    
    }

3.@SessionAttributes
通过在controller上加上注解,绑定HttpSession中attribute的值

@Controller
@SessionAttributes({"session"})
public class TestController extends BaseController {
}

绑定的方法,可以通过model.addAttribute("session",session);

取法可以通过
HttpSession.getAttribute("session");

也可以

HttpServletRequest.getSession.getAttribute("session");

 

4.@ModelAttribute

这一种还没怎么用过,应该是被@ModelAttribute注解过的方法会在controller的每个方法执行之前被调用一遍

public class HelloWorldController {  
 
      @ModelAttribute  
      public void populateModel(@RequestParam String abc, Model model) {  
         model.addAttribute("attributeName", abc);  
       }  
 
        @RequestMapping(value = "/helloWorld")  
        public String helloWorld() {  
          return "helloWorld";  
     }  

下面是一个具体解释@ModelAttribute的链接

http://wangwengcn.iteye.com/blog/1677024

 

 

posted @ 2014-04-30 13:54  歌神小猪哥  阅读(662)  评论(0编辑  收藏  举报