springMVC中的跳转结果的方式
1、 设置ModelAndView
根据view的名称和视图解析器跳转到指定的页面
<!-- 配置视图渲染器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!-- 结果视图的前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 结果视图的后缀 --> <property name="suffix" value=".jsp"/> </bean>
ModelAndView mv = new ModelAndView(); mv.addObject("msg", "hello springmvc annotation"); mv.setViewName("hello");
2、 通过ServletAPI对象来实现,不需要视图解析器
通过HttpServletResponse对象进行输出
@Controller @RequestMapping("/springmvc") public class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().println("hello springmvc use httpservlet api"); } }
通过HttpServletResponse对象来重定向
@RequestMapping("/hello2")
public void hello2(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 实现重定向
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
通过HttpServletRequest对象实现转发
@RequestMapping("/hello3")
public void hello3(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 实现转发
request.setAttribute("msg", "servlet api forward");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
2、 通过springmvc来实现转发和重定向—没有视图解析器
转发实现1
@RequestMapping("/hello")
public String hello() {
// 转发
return "index.jsp";
}
转发实现2
@RequestMapping("/hello2")
public String hello2() {
// 转发
return "forward:index.jsp";
}
重定向实现
@RequestMapping("/hello3")
public String hello3() {
// 重定向
return "redirect:index.jsp";
}
3、 通过springmvc来实现转发和重定向—有视图解析器
转发实现
@RequestMapping("/hello4")
public String hello4() {
// 转发
return "hello";
}
重定向实现
@RequestMapping("/hello5")
public String hello5() {
// 重定向
return "redirect:hello4.do";
}

浙公网安备 33010602011771号