spring mvc常用处理方法的返回方式

来源:互联网 发布:淘宝如何增加粉丝 编辑:程序博客网 时间:2024/06/05 08:22

springMVC对于controller处理方法返回值的可选类型

一:ModelAndView

  
@RequestMapping("/show")
public ModelAndView show(HttpServletRequest request,
           HttpServletResponse response) throws Exception {

       ModelAndView model = new ModelAndView("/demo2/show");

       model.addObject("account", "account -1");
       return model;
   }


使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。 调用addObject()方法将值设置到一个名为ModelMap的类属性,ModelMap是LinkedHashMap的子类, 具体请看类。

:对于ModelAndView构造函数可以指定返回页面的名称,也可以通过setViewName方法来设置所需要跳转的页面


@RequestMapping("/show")
public ModelAndView show(HttpServletRequest request,
           HttpServletResponse response) throws Exception {

       ModelAndView model = new ModelAndView();

       model.addObject("account", "account -1");

       model.setViewName("/demo2/show");
       return model;
   }


二:ModelMap、String

对于String的返回类型,可配合Model,ModelMap来使用的;

   

@RequestMapping(value="/regester.do", method = RequestMethod.POST)
    public String regester(ModelMap model,@ModelAttribute("User")
               User user,@RequestParam(value="code", required=false) String code) throws Exception {
        
          model.addAttribute("userName", user.getUserName());
          model.addAttribute("pwd", user.getPwd());
          model.addAttribute("code", code);
          return "regester";
      }


注:返回字符串表示一个视图名称,这个时候如果需要在渲染视图的过程中需要模型的话,就可以给处理器添加一个模型参数,然后在方法体往模型添加值就可以了


@RequestMapping(method = RequestMethod.GET)

    public String index(Model model) {

        String retVal = "user/index";

        List<User> users = userService.getUsers();

        model.addAttribute("users", users);

        return retVal;

    }



三:void

当返回类型为Void的时候,则响应的视图页面为对应着的访问地址


@Controller
@RequestMapping(value="/type")
public class TypeController extends AbstractBaseController{

    @RequestMapping(method=RequestMethod.GET)

    public void index(){

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("xxx", "xxx");

    }

}

返回的结果页面还是:/type

注:这个时候我们一般是将返回结果写在了HttpServletResponse 中了,如果没写的话,spring就会利用RequestToViewNameTranslator 来返回一个对应的视图名称。如果这个时候需要模型的话,处理方法和返回字符串的情况是相同的。



四:Map

    @RequestMapping(method=RequestMethod.GET)
    
    public Map<String, String> index(){

        Map<String, String> map = new HashMap<String, String>();

        map.put("1", "1");

        return map;

    }

注:响应的view应该也是该请求的view。等同于void返回。  map.put相当于request.setAttribute方法




0 0
原创粉丝点击