springMVC访问静态资源——js、css、img等资源访问不到

2021-05-14 16:56:54 浏览数 (1)

springMVC访问静态资源——js、css、img等资源访问不到

进行springMVC的使用时,搭建框架的时候,发现一个简单的demo都跑不起来。发现引入的js出现404了。之后就查找各种资料后,发现,原来需要配置静态资源,否则不能进行访问指定的js资源。

在springmvn-servlet.xml文件中进行设置:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.xueyoucto.xueyou.controller"/>
    <context:component-scan base-package="com.xueyoucto.xueyou.utils"/>

    <mvc:annotation-driven/>
    <mvc:resources location="/Component/" mapping="/Component/**"/>
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
</beans>

主要是如下内容:

代码语言:javascript复制
<mvc:resources location="/Component/" mapping="/Component/**"/>
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>

其中location是真实的路径,mapping是对外显示的映射的路径。

现在,我想在hello.jsp中引用hello.js和jquery-2.2.2.js,那么我需要在hello.jsp中这样写:

代码语言:javascript复制
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
  <script type="text/javascript" src="${pageContext.request.contextPath}/Component/jquery-2.2.2.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath}/js/hello.js"></script>
    <title>ccc</title>
</head>
<body>
<h1>hello</h1>
</body>
</html>

这样能够引入hello.js。

如果把springmvc-servlet.xml中的mapping映射修改一下:

代码语言:javascript复制
<mvc:resources location="/Component/" mapping="/Component_mapping/**"/>
    <mvc:resources location="/img/" mapping="/img_mapping/**"/>
    <mvc:resources location="/js/" mapping="/js_mapping/**"/>
    <mvc:resources location="/css/" mapping="/css_mapping/**"/>

这时候,在hello.jsp中引用js的时候就需要这样引用:

代码语言:javascript复制
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
  <script type="text/javascript" src="${pageContext.request.contextPath}/Component_mapping/jquery-2.2.2.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath}/js_mapping/hello.js"></script>
    <title>ccc</title>
</head>
<body>
<h1>hello</h1>
</body>
</html>

运行效果:

0 人点赞