Replace CGI with Java servlets

Source: Internet
Author: User
Tags html form

Starting from the early stages of the network, it is hoped that their Web servers will not only be able to display static documents, but that the Universal Gateway Interface (CGI) extends the capabilities of the server, but at the expense of additional processing processes. FASTCGI integrates the external CGI processing process more closely with the Web server, and for proprietary server APIs such as NSAPI and ISAPI, they integrate the external process directly into the server as a server plug-in. Now with Java Servlets, they are powerful and can quickly replace your existing CGI programs.

What is Servlets?

Just like the ability of an applet to expand a Web browser, Servlets is the Java component that expands the capabilities of the Web server. For any kind of server-side processing, servlets can be used as a server-side includes or as a CGI program (which can be used as a plug-in in JavaSoft Java WEB server). Servlets can be ported, unlike CGI and proprietary API modules, you can use Java's "write Once, run everywhere" mechanism to configure network applications in your enterprise. The servlets is also very robust, and in the servlet you create a database connection, and the next time you access the servlet, the connection still exists, which is not the same as a CGI program. Servlets is also extensible, so you can use object-oriented programming methods to reduce development time. The servlets can run on any network server that supports Servlets. Currently, the Servlet SDK supports Netscape, Apache and IIS, as well as a large number of third-party network servers, in addition to the Java WEB server that supports JavaSoft.

JSDK Guide

In order to create servlets, you need the Java servlet SDK (JSDK), which can be downloaded from the JavaSoft website. JSDK contains packages such as Javax.servlet,javax.servlet.http, which contain the classes and interfaces you need to create your own servlets. For the Sun.servlet package, it contains the classes required by the network server to run Servlets. (Support for Servlets is usually in the form of a server plug-in.) Once you have JSDK, you simply create subclasses of the Genericservlet class and overload several methods. Genericservlet defines the three main methods you should Overload: Init (), service (), and destroy ().

Init (): Initializes your servlet, such as opening a database connection.

Destroy (): Clears the servlet itself after the applet has finished running.

Service (): invokes the Service () method each time the servlet is called. There are two objects ServletRequest and servletresponse that need to be routed to the servlet for processing customer requests.

To help handle web-based transactions, JSDK has a HttpServlet class in the Javax.servlet.http package. HttpServlet is derived from the Genericservlet, which provides an implementation of the service (), which is used to automatically process get, head and post requests.

The methods in the HttpServlet class have Doget () and Dopost (). A typical CGI servlet only needs to implement the Doget () and Dopost () methods. The parameters for Doget () and Dopost () are HttpServletRequest and HttpServletResponse.

HttpServletRequest is an interface that provides some ways to obtain information from a customer's request. For example, the GetParameter () method returns a keyword/value pair in a customer request (either from the request string or from the posted data).

The HttpServletResponse provides an output stream that allows the servlet to return HTML-formatted output to the customer.

Basic Servlet Code

Instead of your CGI

The following is a basic servlet code that can replace a CGI program. The servlet does the simple thing: List the keyword/value pairs (Key/value) that are collected by the HTML form.

Basiccgiservlet handles the post, and also handles get with the same. So both Dopost () and doget () call Doservice (). Doservice () can be overloaded in subclasses to achieve more specific functionality.

Import javax.servlet.*;

Import javax.servlet.http.*;

Import java.io.*;

Import java.util.*;

public class Basiccgiservlet extends HttpServlet {

Public Basiccgiservlet () {

Super ();

}

public void DoPost (HttpServletRequest req, HttpServletResponse resp)

Throws Servletexception, IOException {

Doservice (req, resp);

}

public void Doget (HttpServletRequest req, HttpServletResponse resp)

Throws Servletexception, IOException {

Doservice (req, resp);

}

protected synchronized void Doservice (HttpServletRequest req,

HttpServletResponse resp) throws Servletexception, IOException {

Get an output stream to write to

Servletoutputstream out = Resp.getoutputstream ();

Set the content type for the response

Resp.setcontenttype (\ \ "text/html\\");

Optionally should also set any special content-encoding

and content length response headers, and return status codes

Write out the response!

Out.println (\ \ "<body

bgcolor=\\\\ "white\\\\" >\\ ");

Out.println (\ \ "\");

Out.println (\ \ "

\\");

For (Enumeration E = Req.getparameternames (); e.hasmoreelements ();) {

String key = (string) e.nextelement ();

Out.println (\ \ "

\\");

}

Out.println (\ \ "

Key Value
\ \ "+ key + \ \" \ \ "+ req.getparameter (key) +

\\"

\\");

}

}

When Req.getparameternames () is called, the Servlet requests the object to read the form data and decodes it into a keyword/value pair (in fact, once the first call to Getparameternames (), or getparametervalues (), or getparameter ()

decoding). Getparameternames () Returns an enumeration of all keywords. GetParameter () returns the value corresponding to a specific keyword. When a servlet request is parsed into a keyword/value pair, the value of each key is saved in a string array so that it can handle situations where a keyword has multiple values. Calls Getparametervalues (), returns a string array, and after calling GetParameter () returns only the first element in the string array.

You may notice that Doservice () is a synchronous method. This is because Servlets is usually run in a multithreaded environment. Because the network server creates only one instance of the Servlet object, the servlet must be able to service requests that occur concurrently. Therefore, Servlets needs to ensure that these requests remain synchronized while accessing the shared resource. These shared resources include instance variables, database connections, file streams, and so on.

Run your servlet

Once the servlet is written and the compilation succeeds, you can put it on the Web server in the servlet alias directory. As with the Cgi-bin alias directory on the server, any files placed in the servlet directory will be executed as Servlets once they are requested as part of the URL. For example, Basiccgiservlet can be called by the following URL: Http://mycompany.com/servlet/BasicCGIServlet. You can either call the URL directly (and pass it to the servlet for a string that requests a keyword/value pair), or it can be called by an action in an HTML form. To learn more about Web servers that support Servlets, see the documentation information in JSDK.

Further usage

Genericservlet and HttpServlet provide a fixed base class for building servlets. By overloading the service () method, you can build on them. For example, you can include support for response caching (see Getlastmodified () in HttpServlet), support for HTTP 1.1 methods, and so on. You can even build an extended template engine. (who really likes to have HTML code built into their programs?) )

Another usage is to extend the JSDK to support other types of form encodings in addition to the standard application/x-www-form-urlencoded MIME types. For example, you can add support for the Multipart/form-data MIME type to handle uploading files over HTTP. Interface Methods Getparameternames (), Getparametervalues (), and so on, are implemented in the Sun.servlet package, so you need to configure JSDK to join these support. There is also a workaround, you can implement the method yourself, but to do so, you need to copy the code or change the semantics of JSDK. The above methods are feasible, but none of them are perfect.

Conclusion

Now you should create your own Java Servlets, which can be used instead of the traditional Perl and C + + CGI programs. Java's object-oriented nature and the "write once, run everywhere" mechanism make Java servlets easy to write. The robustness of the servlet solves the problem of state management, which is a common problem that is commonly encountered when a CGI program is used only once to solve a real problem. Servlets can take advantage of all the features of the Java language, including JDBC and RMI. Since most Web servers are joined to the servlet support, Java will quickly become an alternative language for developing enterprise applications.

Replace CGI with Java servlets

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.