1. 程式人生 > 實用技巧 >Servlet-web.xml 常見配置

Servlet-web.xml 常見配置

路徑對映

指定一個對映路徑

<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

指定多個對映路徑

<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/hello2</url-pattern>
</servlet-mapping>
...

指定通用對映路徑

<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/hello/*</url-pattern>
</servlet-mapping>

預設請求路徑

<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

指定一些字尾或者字首

<!-- xxx.do -->
<servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

優先順序問題

指定了固有的對映路徑優先順序最高,如果找不到就會走預設的處理請求;

<servlet-mapping>
    <servlet-name>error</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- 404 -->
<servlet-mapping>
    <servlet-name>error</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

過濾器配置

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.demo.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern> <!--所有請求過濾-->
</filter-mapping>

監聽器配置

<listener>
    <listener-class>com.demo.listener.CountOnlineListener</listener-class>
</listener>

session配置

<session-config>
    <!--15分鐘後自動失效-->
    <session-timeout>15</session-timeout>
</session-config>

初始化引數

<context-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
</context-param>