SSM框架--静态资源访问(替换404页面)

配置自定义的404页面,替换Tomcat不友好的404页面

常见404页面:


404也就是说找不到当前资源或者资源不存在

The origin server did not find a current representation for the target resource 
or is not willing to disclose that one exists.

替换思路:错误404这种常出现的页面,我们可以设置为静态资源,以加快网页访问。

第一步:我们需要先把WEB-INF\web.xml下面的mvc-dispatcher更改为全局配置。
<servlet-mapping>
      <servlet-name>mvc-dispatcher</servlet-name>
      <!-- 默认匹配所有的请求 -->
      <!-- 我们默认配置这个是为了让我们的Spring框架接管Servelt,实现Spring控制所有站点请求 -->
      <url-pattern>/</url-pattern>
  </servlet-mapping>

错误404的页面是常用页面之一,所以我们在项目的资源目录(webapp)下创建一个static目录,专门用来存放静态资源,如js、css、错误提示页面、登录、注册页面等等。页面都存放在view中

建立完目录如下



第二步:在web.xml中添加错误页面的资源
<error-page>
    <error-code>404</error-code>
    <location>/static/view/404.html</location>
  </error-page>

不过配好后启动项目输入错误页面还是不能正常显示自己配置的404页面,相关图片走丢了


第三步:在spring目录下写spring-web.xml,用于控制哪些资源被拦截。

spring-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <!-- 简化配置:
        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
    -->
    <mvc:annotation-driven/>

    <!-- 2.静态资源默认servlet配置
        (1)加入对静态资源的处理:js,gif,png
        (2)允许使用"/"做整体映射
     -->
    <mvc:resources mapping="/css/**" location="/static/css/" />
    <mvc:resources mapping="/js/**" location="/static/js/"/>
    <mvc:resources mapping="/images/**" location="/static/images/"/>
    <mvc:default-servlet-handler/>


    <!-- 3.配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.ray.web"/>


</beans>


404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="images/404.png">
</body>
</html>


以上文件配置好后,重启服务器,并输入错误地址,现在插入的404页面正常显示了。

这个是我的404页面



猜你喜欢

转载自blog.csdn.net/q343509740/article/details/80202750