结果跳转方式
一、 ModelAndView
1.设置ModelAndView对象,根据view名称,和视图解析器跳转到指定的页面。
页面:{视图解析器前缀}+viewName+{视图解析器后缀}
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
2.编写的对应继承controller接口的类ContollerTest类
public class ControllerTest implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mav = new ModelAndView();
mav.addObject("msg","ControllerTest1");
mav.setViewName("test");
return mav;
}
}
二、ServletAPI
通过设置ServletAPI , 不需要视图解析器 。
1、通过HttpServletResponse进行输出
//resp输出
@RequestMapping("/test/t1")
public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Hello,test By ServletAPI");
}
2、通过HttpServletResponse实现重定向
//resp重定向
@RequestMapping("/test/t2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.sendRedirect("/index.jsp");
}
3、通过HttpServletResponse实现转发
//req转发
@RequestMapping("/test/t3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws Exception {
req.setAttribute("msg","/test/t3");
req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
}
三、SpringMVC
1.通过SpringMVC来实现转发和重定向,无需视图解析器;
测试前,需要将视图解析器注释掉
@Controller
public class SpringMVCControl {
//转发一:直接返回转发
@RequestMapping("/result/t1")
public String test1(){
return "/index.jsp";
}
//转发二:forword关键字
@RequestMapping("/result/t2")
public String test2(){
return "forward:/index.jsp";
}
//重定向:redirect关键字
@RequestMapping("/result/t3")
public String test3(){
return "redirect:/index.jsp";
}
}
2.通过SpringMVC来实现转发,需要视图解析器;
重定向不需要视图解析器,相当于另一个请求。
@Controller
public class SpringMVCControl2 {
//转发
@RequestMapping("/result2/t1")
public String test1(){
return "hello";
}
//重定向
@RequestMapping("/result2/t2")
public String test3(){
return "redirect:/index.jsp";
//return "redirect:know.do"; //know.do为另一个请求/
}
}