1 SERVLET basic structure
The following code shows the basic structure of a simple servlet. The servlet is a get request, so-called GET request, if you are not familiar with http, you can see it as a user in the browser address bar, click on the link in the web page, browse when you do not specify a form of Method The request sent by the unit. The servlet can also easily handle the POST request. The POST request is to submit the requests issued when specifying a form of Method = "POST". For details, see the discussion of later sessions.
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class somservlet extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
// Use "Request" to read and request information related to information (such as cookies)
// and form data
// Specify the HTTP response status code and response to use "response"
/ / (Such as specifying the content type, setupie)
PrintWriter out = response.getwriter ();
// Use "OUT" to send the answer content to the browser
}
}
If a class wants to be a servlet, it should inherit from httpservlet, sending one or all of the DOGET, DOPOST method based on the data. DOGET and DOPOST methods have two parameters, which are HTTPSERVLETREQUEST types and httpservletResponse types, respectively. HTTPServletRequest provides methods for accessing information about the request, such as form data, HTTP request head, and more. In addition to providing methods for specifying HTTP response status (200, 404, etc.), response head (Content-type, set-cookie, etc.), is the most important thing that it provides a PrintWriter for sending data to the client . For simple servlets, most of its work is to generate a page sent to the client via the PrintLn statement.
Note that doget and dopost throw two exceptions, so you must include them in the statement. Alternatively, you must also import java.io packages (to use PrintWriter and other classes), Javax.Servlet package (to use httpservlets) and javax.servlet.http packages (to use the HttpservletRequest class and HttpservletResponse class).
Finally, the two methods of doget and dopost are called by the Service method, sometimes you may need to directly override the service method, such as the servlet to process both GET and POST requests.
3.2 Simple servlet for outputting plain text
Here is a simple servlet that outputs plain text.
3.2.1 HelloWorld.java
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class helloworld extends httpservlet {
Public void doget (httpservletRequest Request,
HttpservletResponse response) throws servletexception, ioException {
PrintWriter out = response.getwriter ();
Out.println ("Hello World");
}
}
3.2.2 Compilation and installation of servlet
The specific details of the installed servlet on different web servers may be different, please refer to the web server documentation to learn more authoritative instructions. Assume that Java Web Server (JWS) 2.0 is used, the servlet should be installed under the servlets subdirectory of the JWS installation directory. In this article, in order to avoid servlet naming conflicts on different users on the same server, we put all servlets in a separate package Hall; if you and others share a server, and the server does not have a "virtual server" mechanism to avoid This name conflict, then it is best to use a package. After putting the servlet into the bag Hall, helloworld.java is actually placed in the Hall subdirectory of the servlets directory.
Most other servers are similar, except for JWS, the servlets and JSP examples of this article have been tested in BEA WebLogic and IBM WebSphere 3.0. WebSphere has excellent virtual server mechanism, so if it is just to avoid naming conflicts, it is not necessary to use a package.
For beginners who have not used bags, let's introduce two methods of the class inside the compilation package.
One way is to set ClassPath to point to the last level directory (servlet home directory) that actually stores the servlet, and then compile in the directory. For example, if the servlet's home directory is C: \javawebserver\serven, the name of the package (ie, the subdirectory name under the main directory) is Hall, under Windows, the compilation process is as follows:
DOS> SET CLASSPATH = C: \javawebserver\servlets;% classpath%
DOS> CD C: \javawebserver\servlets\hall
DOS> javac yourservlet.java
The method of servlet in the second compilation package is to enter the servlet home directory, perform "Javac Directory ..." or "Javac Directory / YourServlet.java" (UNIX). For example, again assume that the servlet home directory is C: \javawebserver\servlets, the name of the package is Hall, and the compilation process in Windows is as follows:
DOS> CD C: \javawebserver\serven
DOS> javac hall \yourrseervlet.java
Note Under Windows, most JDK 1.1 version of Javac requires the directory name to rendezon (\). JDK1.2 has corrected this problem, but because many web servers still use JDK 1.1, a large number of servlet developers are still using JDK 1.1.
Finally, Javac has a high-level option for supporting the source code and the .class file, you can use Javac's "-d" option to install the .class file to the Directory required by the web server. 3.2.3 Run servlet
Under Java Web Server, servlet should be placed in the servlets subdirectory of the JWS installation directory, and the URL that calls servlet is
HTTP: // Host / servlet / servletname. Attention The name of the subdirectory is servlets (with "S"), and the URL uses "servlet". Since the HelloWorld Servlet is placed in the package Hall, the URL calling it should be
http://host/servlet/hall.helloworld. Methods for installing and calling servlets on other servers may be slightly different.
Most web servers also allow the unique name of the servlet, so the servlet may also be used.
Http: //host/any-path/any-file.html URL call. How to configure how to configure the server type, please refer to the server documentation.
3.3 Servlets Output HTML
Both of the servlets output HTML, rather than outputting plain text as above. There are two additional steps to output HTML to do: telling the browser next to the HTML; modify the PrintLn statement to construct a legitimate HTML page.
The first step is done by setting the Content-Type response header. In general, the response can be set through the setHeader method of HTTPSERVLETRESPONSE, but since the set content type is a very frequent operation, the Servlet API provides a dedicated method setContentType. Note that the setting response should be performed before sending content via the PrintWriter. Here is an example:
Hellowwww.java
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class hellowwww extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
Out.println ("
"Transitional // eN\"> \n "
" \n"
"
"
"
" Body> html>");
}
3.4 Several HTML Tools Functions
Output HTML via the PrintLn statement is not convenient, the fundamental solution is to use JavaServer Pages (JSP). However, for standard servlets, since there are two parts (DOCTYPE and HEAD) in the web page, they can be encapsulated by tool functions.
Although most mainstream browsers ignore the DOCTYPE line, it is strictly that the HTML specification is required to have DOCTYPE lines, which helps the HTML syntax checkter check the HTML document legality according to the declared HTML version. In many web pages, the Head section only contains
The following Java method only accepts the page title as a parameter, then outputs the DOCTYPE, Head, Title section of the page. The list is as follows:
ServletUtilities.java
Package Hall;
Public class servletutilities {
Public static final string docType =
""
Public static string headwithtitle (String Title) {
Return (DOCTYPE "\N"
" \n"
"
}
// The code for other tool functions is introduced later this article
}
Hellowww2.java
Below is the HellowW2 obtained after the use of servletUtilities after rewriting the HellowWW class:
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class hellowwww2 extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
Out.println (ServletUtilities.Headwithtitle ("Hello WWW")
"
"
" Body> html>");
}
}