ModelAndView
设置ModelAndView对象 , 根据view的名称和视图解析器跳到指定的页面
视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
对应的controller类
public class ControllerTest1 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test");
return mv;
}
}
通过SpringMVC来实现转发和重定向
无视图解析器
@RequestMapping("/rsm/t1")
public String test1(){
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
return "forward:/WEB-INF/jsp/test.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
return "redirect:/index.jsp";
}
注意:SpringMVC默认是按照转发处理请求的
WEB-INF目录下的jsp通过转发可以访问,重定向不行
有视图解析器
@RequestMapping("/rsm/t1")
public String test1(){
return "test";
}
@RequestMapping("/rsm/t2")
public String test2(){
return "redirect:/index.jsp";
}
可以看到重定向访问不受视图解析器影响
ServletAPI
不需要视图解析器
通过HttpServletResponse进行输出,重定向,转发
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}