规避Servelet线程安全问题
路径格式的编写
url-pattern:就是提供给外部访问的路径
<servlet-mapping>
<servlet-name>EServlet</servlet-name>
<url-pattern>*.do</url-pattern>
<!--
配置相对路径:
/ => /* => http://localhost:8080/ServletProject/任意
/Eservlet => http://localhost:8080/ServletProject/EServlet
/ABC/EServlet =>http://localhost:8080/ServletProject/ABC/EServlet
/ABC/* => http://localhost:8080/ServletProject/ABC/
后缀名匹配:
*.do => http://localhost:8080/ServletProject/dgdsg/dg/dgsg/sd/g.do
原则:匹配范围越大,优先级越低
-->
</servlet-mapping>
ServletContext
介绍:
Servlet中的全局环境,存储一些项目中的共有资源,
创建:项目启动的时候创建
销毁:项目关闭的时候销毁
获取:
通过ServletConfig对象getServletContext();
功能:
1.可以获得项目参数
2.时Servlet 技术中的3个域对象之一
3.获得项目内的资源
实例:
- web.xml中配置如下Servlet全局上下文参数
<context-param>
<param-name>name</param-name>
<param-value>tom</param-value>
</context-param>
<context-param>
<param-name>age</param-name>
<param-value>18</param-value>
</context-param>
- Servlet 类中如下
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext sc = getServletContext();
Enumeration<String> names = sc.getInitParameterNames();
while (names.hasMoreElements()) {
String key = names.nextElement();
String value = sc.getInitParameter(key);
response.getWriter().write(
"<h2> "+key+"=========>"+value+ "</h2>");
}
}
注意:用sc去获取响应的参数,
若直接调用getInitParameterNames();getInitParameter(key);
则是获取该SErvlet中的配置参数,而不是全局的配置参数