Servlet
2015年7月9日
2015年7月21日增加Annotation配置
2015年8月28日重构
2015年9月4日添加servlet注记、实现
由Java提出规范。由Tomcat等实现方案。并提供部分常用实现类。
目标:将Web应用与具体的服务器解耦,可以被所有实现规范的容器所使用。
原理:servlet规范规定所有的内容按照固定的目录存放。
流程:url请求发送到容器,容器调用servlet生成实例。
方法:
局部配置在当前应用下的WEB-INF(web information)中,全局配置在Tomcat的conf目录下
配置文件:web-inf/web.xml或注记。注意,不要重复设置同一个servlet。
servlet类.class:web-inf/classes。
servlet类使用的jar库:web-inf/lib。
其它文件应放在webapp的子目录中。
目标:配置与web服务相关的所有信息,是容器的配置入口。
原理:容器查找web.xml或注记,根据url实例化servlet类,并调用接口中的方法。
方法:使用web.xml描述。由于管理内容过多,可能导致可读性降低,现逐渐使用annotation解耦配置内容。
servlet使用名称作为标识。
<welcome-file-list>
<welcome-file>index.html </welcome-file>
…
</welcome-file-list>
是否启用注记:metadata-complete,如果为true,表示本xml完全配置,不启用注记。
<servlet-mapping>
<servlet-name>名称标识</servlet-name>
<url-pattern>请求url匹配模式</urlpattern>
</servlet-mapping>
<servlet>
<servlet-name>名称标识</servlet-name>
<servlet-class>具体的类名</servlet-calss>
</servlet>
业务类:com.thbd.TestServlet
package com.thbd;
import java.io.IOException;
import java.io.PrintWriter;
importjavax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
@WebServlet("/TestServlet")
public class TestServletextends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TestServlet() {
// TODO Auto-generated constructor stub
}
/**
* @seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
}
/**
* @seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<?xmlversion="1.0" encoding="ISO-8859-1"?>
<web-appxmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<description>
Servlet and JSP Examples.
</description>
<display-name>Servlet and JSPExamples</display-name>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.thbd.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/helloservlet</url-pattern>
</servlet-mapping>
</web-app>
目标:由于配置文件在大型应用中过于膨胀,可读性降低,耦合度过高,现在逐渐使用注记代替部分配置文件内容。
原理:容器检查注记,与web.xml一样。
当前配置文件可以完全实现annotation的所有功能,两者能够一一映射。
方法:标记为servlet:@WebServlet
设置属性名称:servlet-name,urlPatterns或者value,name等。
url配置模式使用urlPatterns或者values指定。可以指定一个或多个。
@WebServlet(name="TestServlet",urlPatterns="/TestServlet")
@WebServlet(name="TestServlet",urlPatterns={"/TestServlet",”/ts”})
参考:http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html
@WebServlet(name="TestServlet",urlPatterns="/TestServlet")
等价于:
<!--
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.thbd.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
-->
示例1:注记配置Servlet
Web.xml
<?xmlversion="1.0" encoding="GBK"?>
<web-appxmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="false">
</web-app>
ServletTest.java
package lee;
import java.io.IOException;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletTest
*/
@WebServlet(
description = "this is a servelt test withannotation",
urlPatterns = { "/ServletTest01" },
initParams = {
@WebInitParam(name = "name", value = "lixx12",description = "name of the person"),
@WebInitParam(name= "age", value = "16", description = "age of theperson")
})
public class ServletTestextends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private int age;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletTest() {
super();
// TODO Auto-generated constructor stub
}
/**
* @seeHttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletConfig config=getServletConfig();
this.name=config.getInitParameter("name");
this.age=Integer.parseInt(config.getInitParameter("age"));
System.out.println("Hello,Annotation!");
System.out.println("name="+name+",age="+age);
}
}
示例2:注记配置Servlet
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appversion="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false">
<description>
Servlet and JSP Examples.
</description>
<display-name>Servlet and JSPExamples</display-name>
</web-app>
//TestServlet.java
package com.thbd;
import java.io.IOException;
import java.io.PrintWriter;
importjavax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
@WebServlet(urlPatterns={"/TestServlet",”/ts”})
public class TestServletextends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TestServlet() {
// TODO Auto-generated constructor stub
}
/**
* @seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
}
/**
* @seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
1时应用启动就生成实例,默认为第一次请求时生成实例,此值越小,则越早实例化。
目标:响应http请求。
原理:响应get,post,put,delete等http标准请求。但通常只能get、post两种,而且两者一般执行相同的功能。因此一般使用service()作为实际的功能被各个响应函数调用(do*())。
所有相关的类和库都要分别放在classes和lib目录下。
方法:初始化init()(由构造函数调用),服务service()(由各个响应函数调用),释放destroy()(由析构函数调用)。
Init()和destroy()一般不会重写,通常只需要重写service()。
作为前端请求和后端处理库的中间件,并将结果返回给前端。
参考:http://blog.csdn.net/xtu_xiaoxin/article/details/8464808
http://blog.csdn.net/xtu_xiaoxin/article/details/8468629
http://www.cnblogs.com/xieduo/articles/822091.html
此接口保证了容器和servlet的解耦。
初始化:init(),容器启动时调用,初始化一次,从而可以提供服务。
服务:根据请求,调用相关服务。
析构:当web应用终止时,析构。
包括HTTP协议中的doGet(),doPut(),doPost()等。
目标:减化xml配置的辅助手段,对于不太容易变化的部分添加到源程序中。
增加可读性,减少开发周期,减少维护难度,增加配置自动检测。
注意:由于注解在源代码中集成,导致配置与源码耦合,因此仅限于将不易改变的内容使用注解配置(无法在部署环境中配置)。xml配置仍然为基本的解耦方式(但是太多了不好维护,只能将不易改变的直接集成到源码)。但是这种造成一个问题,结果不清晰。无法直接在运行环境通过配置文件获得或改变配置。
参考:https://en.wikipedia.org/wiki/Convention_over_configuration
http://www.quora.com/XML-vs-annotations-which-is-better-in-Spring-Why
http://stackoverflow.com/questions/17086421/annotations-vs-xml-advantages-and-disadvantages
http://stackoverflow.com/questions/182393/xml-configuration-versus-annotation-based-configuration
参考:http://blog.csdn.net/xiazdong/article/details/7208316
servlet3.0规范才能使用Annotation配置servlet,需要web.xml说明。
3.0规范增加metadata-complete属性说明xml是否是完全配置文件,默认为false,将搜索Annotation,如果设置为true,将只使用xml配置。
参考:http://www.oschina.net/question/133505_111261
http://stackoverflow.com/questions/9820379/what-to-do-with-annotations-after-setting-metadata-complete-true-which-resolv
示例:
<?xmlversion="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false">
<description>
Servlet and JSP Examples.
</description>
<display-name>Servlet and JSPExamples</display-name>
</web-app>
参见:注记配置:annotation
目标:配置servlet或filter等注记的初始化参数。
方法:不能独立使用,需要在父注记的初始化标记中设置。
示例:
@WebFilter(urlPatterns="/*",
initParams={@WebInitParam(name="init1",value="i111"),
@WebInitParam(name="init2",value="i222")})
参见:方法:过滤器Filter
参考:方法:监听器Listener
参见:方法:文件上传
参见:Servlet-文件上传MultipartConfig_Part.docx
参见:Servlet-过滤器Filter.docx
参见:Servlet-监听器Listener.docx
参见:Servlet-模块化开发.docx
参见:Servlet-异步执行AsyncContext.docx