JavaWeb核心编程之(三.2)Servlet配置

时间:2024-04-03 11:07:56

Servlet配置

1.配置Serlvet加载时机

2.配置多映射

配置加载时机

新建项目config->创建包com.xiaoan.config->创建类FirstServlet implements Servlet(实现Servlet接口)

->创建类SoundServlet(也实现Servlet接口)

配置web.xml

先配置两个Servlet实现类的Servlet

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>config</display-name> <servlet>
<servlet-name>fs</servlet-name>
<servlet-class>com.xiaoan.config.FirstServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>ss</servlet-name>
<servlet-class>com.xiaoan.config.SoundServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping> </web-app>

运行项目控制台输出为

Sound constiuctor
Sound init
First constiuctor
first init

说明<load-on-startup> 配置值越小  越会先加载

Servlet多映射

将上面的web.xml的fs  servlet的配置中再添加一个servlet-mapping

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>config</display-name> <servlet>
<servlet-name>fs</servlet-name>
<servlet-class>com.xiaoan.config.FirstServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>/fs1/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fs</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>ss</servlet-name>
<servlet-class>com.xiaoan.config.SoundServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ss</servlet-name>
<url-pattern>/ss</url-pattern>
</servlet-mapping> </web-app>

重启服务器

届时 浏览器中访问

localhost:8080/config

http://localhost:8080/config/fs

http://localhost:8080/config/fs1

http://localhost:8080/config/fs1/任意字符

http://localhost:8080/config/任意字符.html

会运行firstservlet的 service方法

源代码到  http://git.oschina.net/azhw/java_node