• springmvc(4)结果显示到前台


    1.设置ModelAndView对象。根据view的名称和视图解析器跳转到指定的页面(视图解析器的前缀+viewName+视图解析器的后缀)

    mvc.xml
    <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!--结果视图的前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--结果视图的后缀--> <property name="suffix" value=".jsp"/> </bean>
    处理器类: public class HelloControllerControll implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView modelAndView = new ModelAndView(); //封装要显示到视图中的数据 modelAndView.addObject("msg","Hello SimpleUrlhandlerMapping"); //试图名称 modelAndView.setViewName("hello"); // /WEB-INF/jsp/hello.jsp return modelAndView; } }

    上述代码跳转的页面为(视图解析器的前缀【/WEB-INF/jsp/】+viewName【hello】+视图解析器的后缀【.jsp】),即/WEB-INF/jsp/hello.jsp

    2.通过Servlet API来实现,不需要视图解析器

    1)通过HttpServletResponse 来进行输出

     @RequestMapping("/hello")
        public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.getWriter().println("use HttpServlet API");
        }

    这里有个事情就是,除了/hello可以映射到这个处理器,/hello.*以及/hello/也可以映射,/hello.jsp不可以,因为tomcat自带的.jsp扩展名匹配优先级高于我配置的【/】,所以hello.jsp会被.jsp匹配上,不会被我的dispatcherServlet匹配上。

    2)通过HttpServletResponse 进行重定向

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

    3)通过HttpServletRequest进行转发

     @RequestMapping("/hello")
        public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            request.setAttribute("msg","HttpServletRequest forward");
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }

    这个转发不会使用视图解析器

    3.通过springMVC进行转发和重定向-没有视图解析器的时候

    1)转发的实现

      @RequestMapping("/hello1")
        public String hello(){
            //转发1
            return "index.jsp";
        }

     @RequestMapping("/hello1")
    public String hello(){
    //转发2
    return "forward:index.jsp";
    }
     

    2)重定向的实现

      @RequestMapping("/hello1")
        public String hello(){
            return "redirect:index.jsp";
        }

    4.通过springMVC进行转发和重定向-有视图解析器的时候

    转发的实现:

       @RequestMapping("/hello2")
        public String hello2(){
            return "hello";
        }

    通过视图解析器会找到:/WEB-INF/jsp/hello.jsp

    重定向不会使用视图解析器,因为是重新定义一个路径,相当于重新开始一次请求,相当于mvc映射方法到处理器而不是将响应的数据渲染到jsp等页面。

  • 相关阅读:
    【简】题解 AWSL090429 【市场】
    【简】题解 AWSL090429 【噪音】
    差分约束
    凸包模板
    杂模板
    后缀数组刷题
    Trie刷题
    字符串模板
    网络流建模专题
    组合数模板
  • 原文地址:https://www.cnblogs.com/yuby/p/11012786.html
Copyright © 2020-2023  润新知