SpringMVC结果跳转的三种方式
- 使用视图解析器
- ServletAPI,不用使用视图解析器
- SpringMVC,不用使用视图解析器
ModelAndView
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
页面 : {视图解析器前缀} + viewName +{视图解析器后缀}
ServletAPI
@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
@Controller
public class ModelTest {
@GetMapping("test1")
public String test1(Model model){
model.addAttribute("msg", "modelTest1");
//转发
return "/index.jsp";
}
@GetMapping("test2")
public String test2(Model model){
model.addAttribute("msg", "modelTest2");
//转发
return "forward:/index.jsp";
}
@GetMapping("test3")
public String test3(Model model){
model.addAttribute("msg", "modelTest3");
//重定向
return "redirect:/index.jsp";
}
}