在RequestMapping中还可以指定一个属性method,其主要对应的值有RequestMethod.GET和RequestMethod.POST,利用该属性可以严格的控制某一方法只能被标记的请求路径对应的请求方法才能访问,如指定method的值为GET,则表示只有通过GET方式才能访问该方法,默认是都可以访问。
在SpringMVC中常用的注解还有@PathVariable,@RequestParam,@PathVariable标记在方法的参数上,利用它标记的参数可以利用请求路径传值,看下面一个例子
- @RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST)
- public void comment(Comment comment,@PathVariable int blogId, HttpSession session, HttpServletResponse response) throws IOException {
- }
在该例子中,blogId是被@PathVariable标记为请求路径变量的,如果请求的是/blog/comment/1.do的时候就表示blogId的值为1. 同样@RequestParam也是用来给参数传值的,但是它是从头request的参数里面取值,相当于request.getParameter("参数名")方法。
在Controller的方法中,如果需要WEB元素HttpServletRequest,HttpServletResponse和HttpSession,只需要在给方法一个对应的参数,那么在访问的时候SpringMVC就会自动给其传值,但是需要注意的是在传入Session的时候如果是第一次访问系统的时候就调用session会报错,因为这个时候session还没有生成。
接下来讨论一下方法的返回值,主要有一下情况:
返回一个ModelAndView,其中Model是一个Map,里面存放的是一对对的键值对,其可以直接在页面上使用,View是一个字符串,表示的是某一个View的名称
返回一个View,也就是一个字符串,这个时候如果需要给页面传值,可以给方法一个Map参数,该Map就相当于一个Model,往该Model里面存入键值对就可以在页面上进行访问了
返回一个Model也就是一个Map,这个时候将解析默认的生成的view name。
什么也不返回,这个时候可以利用HttpServletResponse进行返回,也可以直接使用printStream进行返回
下面是一个简单的实例
- @RequestMapping("/{owner}/index")
- public String userIndex(Map<String, Object> map,@PathVariable String owner, HttpServletRequest request) throws ParserException {
- List<DefCategory> categories = categoryService.find(owner);
- int offset = Util.getOffset(request);
- Pager<Blog> pager = blogService.find(owner, 0, offset, maxResults);
- int totalRecords = pager.getTotalRecords();
- List<Blog> blogs = pager.getData();
- Util.shortBlog(blogs);
- List<Message> messages = messageService.find(owner, 0, 5).getData();
- Util.shortMessage(messages, 20);
- map.put("messages", messages);
- map.put("totalRecords", totalRecords);
- List<BlogStore> stores = storeService.find(owner, 0, 5).getData();
- map.put("maxResults", maxResults);
- map.put("blogs", blogs);
- map.put("totalRecords", totalRecords);
- map.put("owner", userService.find(owner));
- map.put("defCategories", categories);
- map.put("stores", stores);
- return "blog/userIndex";
- }