[读书笔记]J2EE 基本概念 --- Servlet

来源:互联网 发布:淘宝工作招聘 编辑:程序博客网 时间:2024/05/16 19:30

Introduction To Servlets
The biggest benefit servlets offer developers is that they are designed specifically to process HTTP requests coming from the Web client and pass back a suitable response.
In terms of structure, servlets are specialized Java classes that closely resemble the structure of Java applets, but they run on a Web server instead of a client.
An interesting point to note is that servlets can never have their own graphical user interface.  Web servers host these components through the use of a Web container that manages all aspects of their life cycle.

servlets提供给开发人员的最大的好处就是,它们是专门设计出来处理来自客户端的HTTP请求,并且返回合适的响应。从结构上来说,servlets是特殊的java类,它们和Java applets的结构非常相似,不同的是,servlets运行在服务器端,而不是客户端。值得注意的一个有趣的地方是,servlets不可能拥有自己的图形用户界面。网络服务器通过使用容器来运行这些组件,容器负责管理servlets生命周期的各个方面。


Common usage
Most Web developers use servlets as the main point of entry to their server application from the Web client, and in this way, they are simply used as a conduit to pass information back and forth between the client and the server.
大多数网络开发者使用servlets作为从客户端到服务器的入口点,而且,使用这种方式,servlets只是简单的作为一个管道在客户端和服务器端之间来来回回的传递信息。

Best Served Small

In the past, servlets were often built to perform most or all of the following tasks:


n Check and process user input
n Handle significant business logic
n Perform database queries, updates, and synchronization
n Handle complex Web transactions
n Generate dynamic Web page content as output
n Handle  Web page forwarding

More advanced J2EE solutions make use of JSP, EJB, and JavaBeans to split up and offload much of this work, often using new mechanisms built into J2EE to simplify the more difficult tasks for the developer.
Servlets are responsible for a more manageable set of tasks:
Ø Gathering and validating user input, but little or no actual processing
Ø Coordination of output, but with little or no direct generation of dynamic Web page content
Ø Minimal business logic

 过去,servlets常常具有下述大部分或者所有的功能:

检查并处理用户输入
处理重要的商业逻辑
执行数据库查询,更新,等
处理复杂的web事务
产生要输出的网页中的动态内容
处理页面跳转


更先进的J2EE解决方案使用了JSP,EJB和JavaBeans来分别完成上述的工作,为开发者提供了新的J2EE内嵌机制来简化这些复杂的任务。
servlets则负责一些更加可管理的任务:

收集和验证用户输入,但是很少,或者根本不进行实际的处理
协作输出工作,但是很少,或者根本不直接产生网页的动态内容
包含的商业逻辑尽可能的少

Servlet Life Cycle
Servlets are deployed within a servlet container, which in turn is hosted by a Web server.  The particular capabilities and level of compliance of the Web server determines which version of the servlet specification you need to be working with.
The basic behavior of a servlet involves a request-response type model derived from the way the HTTP works; thus, the inherent applicability as a Web component.
Servlets are builts as Java classes that extend one of two basic servlet implementation classes: HttpServlet and GenericServlet.  The former is the most often used, yet slightly more complex of the two.  Both servlet types employ the same basic life cycle.
servlets运行在一个servlet容器中,而这个servlet容器运行在一个web服务器中。web服务器的特定能力和版本决定了你需要使用的servlet的版本。
servlet的基本行为涉及一种从HTTP中衍生出来的 请求-响应 模型;即作为一个web组件的内在适用性。
servlet就是Java类,它继承了两个基本的servlet实现类中的一个:HttpServlet 或者 GenericServlet。前者是最常用的,但是也是比较复杂的一个。两个servlet类型都具有相同的基本生命周期。

Life Cycle Methods
The servlet life cycle makes use of three basic request handler methods, of which any or all can be implemented within the extended servlet classes.
init: Initialize the servlet
service: Services the client request
destroy: Destroy the servlet

Of these methods, the service method is the most interesting because it actually does the majority of the necessary processing.  It typically does the following:
n Receives the request from the client
n Reads the request data
n Writes the response headers
n Gets the writer or output stream object for the response
n Writes the response data

The service method is at the heart of the GenericServlet type.  However, it is almost never overridden and instead is split into lower level HTTP request handlers when used with the HttpServlet type.
The init and destroy life cycle methods are always available to be overridden, but in several cases might not be used if the servlet has no specific objects or connections it needs to initialize or terminate.

Convenience Method
Besides the life cycle methods, servlets commonly make use of what are referred to as convenience methods.  One such convenience method that applies for all servlets is getServletInfo, which returns a general info string about the particular servlet – normally author, version, usage, and so on.

Required method
When building a servlet that extends the GenericServlet class, the service life cycle method must be implemented; otherwise, the servlet is invalid.  All other methods are optional.

Request Handling
Servlets are request-driven and have specific capabilities available to them that simplify handling of incoming requests.
When the Web container receives a request intended for a servlet, it encapsulates the incoming data into a ServletRequest object (commonly referred to as the request object) and passes it on as a parameter to the servlet’s service method.  The servlet can then use the methods available in the ServletRequest interface to query the request object.
Such as:
getParameterNames;
getParameter;

servlets是请求驱动,并且有专门的功能来简化对于请求的处理。

当web容器接收到一个对servlet的请求的时候,它把进来的数据封装到一个ServletRequest对象中(这个对象常常称作“request object”),然后把这个对象作为一个参数传递给servlet的service方法。servlet就能够使用ServletRequest接口中的方法对这个对象进行查询。(获得封装在这个对象中的数据---add by FITZWILLIAM

下面这个方法应该都用过吧

e.g.
String userID=request.getParameter(“USERID”);

Response Generation
A request generally warrants a response, and servlets are no exceptioni in this regard.
Servlets use ServletResponse to simplify this common task.  The ServletResponse object, commonly referred to as the response object, is in fact provided to a servlet alongside the request object as a parameter to the service method.
Output can be written in either binary or character format by obtaining a handle to either a ServletOutputStream object or a PrintWriter object, respectively.

一个请求通常都有一个对应的响应,servlets也不例外。

servelts使用ServletResponse来简化这项常见工作。ServletResponse对象,通常称为"response object",实际上和request object一起,作为一个参数传递给了service方法。

输出可以采用二进制形式,或者是字符形式,二者需要分别获得一个ServletOutputStream对象,或者一个PrintWriter对象。

e.g.
PrintWriter out;
..
response.setContentType(“test/html“);
..
out=response.getWriter();
out.println(“<HTML><HEAD><TITLE>”);
..
out.flush();
out.close();

 


HTTP Request Handlers
The HttpServlet class extends the GenericServlet class and therefore inherits all of the standard servlet capabilities.  In addition to the basic servlet life cycle methods and convenience method, the more complex HttpServlet class adds methods to aid in the processing of HTTP request.  These commonly used handler methods are
doGet: Handles HTTP GET requests
doPost: Handles HTTP POST requests

Quick Guide to HTTP Requests
For the most commonly used request handler methods, the following list provides a quick guide of what the HTTP requests are for:
Get: A call to get information from the server and return it in a response to the client.  The method processing this call must not have any side effects, so it can be repeated safely again and again.  A GET call is typically used when s servlet URL is accessed derectly from a Web browser or via a forward from a form on an HTML or JSP page.  A GET call shows the data being passed to servlet as part of the displayed URL on most Web browsers.  In certain cases, this might not be very desirable from a security perspective. 
POST: A call to allow the client to send data to the server.  The method processing this call is allowed to cause side effects, such as updating of data stored on t he server.  A POST call can be used instead of a GET when forwarding from a form on an HTML or JSP page.  Unlike GET, the use of POST hides from view any data being passed to the servlet.  Some developers choose to process GET and POST exactly the same, or simply ignore one or the other if they do not want that particular call to be supported.
PUT: 略
DELETE: 略

 

The RequestDispatcher Interface
Given the simplicity of servlets, it makes sense to keep each servlet focused on a specific task, and then set up multiple servlets to collaboratively achieve a more complex task.  Servlets can take care of the mechanical aspects of such collaborative efforts easily by implementing the RequestDispatcher interface.
The RequestDispatcher interface provides two key capabilities:
Forward: This method allows a servlet to forward a request to another Web component.  The servlet forwarding the request may process the request in some way prior to the forwarding.
Note that the term “redirect” is sometimes used interchangeably with “forward”, intending the same meaning.  However, this should be not be confused with the sendRedirect method found on the servlet response.  A sendRedirect call does not guarantee preservation of the request data when it forwards to a new page, so it does not allow for the same servlet chaining capabilities.
Include:略。

 

ServletContext

Each servlet runs in some environment.  The ServletContext provides information about the environment the servlet is running in.  A servlet can belong to only one ServletContext as determined by the administrator.  Typically, one ServletContext is associated with each Web application deployed in a container.  In the case of distributed containers, one ServletContext is associated with one Web application per virtual machine.

The ServletContext interface can be used by servlets to store and receive information and share information among servlets.  A servlet obtains the ServletContext it is running in by using the getServletContext method.

Some of the basic services provided by the ServletContext interface are

setAttribute: stores informationi in the context

getAttribute: receives information stored in the ServletContext

 每个servlet都运行在某种环境中。ServletContext提供了这个servlet所运行的环境的信息。管理员决定了一个servlet只能属于一个ServletContext。典型的情况是,一个ServletContext和一个发布在容器中的web应用相关联。对于分布式容器的情况,一个ServletContext和每个虚拟机的一个web应用相关联。
ServletContext接口能够被servlets使用来储存和接受信息,而且能够在servlets之间共享信息。一个servlet使用getServletContext方法获得它正在运行的上下文(ServletContext)。

 注:

setAttribute, getAttribute这两个方法在很多接口中都有,如javax.servlet.ServletRequest,或者javax.servlet.http.HttpSession中,它们的功能是一样的,所以取了相同的名称,但是实际上它们是不同的方法,其作用范围是不同的。到底使用的是谁的setAttribute, getAttribute,或者需要使用谁的setAttribute, getAttribute,要根据实际情况来判断。  ---add by FITZWILLIAM

Servlet Session Management

Given the stateless nature of the HTTP protocol, managing repeat interaction and dialog with the same client (such as that required for an ongoing shopping sesson) poses some serious challenges.  There are various means of overcoming these challenges:

  • Hidden fields
  • Dynamic URL rewriting
  • Cookies
  • Server-side session object

The Java Servlet API provides abstractions that directly support some of the session management techniques discussed in the proceeding list.

The core abstraction provided by the servlet API is the HTTP session, which facilitates handling of multuple requests from the same user.

Servlet Deployment and Web Archives

A descriptor based on XML is used in the deployment of servlets on a Web server.  The compiled servlet class, additional supporting Java classes, and the deployment descriptor are packaged together into a Web archive file, also known as a “.war” file.

The deployment descriptor is an XML-Based file that contains specific configuration and deployment information for use by the servlet container.

The following is an example of a vanilla XML deployment descriptor for an HttpServlet.  Additional required fields in the descriptor are filled in during configuration and deployment on the Web server.

<?xml version="1.0" encoding="Shift_JIS"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app id="WebApp1">

    <servlet>

        <servlet-name>LoginServlet</servlet-name>

        <servlet-class> com.fh.co.common.LoginServlet </servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>WebApplicationServlet</servlet-name>

        <url-pattern>/login/</url-pattern>

    </servlet-mapping>

 </web-app>

 

 

 Summary

In general, the role of servlets is that of a coordinator between the boundary objects and the rest of the system.  All the interaction between the boundary object and the composite control class belongs in the new servlet.  How you split the interaction that is shown between the control object and the entity objects is somewhat less clear.  The key factor to remember is that the servlet is primarily a coordinator; and hence, it should only take on lightweight responsibilities, which could include initiating some business logic.  However, actual business logic, computations, interaction with entity objects, and so no would all fall outside of these responsibilities.

总体上看,servlets就像是boundary objects和系统其他部分之间的一个协调者。Boundary boject和构成控制类之间所有的交互都属于这个新的servlet。怎么把控制对象和实体对象之间的交互分开并不是很容易做到。要记住的关键一点是: servlet主要是一个协调者;所以,它应当只具有轻量级的功能,可以包括初始化一些商业逻辑。然而,实际的商业逻辑,计算,和实体对象的交互,等等,不应该包括在其中。

In this scenario, the servlet is an example of what the RUP calls a front component.  A frot component is typically a servlet or a JSP that is primarily responsible for processing user input but is not itself responsible for presentation.  Rather, it acts simply as an entry point to the application and as a coordinator with other components.  Note that the term “TrasferPage” is used to generally represent a user interface.  We might decide to make this a static HTML page or something more dynamic.
在这种情况下,servlet就是RUP中所谓的“前端组件”。前端组件是一个典型的servlet或者JSP,主要负责处理用户输入,但是它自身并不显示。相反的,它仅仅是作为应用程序的入口点,或者是作为与其他组件的协调器。注意,“传送页面”一般是用来表示用户接口的。我们可以把“传送页面”做成一个静态HTML页面,也可以做成更加动态的东西。

Of the two types of servlets discussed, an HttpServlet appears ideally suited to take on external interaction role when you are building a Web-based project.

Servlets have a lightweight architecture.  They are like ordinary Java classes with the exception that specific life cycle methods must exist in the servlet.  Specific HTTP request handler methods are used for HttpServlet.  Two types of servlets, GenericServlet and HttpServlet, are defined in the J2EE.

An XML deployment descriptor is required for deploying a servlet.

 

以上摘自:Developing Enterprise Java Applications With J2EE and UML    Chapter 10 Servlets

by KHAWAR ZAMAN AHMED AND CARY E. UMRYSH

 

 

原创粉丝点击