zoukankan      html  css  js  c++  java
  • Spring MVC的静态资源访问

    前面已经讲过,如果你的DispatcherServlet拦截“/”,拦截了所有的请求,同时对.js,*.jpg的访问也就被拦截了。下面就讲一讲在注解版中怎么解决这个问题呢?

    webapp的目录结构

    index.jsp内容:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>首页</title>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css">
        <script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>
    </head>
    <body>
    Hello World!!!
    <img src="${pageContext.request.contextPath}/images/test.jpg" width="500" height="429">
    </body>
    </html>

    注意:这里的静态资源路径需要加上上下文路径:${pageContext.request.contextPath}

    一、重写WebMvcConfigurer的addResourceHandlers方法

    /** 静态资源处理: 不被拦截 **/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // addResourceLocations 本地资源路径
        // addResourceHandler 资源路径映射,/js/**表示js目录及子目录的所有资源
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/images/**").addResourceLocations("/images/");
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    二、重写WebMvcConfigurer的configureDefaultServletHandling方法

    这是使用默认的Servlet进行处理

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
  • 相关阅读:
    网络流24题-[CTSC1999]家园
    网络流24题-孤岛营救问题
    汽车加油行驶问题(分层图最短路)
    送外卖(可重复点的哈密顿路径)
    信与信封问题
    最小完全图(最小生成树加边成完全图)
    校园网(有向图加边变成强连通图)
    玩具装箱
    MSTest、NUnit、xUnit对照表
    .NET Core学习 笔记索引
  • 原文地址:https://www.cnblogs.com/myitnews/p/13298398.html
Copyright © 2011-2022 走看看