对于一个J2EE应用的开发者,或者叫java web后台的开发者来讲。常常会和web.xml打交道,偶尔用到几个标签不知道啥意思。而后就度娘一下,长此以往虽然大概知道web.xml的基本使用方法,可是没有一个系统的学习。我就是这样一我的,今天来系统的学习一遍。(http://docs.oracle.com/cd/E11035_01/wls100/webapp/web_xml.html#wp1070143)html
<?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_2_5.xsd " version="2.5"> </web-app>
<link rel="shortcut icon" href="http://example.com/favicon.ico" type="image/vnd.microsoft.icon" /> <link rel="icon" href="http://example.com/favicon.ico" type="image/vnd.microsoft.icon" />
display-name:The optional display-name
element specifies the Web application display name, a short name that can be displayed by GUI tools.可见意义也不是很大。java
description:The optional description element provides descriptive text about the Web application.web
<context-param> <param-name>param_name</param-name> <param-value>param_value</param-value> </context-param>
在JSP页面读取:sql
${initParam.param_name}
在servlet中读取:json
String param_name=getServletContext().getInitParamter("param_name");
在Filter中读取:api
String param_name = request.getServletContext().getInitParameter("param_key");
元素 | 选项 | 描述 |
<icon> | 可选 | 指定icon表明GUI的IDE中表明Filter,没有实际意义 |
<filter-name> | 必选 | 定义过滤器的名字,在部署描述文件的其余地方进行引用 |
<display-name> | 可选 | 在GUI的IDE中显示缩略名 |
<description> | 可选 | A text description of the filter. |
<filter-class> | 必选 | 过滤器对应的class |
<init-param> | 可选 | 包含一个键值对,做为过滤器的初始属性 |
一个简单的例子:tomcat
<filter> <filter-name>LoginFilter</filter-name> <filter-class>com.xxxx.filter.LogFilter</filter-class> <init-param> <param-name>Site</param-name> <param-value>Hello world</param-value> </init-param> </filter>
在过滤器初始化方法获取键值:安全
public void init(FilterConfig config) throws ServletException { logger.info("Filter init"); // 获取初始化参数 String site = config.getInitParameter("Site"); // 输出初始化参数 logger.info("网站名称: " + site); }
元素 | 选项 | 描述 |
<filter-name> | 必选 | 映射URL或servlet的filter的名字 |
<url-pattern> | 必选或使用<servlet进行映射> | 指定须要过滤的URL模式 |
<servlet-name> | 必选或者使用<url-pattern> | 指定须要过滤的servlet name |
简要说明:使用<url-pattern>经过匹配URI调用过滤器,使用<servlet-name>,通过改servlet的全部请求都会走过滤器。若是同时配置<url-pattern>和<servlet-name>,只要知足其一都会走过滤器。cookie
一个简单的例子,全部的请求都会走LoginFilter过滤器:session
<filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> <!--<servlet-name>helloWorld</servlet-name>--> </filter-mapping>
元素 | 选项 | 描述 |
<icon> | 可选 | 指定icon表明GUI的IDE中表明Filter,没有实际意义 |
<servlet-name> | 必选 | 定义servlet名字,在部署描述文件其余地方可引用 |
<display-name> | 可选 | 在GUI的IDE中显示缩略名,没实际意义 |
<description> | 可选 | servlet描述信息 |
<servlet-class> | 必选或使用<jsp- file> |
servlet对应的class,需使用彻底限定名称(包含包名),在<servlet>中只能使用<servlet-class>或<jsp- file>其中之一 |
<jsp-file> | 必选或使用<servlet-class> | 使用相对于应用程序根目录的全路径,在<servlet>中只能使用<servlet-class>或<jsp- file>其中之一 |
<init-param> | 可选 | 包含一个键值对做为servertd的初始化参数,每一个键值对用<init-param> 分开 |
<load-on-startup> | 可选 | 设置web容器加载servlet的顺序,值为正整数,值越小优先级越高。不指定或者指定的值为非正整数加载顺序随机。 |
<run-as> | 可选 | 指定运行web程序的标识着,包含两个子标签 <description>和<role-name> |
<security-role- ref> |
可选 | 引用定义在<security-role>中的安全角色名称,角色名称被硬编码在<security-role>,角色最终定义在容器对应的配置文件中,好比Tomcat中的tomcat-users.xml。该标签引用官网的一段说明以下: The security-role-ref element is used when an application uses the HttpServletRequest.isUserInRole(String role) method. The value of the role-name element must be the String used as the parameter to the HttpServletRequest.isUserInRole(String role) method. The role-link must contain the name of one of the security roles defined in the security-role elements. The container uses the mapping of security-role-ref to security-role when determining the return value of the call. (https://docs.oracle.com/cd/E19226-01/820-7627/bncbb/index.html) 我理解的大概意思就是,为了配合servlet中代码对角色权限的控制,主要是isUserInRole方法,来决定servlet中的业务处理逻辑。 |
servlet-mapping元素定义了servlet和URL之间的映射
元素 | 选项 | 描述 |
<servlet-name> | 必选 | 须要和URL映射的servlet的名称,名称和<servlet>中定义的名称一致 |
<url-pattern> | 必选 | http://host:port + WebAppName后的部分的URL将会和这定义的URL比较,若是匹配的话就会调用其映射的servlet处理此次请求 |
元素 | 选项 | 描述 |
<description> | 可选 | 安全角色描述文本 |
<role-name> | 必选 | 角色名称。对于Tomcat和WebLogic,必须是两个容器中定义的角色,对于Tomcat在配置文件 tomcat-users.xml中有相应角色和用户的对应。 |
十一、<security-role-ref>
元素 | 选项 | 描述 |
role-link |
必选 | The <role-link> element in the security-role-ref element must match a <role-name> defined in the <security-role>element of the same web.xml deployment descriptor |
role-name |
可选 | 在servlet中调用isUserInRole("tomcat-role"),参数就是该标签对应的值或者直接role-link标签对应的值。 |
十二、<security-constraint>
定义对资源集合的访问权限
元素 | 选项 | 描述 |
<web-resource- collection> |
必选 | 定义web应用程序资源集合 |
<auth-constraint> | 可选 | 定义访问这个集合资源的权限 |
<user-data- constraint> |
可选 | Defines how the client should communicate with the server.具体参考 user-data-constraint |
1三、 <login-config>
该标签用于配置验证方式。
元素 | 选项 | 描述 |
<auth-method> | 可选 | 指定验证的方法,可能值:
|
<realm-name> | 可选 | The name of the realm that is referenced to authenticate the user credentials |
<form-login- config> |
可选 | Use this element if you configure the <auth-method> to FORM. 若是使用form表单进行验证的话还要配置form表单对应的文件,以及验证错误的跳转页面,具体参考:form-login-config |
针对以上八、九、十、十一、十二、13举个例子:
<servlet> <servlet-name>ApiServlet</servlet-name> <servlet-class>com.xxxx.servlet.ApiServlet</servlet-class> <security-role-ref> <role-name>tomcat-role</role-name> <role-link>tomcat</role-link> </security-role-ref> </servlet> <servlet-mapping> <servlet-name>ApiServlet</servlet-name> <url-pattern>/api</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> <web-resource-name>api</web-resource-name> <url-pattern>/api</url-pattern> <http-method>PUT</http-method> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>tomcat</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>My Hello World Application</realm-name> </login-config> <security-role> <role-name>tomcat</role-name> </security-role>
tomcat对应的tomcat-users.xml设置:
<role rolename="tomcat"/> <!--<role rolename="role1"/>--> <user username="tomcat" password="tomcat123" roles="tomcat"/> <!--<user username="both" password="tomcat123" roles="tomcat,role1"/>--> <!-- <user username="role1" password="<must-be-changed>" roles="role1"/>-->
ApiServlet中部分代码:
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RandomPwd randomPwd = RandomStringGenerator.getRandomString(); Cookie cookie = new Cookie("tes123", "456"); cookie.setMaxAge(60); response.addCookie(cookie); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = response.getWriter(); out.println(JSON.toJSONString(randomPwd)); if (request.isUserInRole("tomcat")) { logger.info("Have tomcat role!"); } else { logger.info("Don't have tomcat role!"); } String param_name = getServletContext().getInitParameter("testkey"); logger.info(param_name); }
加上以上设置,只要访问/api接口就须要BASIC认证,验证经过了才能访问接口。
定义对外部资源的引用
元素 | 选项 | 描述 |
<description> | 可选 | 简单的文本描述 |
<res-ref-name> | 必选 | 资源在JNDI树中的名字,servletz在web程序中使用这个名字去寻找这个资源的引用 |
<res-type> | 必选 | 资源在Java中定义的类型,必须使用彻底限定名称。例如:<res-type>javax.sql.DataSource</res-type> |
<res-auth> | 必选 | 用于控制资源的安全性。 If set to |
<res-sharing-scope> | 可选 | 指定资源是否能够被共享,可选的值:
|
定义一个程序监听器
元素 | 选项 | 描述 |
<listener-class> | 可选 | 响应web应用程序的的class |
注意:
<listener>
element. The event declaration defines the event listener class that is invoked when the event occurs. The <listener>
element must directly follow the <filter>
and <filter-mapping>
elements and directly precede the <servlet>
element. You can specify more than one event listener class for each type of event. WebLogic Server invokes the event listener classes in the order that they appear in the deployment descriptor (except for shutdown events, which are invoked in the reverse order). For example:<listener> <listener-class>myApp.MyContextListenerClass</listener-class> </listener> <listener> <listener-class>myApp.MySessionAttributeListenerClass</listener-class> </listener>
大概意思是,listener-class必须跟在<filter>后面,<servlet>前面。
经常使用的几个监听器:
javax.servlet.http.HttpSessionEvent
provides access to the HTTP session object
javax.servlet.ServletContextEvent
provides access to the servlet context object.
javax.servlet.ServletContextAttributeEvent
provides access to servlet context and its attributes
javax.servlet.http.HttpSessionBindingEvent
provides access to an HTTP session and its attributes
Servlet Context Event Listener Class Example package myApp; import javax.servlet.http.*; public final class MyContextListenerClass implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { /* This method is called when the servlet context is initialized(when the Web application is deployed). You can initialize servlet context related data here. */ } public void contextDestroyed(ServletContextEvent event) { /* This method is invoked when the Servlet Context (the Web application) is undeployed or WebLogic Server shuts down. */ } }
参考连接:http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/app_events.html#178122
可选的welcome-file-list包含一个有顺序的welcome-file列表,当request请求的是一个目录的时候,该列表的第一个文件会被查找并返回,若是没找到就按列表顺序一值往下找。
元素 | 选项 | 描述 |
<welcome-file> | 可选 | 被指定欢迎文件的名称,例如:index.html |
一个例子:
<welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list>
元素 | 选项 | 描述 |
<session-timeout> | 可选 | 指定应用程序中session的有效时间,单位分钟。该值的设置会覆盖Tomcat或weblogic中的配置文件的设置, Default value: -2 Maximum value: Integer.MAX_VALUE ÷ 60
|
元素 | 选项 | 描述 |
<description> | 可选 | 设定的说明 |
<display-name> | 可选 | 设定名称 |
<url-pattern> | 必选 | 设定值所影响的范围,如: /CH2 或 /*.jsp |
<el-ignored> | 可选 | 若为 true,表示不支持 EL 语法 |
<scripting-invalid> | 可选 | 若为 true,表示不支持 <% scripting %>语法 |
<page-encoding> | 可选 | 设定 JSP 网页的编码 |
<include-prelude> | 可选 | 设置 JSP 网页的抬头,扩展名为 .jspf |
<include-coda> | 可选 | 设置 JSP 网页的结尾,扩展名为 .jspf |
trim-directive-whitespaces> | 可选 | sp中会常用到使用jsp标签和jstl的标签,好比<%@ page ..%>, <%@ taglib ...%>, <c:forEach....%>, 尤为是循环标签,在jsp最终输出的html中会产生大量的空行,使得性能下降。 |
一个简单例子以下:
<jsp-config> <taglib> <taglib-uri>Taglib</taglib-uri> <taglib-location>/WEB-INF/tlds/MyTaglib.tld</taglib-location> </taglib> <jsp-property-group> <description>Special property group for JSP Configuration JSP example.</description> <display-name>JSPConfiguration</display-name> <url-pattern>/jsp/* </url-pattern>
<trim-directive-whitespaces>true </trim-directive-whitespaces> <el-ignored>true</el-ignored> <page-encoding>GB2312</page-encoding> <scripting-invalid>true</scripting-invalid> <include-prelude>/include/prelude.jspf</include-prelude> <include-coda>/include/coda.jspf</include-coda> </jsp-property-group> </jsp-config>