SpringMVC 幾種頁面跳轉方式

 
SpringMVC 幾種頁面跳轉方式總結以下:java

1.不使用ModelAndView服務器

1)、經過HttpServletResponse的API直接輸出(不須要配置渲染器)
@Controller
public class RequestController{
 @RequestMapping("/resp")
    public void test(HttpServletRequest req, HttpServletResponse resp) throws Exception {
         resp.getWriter().println("hello HttpServletResponse");
    }mvc


2)、 使用HttpServletResponse 重定向到另外一個視圖(其餘不變 ) 
    @RequestMapping("/resp")
    public void test(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.sendRedirect("index.jsp");
    }app


3)、 使用HttpServletRequest 轉發(默認訪問/下的index.jsp頁面 不受渲染器的影響)
@RequestMapping("/resp")
    public void test(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setAttribute("message","it's forword ");
        req.getRequestDispatcher("index.jsp").forward(req,resp);
        }jsp


4)、直接返回jsp頁面的名稱(無渲染器)
 @RequestMapping("/nice")
    public String test(){
        //轉發方式1
        return "home.jsp";
        //轉發方式2
        return "forward:index.jsp";
        //重定向方式
        return "redirect:index.jsp";
    }ide


5)、當有渲染器指定
@RequestMapping("/nice")
    public String hello1(){
        //轉發方式1
        return "home";
        //轉發方式2
        return "forward:index";
        //重定向方式  hello指的是requsrmapping
        return "redirect:hello";
    }spa


二、使用ModelAndView
 @Override
public ModelAndView test(javax.servlet.http.HttpServletRequest httpServletRequest,
                                      javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        //封裝要顯示到視圖的數據
        mv.addObject("msg","hello myfirst mvc");
        //經過視圖名跳轉
        mv.setViewName("hello");
        return mv;.net

 

    //跳轉到服務器內部的一個功能處理方法
    //return new ModelAndView("forward:test.jsp");
    //重定向一個功能方法
    //return new ModelAndView("redirect:test.jsp");blog


}
 
原文連接:https://blog.csdn.net/figo0423/article/details/79759151get

相關文章
相關標籤/搜索