web.xml中需要配置的內容
1.配置監聽器<listener>
它有兩個監聽器:
1).
<!--配置文件加載監聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener它的作用是啟動web容器,(加載配置文件)自動裝配applicationContext.xml配置信息(詳細配置見下面)。
2).
<!--spring log4j日志監聽器配置-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>Log4jConfigListener</param-name>
<!-- spring刷新log4j文件的時間間隔 -->
<param-value>10000</param-value>
</context-param>
2.部署applicationContext.xml文件
如果不寫任何參數配置,默認的是在/WEB-INF/applicationContext.xml
如果想要自定義文件名,需要在web.xml中加入contextConfigLocation這個context參數
<!-- 配置applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
3.配置前端控制器DispatcherServlet:它是攔截請
<!-- 配置DispatchServlet 的核心控制器 -->
DispatchServlet是HTTP請求的中央調度處理器,它將web請求轉發給controller層處理,它提供了敏捷的映射和異常處理機制。
<servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 指定SpringMVC配置文件 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping>
<!-- 設置http請求攔截,如*.do,這里設置的是攔截所有 --> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
4.<!-- 錯誤跳轉頁面 -->
<error-page>
<!-- 路徑不正確 -->
<error-code>404</error-code>
<location>/WEB-INF/errorpage/404.jsp</location>
</error-page>
<error-page>
<!-- 沒有訪問權限,訪問被禁止 -->
<error-code>405</error-code>
<location>/WEB-INF/errorpage/405.jsp</location>
</error-page>
<error-page>
<!-- 內部錯誤 -->
<error-code>500</error-code>
<location>/WEB-INF/errorpage/500.jsp</location>
</error-page>
5.配置字符集編碼
<filter>
<!-- 用來對瀏覽器的每一次請求進行過濾,加上了父類沒有的功能,就是設置字符集編碼,一般只用來配置字符集 -->
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<!-- forceEncoding用來設置是否理會 request.getCharacterEncoding的方法 -->
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以上就是我們經常會用到的東西。