SpringMVC访问静态资源

213 阅读1分钟

这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战

前言:在SpringMVC中我们常用到Controller和View。在我们项目中也会使用到静态资源,如html,js,css,image等。在默认的访问的URL是会被DispatcherServlet所拦截的,如果我们希望静态资源可以直接访问,那就会使用我们的Spring的静态资源过滤。

静态资源访问的方法有多种,如:通过开放tomcat的defaultServlet修改其默认的url-parttern、SpringMVC提供的处理静态资源方法等,tomcat我们不做解释,下来我们来说一下SpringMVC的处理方式。

一、使用web.xml配置专门的文件过滤配置文件

web.xml代码如下:

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 检索/WEB-INF/spring/appServlet下的servlet-context.xml文件>
    <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>

以上我么配置了一个servlet-context.xml文件,我们在此文件中添加资源映射。 servlet-context.xml的路径如下:

二、配置文件内容:

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<annotation-driven />

<!-- mapping:映射 location:本地资源路径,注意必须是webapp根目录下的路径。 过滤 更目录下的 css 、images 、js目录下的文件-->
 <resources mapping="/css/**" location="/images/" />
 <resources mapping="/images/**" location="/images/" />
 <resources mapping="/js/**" location="/js/" />
 <!-- 如非要放在WEB-INF中,则必须修改resources映射
 <resources mapping="/js/**" location="/WEB-INF/js/" /> -->
<!-- 将@Controllers选择用于渲染的视图解析为。/WEB-INF/pages目录中的html资源文件 -->
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <beans:property name="prefix" value="/WEB-INF/pages/" />
 <beans:property name="suffix" value=".html" />
 </beans:bean>

 <context:component-scan base-package="com.wzy.teststaticfile" />        

 </beans:beans>

在location中一般情况下是读取webapp根目录下的文件,如果你将资源目录,放置到webapp/WEB-INF下面的话,则就会访问失败。我们来说一下WEB-INF目录作用,他是Java的WEB应用的安全目录。使客户端无法访问,只许服务端可以访问。如果想在浏览器中直接访问其中的文件,需要通过web.xml文件对要访问的文件进行相应映射才能访问。处理如下:

image.png

总结:在SpringMVC中静态文件则是我们经常关注的事情,明天我们来了解一下VUE中静态文件的配置。