SSM靜態資源訪問不了問題


SSM靜態資源訪問不了問題

  • 因為配置SpringMVC會把全部請求都通過它攔截了
<!--springmvc的前端控制器,攔截所有請求-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  • 考慮spring-mvc.xml配置文件配置靜態資源放行了沒
<!-- 設置靜態資源不過濾 -->
<mvc:resources location="/static/css/" mapping="/css/**" />
<mvc:resources location="/static/images/" mapping="/images/**" />
<mvc:resources location="/static/js/" mapping="/js/**" />

<!-- 配置靜態文件放行 -->
<mvc:default-servlet-handler />
  • 配置完后就要在html或jsp中加載這些資源,可能路徑寫錯

  • ${pageContext.request.contextPath} 是獲得項目的webapp的目錄的意思,靜態資源訪問不了可能這個沒寫
  • 在你的頁面中如果需要使用webapp下的一些東西的時候,就可以在頁面中使用這樣的方式去獲得這些資源文件

  • 編寫了一個獲取項目絕對路徑的類,實現ServletContextListener接口
  • 出大問題,忘寫@WebListener注解,所以根本不起作用,也就獲取不到項目的靜態資源了
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //取到ServletContext
        ServletContext context = servletContextEvent.getServletContext();
        context.setAttribute("ctx",context.getContextPath());
        System.err.println("----Servlet容器創建成功,ctx被放到ServletContext作用域----");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}


免責聲明!

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



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