@RequestMapping注解方法返回值意义

来源:互联网 发布:苏州 青少年编程 编辑:程序博客网 时间:2024/05/20 22:00

我们讲解一下之前用的@RequestMapping注解和controller方法返回值


一、@RequestMapping注解作用
1.url映射
定义controller方法对应的url,进行处理器映射使用。
[java] view plain copy
  1. //商品查询列表  
  2. //@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url  
  3. //一般建议将url和方法写成一样  
  4. @RequestMapping("/queryItems")  
  5. public ModelAndView queryItems()throws Exception{  
  6.     //......  
  7. }  

2.窄化请求映射
[java] view plain copy
  1. //商品的Controller  
  2. @Controller  
  3. //为了对url进行分类管理,可以在这里定义根路径,最终访问url是根路径+子路径  
  4. //比如:商品列表:/items/queryItems.action  
  5. @RequestMapping("items")  
  6. public class ItemsController {  
  7.     //......  
  8. }  

限制http请求方法
出于安全性考虑,对http的链接进行方法限制。
[java] view plain copy
  1. //商品信息修改页面显示  
  2. //@RequestMapping("/editItems")  
  3. //限制http请求方法  
  4. @RequestMapping(value="/editItems",method={RequestMethod.POST})  
  5. public ModelAndView editItems()throws Exception{  
  6.     //......  
  7. }  
如果限制请求为post方法,进行get请求,报错:


为了以后开发方便再改回来,让它支持GET和POST就不会出错了
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})

二、controller方法返回值
1.返回ModelAndView
需要方法结束时,定义ModelAndView,将model和view分别进行设置。

2.返回string
如果controller方法返回string,

(1)表示返回逻辑视图名。
真正视图(jsp路径)=前缀+逻辑视图名+后缀
[java] view plain copy
  1. @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})  
  2. public String editItems(Model model)throws Exception{  
  3.           
  4.     //调用service根据商品id查询商品信息  
  5.     ItemsCustom itemsCustom=itemsService.findItemsById(1);  
  6.           
  7.     //通过形参中的model将model数据传到页面  
  8.     //相当于modelAndView.addObject方法  
  9.     model.addAttribute("itemsCustom",itemsCustom);  
  10.           
  11.     return "items/editItems";  
  12. }  

(2)redirect重定向
商品修改提交后,重定向到商品查询列表。
redirect重定向特点:浏览器地址栏中的url会变化。修改提交的request数据无法传到重定向的地址。因为重定向后重新进行request(request无法共享)
[java] view plain copy
  1. //重定向到商品的查询列表  
  2. return "redirect:queryItems.action";  

(3)forward页面转发
通过forward进行页面转发,浏览器地址栏url不变,request可以共享。
[java] view plain copy
  1. //页面转发  
  2. return "forward:queryItems.action";  

3.返回void

在controller方法形参上可以定义request和response,使用request或response指定响应结果:
(1)使用request转向页面,如下:
[java] view plain copy
  1. request.getRequestDispatcher("页面路径").forward(request, response);  

(1)也可以通过response页面重定向:
[java] view plain copy
  1. response.sendRedirect("url")  

(3)也可以通过response指定响应结果,例如响应json数据如下:
[java] view plain copy
  1. response.setCharacterEncoding("utf-8");  
  2. response.setContentType("application/json;charset=utf-8");  
  3. response.getWriter().write("json串");  
1 0
原创粉丝点击