Java Servlet是与平台无关的服务器端组件,运行于Servlet容器中(如Tomcat),Servlet容器负责Servlet和客户端的通信以及调用Servlet的方法,Servlet和客户端的通信采用“请求/响应”的模式。Servlet可完成以下功能:
1、创建并返回基于客户请求的动态HTML页面。
2、创建可以嵌入到现有HTML页面中的HTML片段。
3、与其它服务器资源(如数据库或基于Java的应用程序)进行通信。
4、接收多个客户端的输入,并将结果广播到多个客户端上,例如,Servlet可以实现支持多个参与者的游戏服务器。
5、根据客户请求采用特定的MIME(Multipurpose Internet Mail Extensions)类型对数据过滤,例如进行图像格式转换。
Servlet的框架由两个包组成:javax.servlet和javax.servlet.http。在javax.servlet包中定义的类和接口是独立于协议的。在javax.servlet.http包中定义了采用HTTP通信协议的类和接口。javax.servlet.http包中的某些类和接口扩展继承了某些javax.servlet包中的类和接口。
Servlet框架的核心是javax.servlet.Servlet接口,所有的Servlet类都必须实现这个接口。Servlet接口定义的方法如下:
//负责初始化Servlet对象
public void init(ServletConfig config) throws ServletException;
//获得ServletConfig接口,可以得到Servlet的相关参数
public ServletConfig getServletConfig();
//负责响应客户端的请求
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
//获得Servlet的相关信息
public String getServletInfo();
//当Servlet对象退出生命周期时,负责释放占用的资源
public void destroy();
在javax.servlet包中,GenericServlet类实现了Servlet接口,在javax.servlet.http包中,HttpServlet类扩展了GenericServlet类。当用户开发自己的Servlet时,必须扩展以上两个类中的一个,如果扩展自GenericServlet类,则必须自己实现service方法,如果扩展自HttpServlet类,则不需要自己实现service方法,因为HttpServlet类已经实现了该方法。
GenericServlet类的service方法是一个抽象方法,只有两个参数:ServletRequest和ServletResponse。HttpServlet类的service方法也只有两个参数:HttpServletRequest和HttpServletResponse。HttpSevletRequest接口和HttpResponse接口分别扩展自ServletRequest和ServletResponse接口,都提供了与特定协议HTTP相关的数据。
ServletRequest接口的方法如下:
//获得属性值
public Object getAttribute(String name);
//获取所有属性名的枚举
public Enumeration getAttributeNames();
//获得字符编码
public String getCharacterEncoding();
//设置字符编码
public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException;
//获得内容长度
public int getContentLength();
//获得客户请求数据的MIME类型
public String getContentType();
//获得可以读取客户请求数据的输入流
public ServletInputStream getInputStream() throws IOException;
//获得参数值
public String getParameter(String name);
//获得所有参数名的枚举
public Enumeration getParameterNames();
public String[] getParameterValues(String name);
public Map getParameterMap();
public String getProtocol();
public String getScheme();
public String getServerName();
public int getServerPort();
public BufferedReader getReader() throws IOException;
//获得客户端的IP
public String getRemoteAddr();
//获得客户端的主机名
public String getRemoteHost();
//设置属性值
public void setAttribute(String name, Object o);
//移除属性
public void removeAttribute(String name);
public Locale getLocale();
public Enumeration getLocales();
public boolean isSecure();
public RequestDispatcher getRequestDispatcher(String path);
public String getRealPath(String path);
//获得客户端的端口
public int getRemotePort();
public String getLocalName();
public String getLocalAddr();
public int getLocalPort();
ServletResponse接口的方法如下:
//获得Servlet发送的响应数据的字符编码
public String getCharacterEncoding();
//返回Servlet发送的响应数据的MIME类型
public String getContentType();
//获得可以向客户端发送二进制数据的输出流对象ServletOutputStream
public ServletOutputStream getOutputStream() throws IOException;
//获得可以向客户端发送字符数据的PrintWriter对象
public PrintWriter getWriter() throws IOException;
//设置Servlet发送的响应数据的字符编码
public void setCharacterEncoding(String charset);
//设置Servlet发送的响应数据的长度
public void setContentLength(int len);
//设置Servlet发送的响应数据的MIME类型
public void setContentType(String type);
public void setBufferSize(int size);
public int getBufferSize();
public void flushBuffer() throws IOException;
public void resetBuffer();
public boolean isCommitted();
public void reset();
public void setLocale(Locale loc);
public Locale getLocale();
Servlet的init方法有如下两种形式:
public void init(ServletConfig config) throws ServletException
public void init() throws ServletException
在Servlet的初始化分阶段,Servlet容器会为Servlet创建一个ServletConfig对象,用来存放Servlet的初始化配置信息,如Servlet的初始参数。如果Servlet覆盖了带参数的init方法,则必须在函数体内先调用super.init(config); 以确保config参数引用了ServletConfig对象。如果Servlet覆盖了没有带参数的init方法,则不需要调用super.init(); 方法,可以通过调用getServletConfig()方法来获得ServletConfig对象。
Servlet容器会为Web应用创建一个唯一的全局的ServletContext对象,可以把它看成是一个Web应用的服务器端组件的共享内存。它有如下方法:
public ServletContext getContext(String uripath);
public String getContextPath();
public int getMajorVersion();
public int getMinorVersion();
//返回文件的MIME类型
public String getMimeType(String file);
public Set getResourcePaths(String path);
public URL getResource(String path) throws MalformedURLException;
public InputStream getResourceAsStream(String path);
public RequestDispatcher getRequestDispatcher(String path);
public RequestDispatcher getNamedDispatcher(String name);
public Servlet getServlet(String name) throws ServletException;
public Enumeration getServlets();
public Enumeration getServletNames();
public void log(String msg);
public void log(Exception exception, String msg);
public void log(String message, Throwable throwable);
//返回网络路径path对应的文件系统路径
public String getRealPath(String path);
//返回Servlet容器的名称和版本
public String getServerInfo();
//获得指定名称的参数值,该参数是Web应用的初始化参数
public String getInitParameter(String name);
//返回Web应用的所有初始化参数的名称的Enumeration对象
public Enumeration getInitParameterNames();
//获得指定名称的属性值
public Object getAttribute(String name);
//返回所有属性名的一个Enumeration对象
public Enumeration getAttributeNames();
//将一个对象与一个属性名绑定,并存放到ServletContext中
public void setAttribute(String name, Object object);
//移除指定名称的属性
public void removeAttribute(String name);
public String getServletContextName();
注意: 一般在HptpServlet的子类中,将doPost方法的实现合并到doGet方法中,也就是在doPost方法中简单地调用doGet方法.因为一般情况下对于Get和Post请求,它们都是一样的处理.
编译了Servlet后,将它打包成jar放到WEB-INF/lib目录下,或将Servlet的class文件放到WEB-INF/classes/目录下,再在WEB-INF/web.xml配置文件中配置这些servlet,就可以在Web应用中访问servlet了,配置如下:
<servlet> <servlet-name>my_servlet</servlet-name> <servlet-class>com.mycompany.ServletClass1</servlet-class> < init-param> <!--定义servlet的初始化参数, 可以有多个init-param参数--> < param-name>iParam< /param-name> < param-value>2< /param-value> < /init-param> < load-on-startup>2< /load-on-startup> <!--定义servlet的加载顺序--> </servlet> <servlet-mapping> <servlet-name>my_servlet</servlet-name> <url-pattern>*.hello</url-pattern> </servlet-mapping>