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();
    }
  • 相关阅读:
    Count and Say leetcode
    Find Minimum in Rotated Sorted Array II leetcode
    Find Minimum in Rotated Sorted Array leetcode
    Search in Rotated Sorted Array II leetcode
    search in rotated sorted array leetcode
    Substring with Concatenation of All Words
    Subsets 子集系列问题 leetcode
    Sudoku Solver Backtracking
    Valid Sudoku leetcode
    《如何求解问题》-现代启发式方法
  • 原文地址:https://www.cnblogs.com/myitnews/p/13298398.html
Copyright © 2011-2022 走看看