JavaWeb核心编程之(三.2)Servlet配置
Servlet配置
1.配置Serlvet加载时机
2.配置多映射
配置加载时机
新建项目config->创建包com.xiaoan.config->创建类FirstServlet implements Servlet(实现Servlet接口)
->创建类SoundServlet(也实现Servlet接口)
配置web.xml
先配置两个Servlet实现类的Servlet
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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"> 3 <display-name>config</display-name> 4 5 <servlet> 6 <servlet-name>fs</servlet-name> 7 <servlet-class>com.xiaoan.config.FirstServlet</servlet-class> 8 <load-on-startup>3</load-on-startup> 9 </servlet> 10 11 <servlet-mapping> 12 <servlet-name>fs</servlet-name> 13 <url-pattern>/fs</url-pattern> 14 </servlet-mapping> 15 16 17 <servlet> 18 <servlet-name>ss</servlet-name> 19 <servlet-class>com.xiaoan.config.SoundServlet</servlet-class> 20 <load-on-startup>1</load-on-startup> 21 </servlet> 22 <servlet-mapping> 23 <servlet-name>ss</servlet-name> 24 <url-pattern>/ss</url-pattern> 25 </servlet-mapping> 26 27 </web-app>
运行项目控制台输出为
Sound constiuctor
Sound init
First constiuctor
first init
说明<load-on-startup> 配置值越小 越会先加载
Servlet多映射
将上面的web.xml的fs servlet的配置中再添加一个servlet-mapping
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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"> 3 <display-name>config</display-name> 4 5 <servlet> 6 <servlet-name>fs</servlet-name> 7 <servlet-class>com.xiaoan.config.FirstServlet</servlet-class> 8 <load-on-startup>3</load-on-startup> 9 </servlet> 10 11 <servlet-mapping> 12 <servlet-name>fs</servlet-name> 13 <url-pattern>/fs</url-pattern> 14 </servlet-mapping> 15 <servlet-mapping> 16 <servlet-name>fs</servlet-name> 17 <url-pattern>/fs1/*</url-pattern> 18 </servlet-mapping> 19 <servlet-mapping> 20 <servlet-name>fs</servlet-name> 21 <url-pattern>*.html</url-pattern> 22 </servlet-mapping> 23 24 25 <servlet> 26 <servlet-name>ss</servlet-name> 27 <servlet-class>com.xiaoan.config.SoundServlet</servlet-class> 28 <load-on-startup>1</load-on-startup> 29 </servlet> 30 <servlet-mapping> 31 <servlet-name>ss</servlet-name> 32 <url-pattern>/ss</url-pattern> 33 </servlet-mapping> 34 35 </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