3. The first Servlet

Source: Internet
Author: User

3.1 basic servlet Structure

The followingCodeShows the basic structure of a simple servlet. The servlet processes GET requests. If you are not familiar with HTTP, it can be viewed as a request sent by the browser when a user enters a URL in the browser address bar, clicks a link on the web page, and submits a form without a specified method. Servlet can also easily process post requests. A POST request is a request sent when a form with the specified method = "Post" is submitted. For more information, see the following sections.
Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;

Public class someservlet extends httpservlet {
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {

// Use "request" To Read Request-related information (such as cookies)
// And form data

// Use "response" to specify the HTTP response status code and Response Header
// (For example, specify the content type and set the cookie)

Printwriter out = response. getwriter ();
// Use "out" to send the response content to the browser
}
}

If a class is to be a servlet, it should inherit from httpservlet, and be sent through get or post based on the data, overwriting one or all of the doget and dopost methods. The doget and dopost methods both have two parameters: httpservletrequest and httpservletresponse. Httpservletrequest provides methods to access request information, such as form data and HTTP request headers. Httpservletresponse provides methods to specify the HTTP response status (200,404, etc.), Response Header (Content-Type, set-Cookie, etc, most importantly, it provides a printwriter for sending data to the client. For a simple servlet, most of its work is to generate a page sent to the client through the println statement.

Note that doget and dopost throw two exceptions, so you must include them in the Declaration. In addition, you must import Java. io packages (printwriter and other classes are used), javax. servlet package (use httpservlet and other classes) and javax. servlet. HTTP packet (the httpservletrequest class and httpservletresponse class are required ).

Finally, the doget and dopost methods are called by the service method. Sometimes you may need to directly overwrite the service method. For example, when the servlet needs to process get and post requests.

3.2 simple servlet for outputting plain text

Below 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 servlet compilation and Installation

The detailed details of servlet installation on different Web servers may vary. Refer to the Web server documentation for more authoritative instructions. Assuming 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, to avoid conflicts between servlet names of different users on the same server, we put all servlets in an independent package Hall. If you share a server with others, in addition, this server does not have a "virtual server" mechanism to avoid such name conflicts, so it is best to use the package. After the servlet is put into the hall package, helloworld. Java is actually put under the hall subdirectory of the servlets directory.

The configuration methods for most other servers are similar. In addition to JWS, the servlet and jsp examples in this article have been tested under BEA Weblogic and IBM WebSphere 3.0. WebSphere has an excellent virtual server mechanism. Therefore, if you only want to avoid naming conflicts, you do not have to use packages.

For beginners who have not used the package, we will introduce two methods for compiling the class in the package.

One way is to set classpath so that it points to the upper-level directory (servlet main directory) that actually stores the servlet, and then compile the directory in the normal way. For example, if the main directory of the servlet is c: \ javawebserver \ servlets and the package name (that is, the subdirectory name under the main directory) is Hall, the compilation process in Windows is as follows:
DOS> set classpath = c: \ javawebserver \ servlets; % classpath %
DOS> Cd c: \ javawebserver \ servlets \ Hall
DOS> javac yourservlet. Java

The second method to compile the servlet in the package is to enter the servlet home directory and run "javac directory \ yourservlet. Java" (Windows) or "javac directory/yourservlet. Java" (UNIX ). For example, assume that the main directory of the servlet is c: \ javawebserver \ servlets and the package name is Hall. The compilation process in Windows is as follows:
DOS> Cd c: \ javawebserver \ servlets
DOS> javac Hall \ yourservlet. Java

Note that in windows, most JDK 1.1 javac requires that the directory name be followed by a backslash (\). JDK 1.1 has been corrected. However, many web servers still use JDK 1.1, so many servlet developers are still using JDK.

Finally, javac has an advanced option to supportSource codeSeparate it from the. Class file, that is, you can use the "-d" option of javac to install the. Class file to the directory required by the Web server.

3.2.3 run Servlet

In Java Web server, the servlet should be placed in the servlets subdirectory of the JWS installation directory, and the URL of the servlet to be called is http: // host/servlet/servletname. Note that the sub-directory name is servlets (with "S"), and the URL uses "servlet ". Because the helloworld servlet is put into the hall package, the URL to call it should be http: // host/servlet/Hall. helloworld. On other servers, the methods for installing and calling servlet may be slightly different.

Most Web servers also allow the definition of servlet aliases, so servlet may also be called using a URL in the form of http: // host/any-path/any-file.html. For details about how to configure the server type, refer to the server documentation for details.

3.3 HTML servlet output

Most servlets output HTML, instead of plain text. There are two additional steps to output HTML: Tell the browser that HTML is sent next; modify the println statement to construct a valid HTML page.

Step 1: Set the Content-Type response header. Generally, the response header can be set through the setheader method of httpservletresponse. However, because the content type is set frequently, Servlet API provides a dedicated method setcontenttype. Note that you should set the Response Header before sending content through printwriter. The following is an example:

Hellowww. Java
Package Hall;

Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;

Public class hellowww extends httpservlet {
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();
Out. println ("<! Doctype HTML public \ "-// W3C // dtd html 4.0" +
"Transitional // en \"> \ n "+
"<HTML> \ n" +
"<Head> <title> Hello WWW </title> "<Body> \ n" +
"<H1> Hello WWW "</Body> }
}

3.4 HTML tool Functions

It is not convenient to output HTML using println statements. The fundamental solution is to use JavaServer Pages (JSP ). However, for standard Servlets, because there are two parts of the web page (doctype and head) are generally not changed, you can use tool functions to encapsulate the code that generates the content.

Although most mainstream browsers ignore the doctype line, but strictly speaking, the HTML specification requires the doctype line, which helps the HTML syntax Checker to check the validity of the HTML document according to the declared html version. In many web pages, the head part only contains <title>. Although many experienced writers will include many meta tags and style declarations in the head, Here we only consider the simplest case.

The following Java method only accepts the page title as a parameter, and then outputs the doctype, Head, and title sections of the page. The list is as follows:

Servletutilities. Java
Package Hall;

Public class servletutilities {
Public static final string doctype =
"<! Doctype HTML public \ "-// W3C // dtd html 4.0 transitional // en \"> ";

Public static string headwithtitle (String title ){
Return (doctype + "\ n" +
"<HTML> \ n" +
"<Head> <title>" + title + "</title> }

// Code of other tool functions will be introduced later in this article
}

Hellowww2.java

The following is the hellowww2 obtained by rewriting the hellowww class after applying servletutilities:
Package Hall;

Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;

Public class hellowww2 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> \ n" +
"<H1> Hello WWW "</Body> }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.