SpringMVC Controller的返回类型

Controller的三种返回类型中html

ModelAndView类型 带数据带跳转页面ajax

String 跳转页面不带数据json

void 一般是ajax格式请求时使用app

 

1返回ModelAndView

controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。jsp

controllerpost

@RequestMapping("/test")
public ModelAndView test(){
    ModelAndView mav=new ModelAndView("hello");//经过ModelAndView构造方法能够指定返回的页面名称,也能够经过setViewName()方法跳转到指定的页面
    mav.addObject("time", new Date());
    mav.getModel().put("name", "caoyc");
    return mav;
}

JSPurl

 time:${requestScope.time}
 <br/>
 name:${name }

 

2   返回字符串  

controller方法返回字符串能够指定逻辑视图名,经过视图解析器解析为物理视图地址。spa

        @RequestMapping(value = "saveRegSigned")
        public String saveRegSigned(MeetingReg meetingReg, HttpServletRequest request, HttpServletResponse response,
                Model model) throws Exception {
            meetingReg.setMeetingId(Utils.getMeetingId(request));
            Map<String, Object> resultMap = regService.saveRegSigned(meetingReg);
            model.addAttribute("resultMap", resultMap);
            return "modules/meeting/signed/RegSignedReturnPage";
        }
        

JSPcode

                <div class="code_reg">
                    <ul>
                        <li>注册号:${resultMap.regCode}</li>
                        <li>注册类型:${resultMap.regType}</li>
                    </ul>
                </div>

 

3   返回void

void htm

若是返回值为空,则响应的视图页面对应为访问地址

@RequestMapping("/index")
public void index() {
    return;
}

对应的逻辑视图名为"index"

 

4返回map

Map

复制代码
@RequestMapping("/demo2/show") 
    public Map<String, String> getMap() { 
        Map<String, String> map = new HashMap<String, String>(); 
        map.put("key1", "value-1"); 
        map.put("key2", "value-2"); 
        return map; 
    } 
复制代码

在jsp页面中可直经过${key1}得到到值, map.put()至关于request.setAttribute方法。

对应的逻辑视图名为../demo2/show+suffix

返回其余object类型同map

 

1.使用 String 做为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具备很大的灵活性,而模型数据又能够经过 ModelMap 控制。
2.使用void,map,Model 时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成。
3.使用String,ModelAndView返回视图名称能够不受请求的url绑定,ModelAndView能够设置返回的视图名称。

参考http://www.cnblogs.com/xiepeixing/p/4243801.html

    在controller方法形参上能够定义request和response,使用request或response指定响应结果:
    一、使用request转向页面,以下:
    request.getRequestDispatcher("页面路径").forward(request, response);

      二、也能够经过response页面重定向:
    response.sendRedirect("url")

     三、也能够经过response指定响应结果,例如响应json数据以下:    response.setCharacterEncoding("utf-8");    response.setContentType("application/json;charset=utf-8");    response.getWriter().write("json串");

相关文章
相关标签/搜索