【SpringMVC】(四)结果跳转方式

结果跳转方式

SpringMVC:结果跳转方式


1.ModelAndView(常用)

  根据ModelAndView对象的view名称,结合视图解析器的前后缀,跳到指定页面。

  (略)


2.ServletAPI

  • 通过ServletAPI,不需要视图解析器。

  • 1.通过HttpServletResponse进行输出

    @Controller
    public class ServletAPITest {
    
        @RequestMapping("/result/t1")
        public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.getWriter().println("Hello,Spring By Servlet API");
        }
    }
    

  • 2.通过HttpServletResponse实现重定向

    @RequestMapping("/result/t2")
    public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	response.sendRedirect("/index.jsp");
    }
    

  • 3.通过HttpServletResponse实现转发

    @RequestMapping("/result/t3")
    public void test3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	//转发
        request.setAttribute("msg","传递msg");
        request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request,response);
    }
    


3.SpringMVC

3.1 通过SpringMVC来实现转发和重定向,无需视图解析器。

  • 测试前,注释掉试图解析器。

  • 1.转发

     @RequestMapping("/rsm/t1")
        public String test1(){
            //转发一
            return "/index.jsp";
        }
    
  • 2.转发二

    @RequestMapping("/rsm/t2")
        public String test2(){
            return "forward:/index.jsp";
        }
    
  • 3.重定向

    @RequestMapping("/rsm/t3")
        public String test3(){
            return "redirect:/index.jsp";
        }
    

3.2 通过SpringMVC来实现转发和重定向,有视图解析器。

  • 1.转发

    @RequestMapping("/rsm2/t1")
        public String test1(){
            return "test";
        }
    
  • 2.重定向一个页面

    @RequestMapping("/rsm2/t2")
        public String test2(){
            return "redirect:/index.jsp";
        }
    
  • 3.重定向另一个请求

    @RequestMapping("/rsm2/t1")
        public String test1(){
            return "test";
        }
    
        @RequestMapping("/rsm2/t3")
        public String test3(){
            return "redirect:/rsm2/t1.do";//重定向到/rsm2/t1的请求
        }
    
posted @ 2021-02-06 23:33  musecho  阅读(77)  评论(0)    收藏  举报