配置自定義的404頁面,替換Tomcat不友好的404頁面
有時候我們想替換掉tomcat自帶的404頁面
如圖:
Paste_Image.png
404也就是說找不到目前資源或者資源不存在
The origin server did not find a current representation for the target resource
or is not willing to disclose that one exists.
替換思路:錯誤404這種常出現的頁面,我們可以設定為靜态資源,以加快網頁通路。
替換項目的404頁面
第一步:我們需要先把WEB-IN\Fweb.xml下面的mvc-dispatcher更改為全局配置。
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- 預設比對所有的請求 -->
<!-- 我們預設配置這個是為了讓我們的Spring架構接管Servelt,實作Spring控制所有站點請求 -->
<url-pattern>/</url-pattern>
<!--<url-pattern>/css/*</url-pattern>-->
<!--<url-pattern>/images/*</url-pattern>-->
<!--<url-pattern>/fonts/*</url-pattern>-->
</servlet-mapping>
錯誤404的頁面是常用頁面之一,是以我們在項目的資源目錄(webapp)下建立一個static目錄,專門用來存放靜态資源,如js、css、錯誤提示頁面、登入、注冊頁面等等。頁面都存放在view中
建立完目錄如下
PS:你可以上網找一些好看的404頁面,在上面的相關目錄存相關資源,例如一些CSS,JS的資源,HTML頁面的話就存在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: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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.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:resources mapping="/view/**" location="/static/view/" />
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 顯示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 4.掃描web相關的bean -->
<context:component-scan base-package="pjb.ssm.mvc">
<!-- 制定掃包規則 ,隻掃描使用@Controller注解的JAVA類 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
以上檔案配置好後,重新開機伺服器,并輸入錯誤位址,現在插入的404頁面正常顯示了。
這個是我的404頁面
主要參考于大牛
Clone丶記憶的SSM內建之路