At the heart of Java servlet technology is the creation of objects on the server that respond to user requests, and the objects created are accustomed to being called a Servlet object.
To write a class that creates a Servlet object is to write a subclass of a special class that is the HttpServlet class in the Javax.servlet.http package. The HttpServlet class implements the Servlet interface and implements the method of responding to the user. Subclasses of the Httpserlet class are accustomed to being called a servlet class, such that the object created by such a class is accustomed to being called a Servlet object.
1 Deploying Servlets
Using the Tomcat server after Tomcat 5.x requires the servlet class to have a package name. However, like beans, the compiled bytecode needs to be copied into the corresponding directory (\web-inf\classes directory) with the package.
*************************
In order to compile the servlet source files, you need HttpServlet, httpservletrequest, and so on. These class files are not included in the JDK, and you need to copy the Servlet-api.jar file from the Common/lib directory in the Tomcat server to the \jre\lib\ext subdirectory of the JDK installation directory.
A servlet instance:
Package Star.moon;
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class Hellobeijing extends httpservlet{
public void init (ServletConfig config) throws servletexception{
Super.init (config);
}
public void Service (HttpServletRequest request,httpservletresponse response) throws ioexception{
Response.setcontenttype ("text/html; charset=gb2312 ");
PrintWriter Out=response.getwriter ();
Out.println ("Out.println ("Out.println ("</body>}
}
In order for the Tomcat server to create an object with a servlet bytecode file, a deployment file must be written for the Tomcat server, which is an XML file, the name is the Web. Web-inf directory, which is managed by the Tomcat server. The application that uses the XML file (the Tomcat server) has a built-in parser that resolves the data in the XML tag and can find a Web. xml file in the root directory of the Tomcat server's WebApps directory, referencing it to write its own web. xml file.
Example Web. xml:
<?xml version= "1.0" encoding= "Iso-8859-1"?>
<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>star.moon.HelloBeijing</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/lookhello</url-pattern>
</servlet-mapping>
</web-app>
An XML file should have an XML declaration as the first line of the file, with no whitespace, other processing instructions, or annotations in front of it. The XML declaration begins with the "<?xml" identity and ends with the "?>" identity. Note that there is no space between the < and the XML and the >. If the value of the Encoding property is not explicitly specified in the XML declaration, the default value for this property is UTF-8 encoding. You can also set the value of the encoding property to Iso-8859-1 If you are writing an XML file that is only intended to use ASCII characters. The XML file must be saved with ANSI encoding, and the XML parser in the Tomcat server recognizes the markup in the XML file and correctly parses the contents of the tag based on the value of the Encoding property. If the value of the Encoding property is Utf-8,xml, the file must be saved according to UTF-8 encoding.
The specific content of the markup in the Web. xml file and its role:
Root tag: The XML file must have a root tag, and the root tag of the Web. xml file is <web-app>.
<servlet> tags and sub-tags. <servlet> needs to have two sub-tags <servlet-name> and <servlet-class>. The content of the <servlet-name> tag is the name of the Servlet object created by the Tomcat server. The contents of the <servlet-class> tag specify which class the Tomcat server uses to create the Servlet object.
<servlet-mapping> tags and sub-tags. Both the tag and the <servlet> tag are the direct child tags of the root tag. The <servlet-mapping> tag needs to have two sub-tags:<servlet-name> and <url-pattern>, where <servlet-name> The tagged content is the name of the Servlet object created by the Tomcat server. The <url-pattern> tag is used to specify what mode the user requests for the Servlet object. such as <URL-PATTERN>/LOOKHELLO</URL-PATTERN>, the user must request the servlet through the current Web service directory. The user wants to request that the server run the Servlet object Hello for its service, then the address bar in the browser should be entered: Http://127.0.0.1:8000/ch7/lookhello
The Web. xml file for the directory is responsible for managing the servlet objects in that directory, and when the Web service catalog needs to provide more Servlet objects, simply add <servlet> and < in the. xml file Servlet-mapping> the child tag.
The servlet class can use the Getservletname () method to return the name of the servlet given by the <servlet-name> tag in the configuration file.
How the 2servlet works
The life cycle of the servlet
A Servlet object is an instance of the subclass of the HttpServlet class in the Javax.servlet package, and the server creates and finishes its initialization work. When multiple clients request a servlet, the server initiates a thread for each client instead of a process when the server requests a servlet for each customer.
The life cycle of a Servlet object consists mainly of the following three processes:
Initializes the Servlet object. The first time a Servlet object is requested to load, the server initializes the Servlet object, which creates a Servlet object that calls the Init method to do the necessary initialization work.
The spawned Servlet object responds to the client's request in a call to the service method.
When the server shuts down, call the Destroy method to destroy the Servlet object.
The Init method is called only once, which is called when the servlet is requested to load for the first time, and when a subsequent client requests the Servlet service, the Web service enables a new thread for each client, in which the Servlet object invokes the service method in response to the client's request.
Init method
The method is a method in the HttpServlet class that can be overridden in a servlet class. Declaration format for the Init method:
public void init (ServletConfig config) throws Servletexception
When this method executes, the server passes an object of type ServletConfig to the init () method, which is stored in the Servlet object until the servlet is destroyed. The ServletConfig object is responsible for passing service provisioning information to the servlet, and servletexception occurs if delivery fails.
Service method
This method is a method in the HttpServlet class that can either inherit the method directly from the Servlet class or override the method. Declarative format for service methods:
public void Service (HttpServletRequest request,httpservletresponse response) throw servletexception,ioexception
When the Servlet object is successfully created and initialized, the object invokes the service method to process the user's request and return the response. The server passes two parameters to the method, an object of type HttpServletRequest that encapsulates the user's request information, and another parameter object that is an object of type HttpServletResponse that responds to the user's request. Each request from each client causes the service method to be called to execute, the calling process runs in different threads, and the local variables in the service methods of different threads do not interfere with each other.
Destroy method
This method is a method in the HttpServlet class. A servlet class can inherit this method directly, and generally does not need to be rewritten. Declaration format for the destroy method: Public Destroy ()
The Destroy () method is executed when the server terminates the service.
3 calling a servlet from a JSP page
A JSP page under the Web Services directory can request a servlet under the Web service directory through a form or hyperlink.
Submitting data through a table one-way servlet * * *
Note If the servlet request format is/name, then the JSP page requests the servlet, which must be written as name, not written as/name, or it will become a servlet in the request root service directory.
The servlet file is the name of <url-pattern>/name</url-pattern> * * *
Example: <form action= "servlet file" method=post>....</form>
Access servlet*** through hyperlinks
In the JSP page, you can click a hyperlink to access the Servlet object. Example: <a href= "servlet file" >...</A>
The Servlet class is a subclass of HttpServlet, and you can declare some member variables when you write subclasses. Then the member variables of the servlet class are shared by all users requesting the servlet.
Access servlert*** through the Forward action table
<jsp:forward page= "The page to turn to or the servlet"/>
For example
<jsp:forward page= "/dbservlet"/>
4doGet and Dopost methods
In addition to the INIT, service, and Destroy methods, the HttpServlet class has two important methods, Doget and Dopost, to handle the client's request and respond.
Whenever the server receives a servlet request, a new thread is generated, in which the Servlet object invokes the service method to check the HTTP request type (GET, post, etc.) and, in the service method, according to the user's request, The Doget and Dopost methods are called accordingly.
5sendRedirect method
The void Sendredirect (java.lang.String location) method is a method in the HttpServletResponse class. When a user requests a servlet, the servlet can use this method to redirect the user to a JSP page or to another servlet after the data is processed. The Redirect method directs the user from the current page or servlet to another JSP page or servlet, but cannot forward the user's request to the current page or another servlet to the targeted JSP page or servlet. That is, the redirected target page or Servlet object cannot use the request to get user-submitted data.
6RequestDispatcher objects
The RequestDispatcher object can forward a user's request to the current JSP page or servlet to another JSP page or servlet. It also passes the user's request and response to the current JSP page or servlet to the forwarded JSP page or servlet. The target page or Servlet object that is currently being forwarded can use request to get the data submitted by the user.
There are two steps to implementing a forwarding:
Get RequestDispatcher Object
The current JSP or servlet requested by the user allows the HttpServletRequest object request to be called
Public RequestDispatcher Getrequestdispatcher (java.lang.String path)
Returns a RequestDispatcher object where the parameter path is the address of the JSP or servlet to be forwarded.
Forward
Get the RequestDispatcher object in step 1 call the following method to forward the user's request to the current JSP page or servlet to the JSP page or servlet specified by the RequestDispatcher object.
void forward (ServletRequest request,servletresponse response) throws Servletexcpetion,java.io.ioexception
Methods that use forward must throw servletexception. (Throws Servletexception)
7 getting a user's session
The HttpServletRequest object request invokes the GetSession method to get the user's session object:
HttpSession session=request.getsession (TRUE);
The session object that a user gets in a different servlet object is exactly the same. But the session objects of different users are not the same.
Cases:
Package Shili;
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class Showletter extends HttpServlet {
@Override public void init (ServletConfig config) throws servletexception{
Super.init (config);
}
@Override public void Service (HttpServletRequest request,httpservletresponse response) throws ioexception{
Response.setcontenttype ("text/html;charset=gb2312");
PrintWriter Out=response.getwriter ();
Out.println ("Out.print ("<br> lowercase Greek alphabet:");
for (Char c= ' a '; c<= ' w '; C + +) {
Out.print ("+c");
}
Out.print ("<br> uppercase Greek Alphabet:");
for (char c= ' A '; c<= ' W '; C + +) {
Out.print ("+c");
}
Out.println ("</body>}
}
**************************************
How to specify app event listeners
Applying an event listener is a class that is notified when a Servlet environment or Session object is established or modified. These are the new content in version 2.3 of the servlet specification. This is simply a description of the use of the Web. XML used to register a listener with the application.
Registering a listener involves placing a listener element within the Web-app element of Web. Xml. Within the listener element, the Listener-class element lists the full qualified class name of the listener, as follows:
<listener>
<listener-class>package. Listenerclass</listener-class>
</listener>
Although the structure of the listener element is simple, please do not forget that the order of the child elements within the Web-app element must be given correctly.
*******************
The listener element is positioned before all servlet elements and after all filter-mapping elements. Also, because the app Lifetime listener is new in version 2.3 of the Serlvet specification, you must use the 2.3 version of the Web. XML DTD instead of the 2.2 version.
Servlet version and JSP version view:
Locate Jsp-api.jar Servlet-api.jar unzip the two files and open the Mainmeft.mf file under Meta-inf with Notepad. The file records their version number.
*******************
For example, the program listing 5-20 shows a simple listener named Contextreporter that displays a message on standard output as long as the Web app's Servlet-context is established (such as loading a web app) or eliminated (such as a server shutdown). Listing 5-21 shows part of the Web. xml file required for this listener registration.
Program Listing 5-20 Contextreporterjava
Package moreservlets;
Import javax.servlet.*;
Import java.util.*;
public class Contextreporter implements Servletcontextlistener {
public void contextinitialized (Servletcontextevent event) {
The Getservletcontext () method of the Servletcontextevent instance returns the Sevletcontext object
ServletContext ServletContext = Event.getservletcontext ();
System.out.println ("Context created on" +
New Date () + ".");
}
public void contextdestroyed (Servletcontextevent event) {
System.out.println ("Context destroyed on" +
New Date () + ".");
}
}
Program Manifest 5-21 Web. XML (declares an excerpt of a listener)
<?xml version= "1.0" encoding= "Iso-8859-1"?>
<! 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>
<!--...-->
<filter-mapping> ... </filter-mapping>
<listener>
<listener-class>package. Listenerclass</listener-class>
</listener>
<servlet> ... </servlet>
<!--...-->
</web-app>
Servletcontextlistener Monitor ServletContext. The contextinitialized (Servletcontextevent SCE) method is fired when the ServletContext is created, and when ServletContext is destroyed, the contextdestroyed is fired ( Servletcontextevent sce) method.
6Java servlet Basics