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

来源:互联网 发布:顾客数据 编辑:程序博客网 时间:2024/06/05 05:58
简介

对于springMVC处理方法支持支持一系列的返回方式:

  1. ModelAndView
  2. Model
  3. ModelMap
  4. Map
  5. View
  6. String
  7. Void

具体介绍

详细介绍每一个返回类型的各个特点;

ModelAndView

?
1
2
3
4
5
6
@RequestMapping(method=RequestMethod.GET)
    publicModelAndView index(){
        ModelAndView modelAndView =new ModelAndView("/user/index");
        modelAndView.addObject("xxx","xxx");
        returnmodelAndView;
    }

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

PPS:返回的是一个包含模型和视图的ModelAndView对象;

?
1
2
3
4
5
6
7
@RequestMapping(method=RequestMethod.GET)
    publicModelAndView index(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.addObject("xxx","xxx");
        modelAndView.setViewName("/user/index");
        returnmodelAndView;
    }

对于ModelAndView类的属性和方法

Model

一个模型对象,主要包含spring封装好的model和modelMap,以及java.util.Map,当没有视图返回的时候视图名称将由requestToViewNameTranslator决定;

ModelMap

待续

Map

?
1
2
3
4
5
6
7
@RequestMapping(method=RequestMethod.GET)
    publicMap<String, String> index(){
        Map<String, String> map =new HashMap<String, String>();
        map.put("1","1");
        //map.put相当于request.setAttribute方法
        returnmap;
    }
PS:响应的view应该也是该请求的view。等同于void返回。

View

这个时候如果在渲染页面的过程中模型的话,就会给处理器方法定义一个模型参数,然后在方法体里面往模型中添加值。

String

对于String的返回类型,笔者是配合Model来使用的;

?
1
2
3
4
5
6
7
8
@RequestMapping(method = RequestMethod.GET)
    publicString index(Model model) {
        String retVal ="user/index";
        List<User> users = userService.getUsers();
        model.addAttribute("users", users);
 
        returnretVal;
    }

或者通过配合@ResponseBody来将内容或者对象作为HTTP响应正文返回(适合做即时校验);

?
1
2
3
4
5
6
7
@RequestMapping(value ="/valid", method = RequestMethod.GET)
    public@ResponseBody
    String valid(@RequestParam(value = "userId", required =false) Integer userId,
            @RequestParam(value = "logName") String strLogName) {
        returnString.valueOf(!userService.isLogNameExist(strLogName, userId));
 
    }

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

Void

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

?
1
2
3
4
5
6
7
8
9
10
@Controller
@RequestMapping(value="/type")
publicclassTypeControllerextends AbstractBaseController{
 
    @RequestMapping(method=RequestMethod.GET)
    publicvoidindex(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.addObject("xxx","xxx");
    }
}

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

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


0 0