15.spring-mvc视图解析器

web.xml中的配置
    <context:component-scan base-package="cn.com"></context:component-scan>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/page/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
jsp页面的配置:
    <body>
        <a href="handle1">handl1请求,返回/WEB-INF/page/sucess.jsp页面!</a><br>
        <a href="handle2">handl2请求,返回index.jsp页面!</a><br>
        <a href="handle3">handl3请求,返回index.jsp页面!</a><br>
        <a href="handle4">handl4请求,返回index.jsp页面!</a><br>
    </body>
    
对应的controler类:
    @Controller
    public class HelloControler {
        @RequestMapping(value = "/handle1")
        public String handel1() {
            System.out.println("处理handl1请求,返回/WEB-INF/page/sucess.jsp页面!");
            return "success";------------->进行动态拼接,访问地址是:/WEB-INF/page/sucess.jsp
        }
        @RequestMapping("/handle2")
        public String handle2() {
            System.out.println("handl2请求,返回index.jsp页面");
            return "../../index";------------->进行动态拼接,访问地址是:/WEB-INF/page/../../index.jsp,等于往出跳了两层目录,即/index.jsp
        }
        @RequestMapping("/handle3")
        public String handle3() {
            System.out.println("请求转发:handl3请求,返回index.jsp页面");
            return "forward:/index.jsp";----->也想访问index.jsp,用了转发技术:格式是"forward:/访问的jsp",带了forwad,spring会跳过视图解析器的拼接,即/index.jsp
                                        ----->一定要加上/,不加是相对路径,容易出问题
        }
        @RequestMapping("/handle4")
        public String handle4() {
            System.out.println("请求转发:handl4请求,返回index.jsp页面");
            return "forward:/handle3";------->也是进行了转发,不过转发到/handle3请求,再又handle3转发到index.jsp页面,进行了两次转发
        }
    }
项目结构如下:

结论:
转发格式:
return "forward:/index.jsp";
return "forward:/handle3";
1.一定要加上/,不加是相对路径,容易出问题
2.forward:转发的前缀,不会由我们配置的视图解析器解析拼串
3.即带前缀的返回不会通过视图解析器进行拼串
4.但是会帮我们拼接上项目名称
重定向:
    /**
     * 重定向到index.jsp页面
     * 有前缀的转发和重定向,视图解析器不会进行拼串
     * 转发: forward:转发的路径
     * 重定向:redirect:重定向的路径
     *
     * /index.jsp 表示从当前项目下开始,springmvc会自动为路径拼接上项目名称
     *  原生的Servlet重定向/需要加上项目名称才能成功
     *  reponse.sendRedirect("/spring-mvc/hello.jsp")
     */
    @RequestMapping("/handle5")
    public String handle5(){
        System.out.println("handl5请求:重定向到index.jsp页面");
        return "redirect:/index.jsp";-------------------------->重定向到index.jsp页面,和原生的不同,这里不需要拼接项目名称,springmvc会自动拼接
    }
    @RequestMapping("handle6")
    public String handle6(){
        System.out.println("handl6请求:重定向到handle5,再重定向到index.jsp页面");
        return "redirect:/handle5";--------------------------->重定向到handle5请求,再重定向到index.jsp页面
    }

 

posted @ 2022-05-08 22:11  努力的达子  阅读(71)  评论(0编辑  收藏  举报