SpringMVC-后台跳轉回前端的方式


Controller.java

@Controller // 表示是控制器
public class ResultController {
    // 1.視圖解析器方式,需要配置視圖解析器
    @RequestMapping("/result1") // 設置映射
    public ModelAndView result1(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "hello result 1");
        // 轉發,不設置名字就和@RequestMapping()里的名字一樣
        mv.setViewName("hello1");
        // 重定向 后綴加不加都可以, 帶參數必須加上
        // mv.setViewName("redirect:hello1.jsp");
        return mv;
    }

    // 2.HttpServlet API方式,不需要配置視圖解析器
    @RequestMapping("/result2")
    public void result2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("msg", "hello result 2-2");
        // 重定向,帶參數不能有空格?
        resp.sendRedirect("hello2-1.jsp?msg=hello-result-2-2");
        // 轉發
        // req.getRequestDispatcher("hello2-2.jsp").forward(req, resp);
    }

    // 3.SpringMVC方式,不需要配置視圖解析器
    @RequestMapping("/result3")
    public String result3(RedirectAttributes attr) {
        // 轉發 1.不傳參數,不能加后綴,但需視圖解析器。2.要傳參數,必須加上后綴
        // return "hello3-1";
        // return "hello3-1.jsp?msg=hello result 3-1";
        // 兩種一樣,這種要后綴
        // return "forward:hello3-1.jsp?msg=hello result 3-1";
        // 重定向 這種要后綴,還需在xml文件加<mvc:annotation-driven />
        // attr.addAttribute("msg", "hello result 3-2");
        return "redirect:hello3-2.jsp";
    }
}

springmvc.xml配置

略(配置視圖解析器)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM