springMVC js等文件找不到错误

spring3. 1应用springMVC时如果配置URL映射时如下配置


[html] 
<servlet> 
        <servlet-name>appServlet</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param> 
            <param-name>contextConfigLocation</param-name> 
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
 
    <servlet-mapping> 
        <servlet-name>appServlet</servlet-name> 
        <url-pattern>/</url-pattern> 
    </servlet-mapping> 

会导致页面引用的JS CSS发生找不到的错误,原因是  <url-pattern>/</url-pattern>  这里配置访问所有的文件都经过DispatcherServlet,spring 默认不能访问js, css, impge等静态文件,所以在页面里访问js和CSS文件,即使路径对了,也不能访问,解决方法是在sping的配置文件里配置  <mvc:resources mapping="/javascript/**"   location="/static_resources/javascript/"/>   来映射静态文件的位置,上面的意思是告诉spring,页面使用 /javascript/的路径时, 会到/static_resources/javascript 文件夹下面找.例如:

spring-servlet.xml 里配置如下:

   <mvc:resources mapping="/javascript/**"   location="/static_resources/javascript/"/>  

jsp页面要引用js的如下:

<%
String path = request.getContextPath();
// 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 将 "项目路径basePath" 放入pageContext中,待以后用EL表达式读出。
pageContext.setAttribute("basePath",basePath);
%>

<html>
<head>
<title>Insert title here</title>
<script type="text/javascript" src="<%=basePath%>/javascript/jsonReuest.js">
</script>

猜你喜欢

转载自joezheng123.iteye.com/blog/2024838