一、ModelAndView
- 设置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>
对应的controller类
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//1.返回一个模型视图对象
ModelAndView mv = new ModelAndView();
//2.此处写业务代码
//3.键值对,前端传数据
mv.addObject("msg","ControllerTest1");
//4.拼接成/WEB-INF/jsp/test.jsp
mv.setViewName("test");
return mv;
}
}
二、ServletAPI
通过设置ServletAPI (req,resp) 不需要视图解析器 。
- 通过HttpServletResponse进行输出rsp.getWriter()
- 通过HttpServletResponse实现重定向rsp.sendRedirect()
- 通过HttpServletRequest实现转发req.getRequestDispatcher().forward()
@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);
}
}
三、SpringMVC
- 通过SpringMVC来实现转发和重定向 - 无需视图解析器;
- 比如return “/index.jsp”,要写完整路径。
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//转发
return "/index.jsp"; }
@RequestMapping("/rsm/t2")
public String test2(){
//转发二
return "forward:/index.jsp"; }
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
- 通过SpringMVC来实现转发和重定向 - 需要视图解析器;
- 此时return只需要写jsp文件的名字,视图解析器会将路径补全、
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//转发
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
}
}