java与servlet

servlet 搞java web开发的人一定不会陌生,而且大家还会时常用到它。

下面是java官方网站上对servlet的介绍:

java官网对于servlet的解释 写道

Java Servlet Technology Overview
Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools.

Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, and crash protection.

Today servlets are a popular choice for building interactive Web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.

You might want to check out the latest information on JavaServer Pages (JSP) technology. JSP technology is an extension of the servlet technology created to support authoring of HTML and XML pages. It makes it easier to combine fixed or static template data with dynamic content. Even if you're comfortable writing servlets, there are several compelling reasons to investigate JSP technology as a complement to your existing work.

通过简单的翻译可以读出,servlet是针对cgi而产生的更简单高效的产生动态内容的组件,它可以很轻松的生成动态内容,而且可以通过servlet调用底层的数据库,亦或是其他服务层内容,所以servlet就像是一个显卡的GPU,既可以显示内容又可以运算逻辑,不知道我这么比喻恰不恰当。

而后又产生了JSP,使得servlet显示网页内容的工作得以释放,在JSP中可以更简单的编辑与调整标准Html内容。

servelt=java server+applet

当初sun的意思是将servlet定义为服务端的小程序搭配applet来使用,但applet早早的夭折了。

servlet是一种小型的Java程序,它扩展了Web服务器的功能。作为一种服务器端的应用,当被请求时开始执行。Servlet提供的功能大多与JSP类似,不过实现的方式不同。JSP通常是大多数HTML代码中嵌入少量的Java代码,而servlets全部由Java写成并且生成HTML

JSP没有出现之前程序员要在servlet中编写大量例如:

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is a servlet!");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();

这样的代码,仅仅输出一句话就这么麻烦,那么整个一个网页的内容呢?可想而知是多么可怕的工作量!而且一个项目不仅仅只有一个网页,一个大型项目维护起来是多么的麻烦和恐怖。幸运的是当时的sun也看到了这一点,没多久就发布了JSP1.0,使得程序员在海量的代码中得以解脱,完全可以把网页内容交由美工去做了:)。

Servlet发展至今已经是3.0版本,功能更加强大,支持异步处理,可选择插件支持等等,现在大家用的servlet版本普遍为2.x

Servletj2ee/javaeejavax.servlet包中的一个接口,打开官网的api可以看到里面有很多与servlet相关的接口与抽象类,因为不开源所以我们没办法分析它的源代码,而且javaee是一种标准,实现全靠其他厂商。

Api地址:http://docs.oracle.com/javaee/5/api/

Interfaces

Servlet —servlet编写必须实现的重要接口

ServletConfig —包含servlet相关信息,在servlet初始化是为其传递信息

ServletContext —servlet上下文配置,也就是servlet在web.xml中得相关配置信息

ServletContextAttributeListener —ServletContext属性监听器

ServletContextListener —ServletContext监听器

ServletRequest —为servlet获取request对象的接口

ServletRequestAttributeListener —ServletRequest属性监听器

ServletRequestListener —ServletRequest监听器

ServletResponse —为servlet获取response对象的接口

Classes

 GenericServlet —通用servlet实现类

 ServletContextAttributeEvent —ServletContextAttribute事件

 ServletContextEvent —ServletContext事件

 ServletInputStream —servlet中的inputstream

 ServletOutputStream —servlet中的outputstream

 ServletRequestAttributeEvent —ServletRequestAttribute事件

 ServletRequestEvent —ServletRequest事件

 ServletRequestWrapper —ServletRequest包装类,实现了ServletRequest的方

 ServletResponseWrapper —ServletResponse包装类,实现了ServletResponse的方法

Exceptions

ServletException —servlet相关异常

 

下面一一介绍跟servlet相关重要的类或者接口:

Servlet接口:这个接口是所有servlet必须实现的,通过读取api的注释可以了解到,想编写一个servlet用户可以去继承GenericServlet 或者 HTTPServlet这两个抽象类,这两个抽象类。

Servlet接口中的方法有:

/**
	 * 获取ServletConfig对象实例
	 */
	public ServletConfig getServletConfig() {
		return null;
	}
	/**
	 * 获取servlet相关信息
	 */
	public String getServletInfo() {
		return null;
	}
	/**
	 * 初始化方法
	 */
	public void init(ServletConfig config) throws ServletException {

	}
	/**
	 * servelt中服务方法,相当于我们熟悉的doGet,doPost
	 */
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {

	}
	/**
	 * 默认销毁方法
	 */
	public void destroy() {

}

 

api中我们可以看见有这样一段话:

写道
1.The servlet is constructed, then initialized with the init method.
2.Any calls from clients to the service method are handled.
3.The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

 

这段话说明的是servlet的生命周期,1.首先servlet被实例化,调用初始化方法。2.从客户端的请求被发送至servlet,调用service方法。3.service执行之后调用销毁方法,整个servlet被销毁。此外除了这些生命周期方法外还可以调用getServletConfig方法,返回类似作者、注释等相关信息。

 

ServletConfig接口:这个接口比较简单就几个方法,都是用来获取servlet相关参数的。

 

/**
	 * 获取初始化参数
	 */
	public String getInitParameter(String pars) {
		return null;
	}
	/**
	 * 获取初始化参数名称
	 */
	public Enumeration getInitParameterNames() {
		return null;
	}
	/**
	 * 获取ServletContext实例
	 */
	public ServletContext getServletContext() {
		return null;
	}
	/**
	 * 获取servlet名称
	 */
	public String getServletName() {
		return null;
}

 

ServletContext接口:这个接口里有很多方法,大多是获取servlet相关配置和参数的,所以我就不介绍了,这也是一个比较重要的接口。

ServletRequestServletResponse接口:这两个接口也非常重要,HttpServletRequestHttpServletResponse就是分别实现了这两个接口,这么说大家就非常熟悉了吧,通过requestresponse对象可以做很多操作,我就不介绍了。

GenericServlet类:通用的servlet实现类继承了Servlet, ServletConfig这两个接口,实现自己的servlet可以继承这个类,当然是没人会那么做的,因为sun已经为我们做好了现成的实现类HttpServlet

HttpServlet类:继承了GenericServlet类,实现接口有Servlet, ServletConfig,大家开发都会继承这个类,一般只要实现doGetdoPost方法就行了。这个类还有一些常用的其他方法:

写道
•doGet, 处理get请求的方法
•doPost, 处理post请求的方法
•doPut, 处理put请求的方法
•doDelete, 处理delete请求的方法
•init and destroy, 默认初始化和销毁方法
•getServletInfo, 获取servlet信息

 

关于putdelete可以自己搜索一下,因为用途比较少,在这我就不解释了。

下面是一个最简单的servlet实例和相关web.xml的配置:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述:这就是一个最简单的servlet实例了
 * 
 * @author ming.li<br/>
 *         <a href="http://g21121.iteye.com">iteye bolg</a>
 * @time 2012-1-13 上午11:05:45
 */
public class TestServlet extends HttpServlet   {
	/**
	 * get请求处理方法
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取name为param的参数值
		String param=(String) request.getAttribute("param");
		System.out.println(param);
	}
	/**
	 * post请求处理方法
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//跳转到index.html这个页面
		response.sendRedirect("index.html");
	}
}

下面是web.xml中的配置:

 <!-- servlet配置 -->
  <servlet>
    <description>test servlet</description>
    <display-name>test servlet</display-name>
    <servlet-name>testServlet</servlet-name>
    <!-- 这个是servlet的全路径,如果有报名也要写全 -->
    <servlet-class>TestServlet</servlet-class>
  </servlet>
  <!-- servlet上下文配置,注意两个servlet-name要保持一致 -->
  <servlet-mapping>
    <servlet-name>testServlet</servlet-name>
    <!-- 请求这个servlet的地址('/servlet/testServlet'可以自己任意命名),eg:http://path//servlet/testServlet -->
    <url-pattern>/servlet/testServlet</url-pattern>
  </servlet-mapping>

 

 

 

猜你喜欢

转载自286.iteye.com/blog/1350406