JSP servlet Basics Primer Learning: The first servlet

Source: Internet
Author: User
Tags functions header html page http request include require string java web
Js|servlet 3.1 servlet Basic structure

The following code shows the basic structure of a simple servlet. The servlet handles the GET request, the so-called getting request, and if you are unfamiliar with HTTP, you can think of it as a request from the browser when the user enters a URL in the browser's address bar, clicks a link in the Web page, and submits a form that does not specify method. A servlet can also easily handle post requests. A POST request is a request that is made when a form that specifies the method= "POST" is submitted, as discussed in a later section.

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 and request information (such as cookies)
and form data

Use "response" to specify HTTP answer status codes and answer headers
(such as specifying content type, setting cookies)

PrintWriter out = Response.getwriter ();
Use "Out" to send the answer to the browser
}
}




If a class is to be a servlet, it should inherit from HttpServlet, overwriting one or all of the Doget, Dopost methods, depending on whether the data is sent via GET or post. The Doget and Dopost methods all have two parameters, HttpServletRequest type and httpservletresponse type respectively. HttpServletRequest provides methods to access information about the request, such as form data, HTTP request headers, and so on. HttpServletResponse In addition to providing a way to specify HTTP response status (200,404), answer headers (Content-type,set-cookie, and so on), Most importantly, it provides a printwriter for sending data to the client. For a simple servlet, most of its work is to generate pages 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 also import java.io packages (to be used for classes such as PrintWriter), Javax.servlet packages (to use classes such as HttpServlet) and javax.servlet.http packages (HttpServletRequest and HttpServletResponse classes are used).

Finally, Doget and Dopost are called by the service method, and sometimes you may need to cover the service method directly, such as when the servlet handles get and post two kinds of requests.

   3.2 Simple servlet for output plain text

The following 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");
}
}




Compilation and installation of the 3.2.2 Servlet

The specifics of installing a servlet on a different Web server may vary, please refer to the Web Server documentation for more authoritative instructions. Assuming that you are using Java Web Server (JWS) 2.0, the servlet should be installed in the Servlets subdirectory of the JWS installation directory. In this article, to avoid the servlet naming conflicts of different users on the same server, we put all the servlet into a separate package hall, and if you share a server with other people and the server does not have a "virtual server" mechanism to avoid this naming conflict, it is best to use the package as well. After putting the servlet in the package hall, Helloworld.java is actually placed in the Hall subdirectory of the Servlets directory.

Most other servers have similar configuration methods, except for JWs, the servlet and JSP samples of this article have been tested under BEA WebLogic and IBM WebSphere 3.0. WebSphere has excellent virtual server mechanisms, so it is not necessary to use packages to avoid naming conflicts.

For beginners who have not used a package, here are two ways to compile the class within the package.

One way is to set the classpath to point to the level of the directory (the servlet home directory) where the servlet actually resides, and then compile it in the directory as normal. For example, if the servlet's home directory is C:\JavaWebServer\servlets, and the package name (that is, the subdirectory name under the home 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 second way to compile the servlet in the package is to go into the servlet home directory and execute "Javac Directory\yourservlet.java" (Windows) or "Javac directory/ Yourservlet.java "(Unix). For example, again assume that the servlet home directory is C:\JavaWebServer\servlets, and that the package's name is Hall, and that the compilation process in Windows is as follows:
dos> CD C:\JavaWebServer\servlets
dos> Javac Hall\yourservlet.java



Note that most JDK 1.1 versions of Javac require a backslash (\) behind the directory name under Windows. JDK1.2 has corrected the problem, however, since many Web servers still use JDK 1.1, a large number of servlet developers are still using JDK 1.1.

Finally, Javac also has an advanced option to support the separate placement of the source code and the. class file, which means you can install the. class file to the directory requested by the Web server with the Javac "-d" option.

3.2.3 Run servlet

Under Java Web Server, the servlet should be placed in the Servlets subdirectory of the JWS installation directory, and the URL of the calling servlet is Http://host/servlet/ServletName. Note that the subdirectory's name is Servlets (with "s"), and the URL uses a "servlet". Because the HelloWorld servlet is placed in the package hall, the URL to call it should be http://host/servlet/hall.HelloWorld. On other servers, the method of installing and invoking the servlet may be slightly different.

Most Web servers also allow you to define the alias of a servlet, so the servlet may also be invoked in the form of http://host/any-path/any-file.html URLs. Depending on the server type, refer to the server documentation for details about how to configure it.

   3.3 servlet for output HTML

Most servlet output HTML instead of plain text as in the example above. There are two additional steps to output HTML: Tell the browser to send the HTML next, and modify the PRINTLN statement to construct a legitimate HTML page.

The first step is done by setting the Content-type (content Type) answer header. Generally, the answer header can be set through the HttpServletResponse SetHeader method, but because setting the content type is a very frequent operation, the Servlet API provides a dedicated method setContentType. Note Setting up the answer header should be done before the content is sent through PrintWriter. Here 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> </HEAD> \ n" +
"<BODY> \ n" +
""</BODY> </HTML>");
}
}




   3.4 Several HTML tool functions

Exporting HTML through the PRINTLN statement is not convenient, and the fundamental solution is to use JavaServer Pages (JSP). However, for a standard servlet, there are two parts of the Web page (DOCTYPE and head) that generally do not change, so you can use a tool function to encapsulate the code that generates the content.

While most mainstream browsers ignore DOCTYPE lines, strictly speaking, HTML specifications require DOCTYPE lines, which help the HTML grammar checker check the legality of HTML documents based on the declared HTML version. In many web pages, the Head section contains only <TITLE>. Although many experienced writers include many meta tags and style declarations in the head, only the simplest scenarios are considered here.

The following Java method takes only the page title as a parameter and then outputs the DOCTYPE, head, and Title section of the page. The list is as follows:

Servletutilities.java
Package Hall;

public class Servletutilities {
public static final String DOCTYPE =
"Yes! 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> </HEAD> \ n");
}

The code for other tool functions is described later in this article
}




Hellowww2.java

The following is the HelloWWW2 that overrides the Hellowww class after applying the 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" +
""</BODY> </HTML>");
}
}

Related Article

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.