Servlet and JSP Tutorial (1) -Servlet and JSP Overview
First, Servlet and JSP Overview
1.1 Java servlet and its characteristics
Servlet is Java technology to answer CGI programming. The servlet program runs in the server side, dynamically generates a web page. Compared to traditional CGIs and many other similar CGI technologies, Java servlets have higher efficiency, easier to use, more powerful, better portability, saving more investment (more important, servlet programmers The income is higher than the Perl programmer :-):
Efficient.
In the traditional CGI, each request will start a new process. If the CGI program itself has a short period of execution, the overhead required to start the process is likely to exceed the actual execution time. In the servlet, each request is processed by a lightweight Java thread (not the heavyweight operating system process).
In the traditional CGI, if there is a request to the same CGI program, the code of the CGI program is repeated in memory in memory; for servlet, the request is N thread, only one servlet Class code. In terms of performance optimization, servlets have more choices than CGI, such as buffering previous calculations, maintaining the activity of the database connection, and so on.
Convenience.
Servlet provides a large number of utility routines, such as automatically parsing and decoding HTML form data, reading, and setting up HTTP headers, processing cookies, tracking session status, etc.
Powerful.
In servlet, many tasks that use traditional CGI programs are easy to complete. For example, servlets can interact directly with the web server, while ordinary CGI programs cannot. Servlets are also capable of sharing data between individual programs, making it easy to implement the functions such as database connection pools.
It is good to be portable.
Servlet is written in Java, servlet API has a perfect standard. Therefore, servlet written for I-Planet Enterprise Server can be ported to Apache, Microsoft IIS or WebStar without any substantial changes. Almost all mainstream servers support the servlet directly or through the plugin.
Save investment.
Not only is there many cheap or even free web servers available for personal or small-scale websites, but also for existing servers, if it doesn't support servlet, add this part of the function is often free (or only very small investment).
1.2 JSP and its characteristics
JavaServer Pages (JSP) is a technique that implements normal static HTML and dynamic HTML mixed encoding. See "JSP Technical Introduction" instructions for JSP basic concepts.
Many of the pages generated by the CGI program are still still static HTML, and the dynamic content appears only in several parts of the page. However, most CGI technology, including servlets and variants, always generates the entire page via the program. JSP makes we can create these two parts, respectively. For example, the following is a simple JSP page:
Welcome,
<% out.println (utils.getusernamefromcookie (request));%>
To set an account information, please click
The rest of the page. .
Body> html>
Below is a simple comparison of JSP and other similar or related technologies:
JSP and Active Server Pages (ASP)
Microsoft's ASP is a similar technology similar to JSP. JSP and ASP have the advantages of two aspects. First, the dynamic part is written in Java, not the VB Script or other Microsoft language, not only more powerful and easier to use. Second, JSP applications can be ported to other operating systems and non-Microsoft web servers.
JSP and pure servlet
JSP does not increase any functionality that cannot be implemented in nature. However, writing static HTML in JSP is more convenient, do not have to use the PrintLn statement to output each line HTML code. More importantly, with the separation of the content and appearance, the task of different nature in the page can be conveniently separated: For example, the page design expert is HTML design, and the space for the servlet programmer is inserted into the dynamic content.
JSP and server-side include (Server-Side Include, SSI)
SSI is a technique that is widely supported in a static HTML introduces external code. JSP support is more perfect in this regard because it can generate dynamic content with servlet instead of independent programs. In addition, SSI is actually only used in simple containers, rather than facing "real" programs that can handle form data and access databases.
JSP and JavaScript compared to JavaScript
JavaScript can dynamically generate HTML on the client. Although JavaScript is useful, it can only handle dynamic information based on the client environment. In addition to cookies, HTTP status and form submission data are unavailable for JavaScript. In addition, JavaScript cannot access server-end resources, such as databases, directory information, and more.
Servlet and JSP Tutorial (2) - Setting development, operating environment
Second, set development, operating environment
2.1 Install Servlet and JSP Development Tools
To learn Servlet and JSP development, you must first prepare a development environment that meets Java Servlet 2.2 and JavaServer Pages1.0 / 1.1 specification. Sun offers free JavaServer Web Development Kit (JSWDK), you can download from http://java.sun.com/products/servlet/.
After installing JSWDK, you have to tell Javac, where to find the Servlet and JSP classes when compiling files. The JSWDK Installation Guide has a detailed description of this, but mainly to join servlet.jar and jsp.jar to ClassPath. ClassPath is an environment variable indicating how Java is looking for class files. If you do not set ClassPath, Java is looking for classes in the current directory and standard system library; if you settle ClassPath, don't forget to include the current directory (ie, in classpath ". "). In addition, in order to avoid name conflicts to install and other developers to servlets on the same web server, it is best to put their own servlet into the package. At this point, there is a lot of convenience to ClassPath in the top-level directory in the package hierarchy. Please refer to the details below.
2.2 Installing the web server supporting servlet
In addition to the development tool, you have to install a web server that supports Java Servlet, or installs a servlet package on an existing web server. If you are using the latest web server or application server, it is likely that it already has all necessary software. Check the web server document, or visit http://java.sun.com/products/servlet/industry.html View the list of server software that supports servlet.
Although the final run Servlet is often a business-grade server, it is enough to develop and test with a free system that can run on the desktop. Below is a few of the current most popular products.
Apache Tomcat.
Tomcat is an official reference implementation of servlet 2.2 and JSP 1.1 specification. Tomcat can be used separately as a small servlet, a JSP test server, or can also be integrated into the Apache Web server. Until 2000, Tomcat is only the only server that supports Servlet 2.2 and JSP 1.1 specification, but many other servers have announced their support.
Tomcat and Apache are free. However, fast, stable Apache servers have a bit troublesome, Tomcat has the same shortcomings. Compared with other business-grade Servlet Engines, the workload of Tomcat is obviously more than one. For details, see http://jakarta.apache.org/.
JavaServer Web Development Kit (JSWDK).
JSWDK is an official reference implementation of servlet 2.1 and JSP 1.0. The JSWDK can be separate as a small servlet, a JSP test server before deploying Servlet and JSP applications to officially running their servers. JSWDK is also free and has good stability, but its installation and configuration is also more complicated. For details, see http://java.sun.com/products/servlet/download.html.
Allaire Jrun.
JRUN is a servlet and JSP engine that can be integrated into Netscape Enterprise or FastTrack Server, IIS, Microsoft Personal Web Server, low version of Apache, O`elly WebSite or Starnine Web Star. Up to 5 concurrently connected restrictions are free, there is no restriction in commercial versions, and the functions such as the remote management console are added. See http://www.allaire.com/products/jrun/ for details.
New Atlanta's servletexec
ServletExec is a quick servlet and JSP engine that integrates to most popular web servers, support platforms include Solaris, Windows, MacOS, HP-UX, and Linux. ServleTexec can be downloaded and used for free, but many advanced features and management tools can only be used after purchasing licenses. New Atlanta also offers a free servlet debugger that works in many popular Java IDEs. See http://newatlanta.com/ for details. Gefion's LiteWeb Server (LWS)
LWS is a free small web server that supports Servlet 2.2 and JSP 1.1. Gefion also has a free Wai Chiolrunner plugin that uses the plugin to add Servlet 2.2 and JSP 1.1 support for Netscape FastTrack and Enterprise Server. See http://www.gefionsoftware.com/.
Sun's Java Web Server.
The server is written in Java, and is one of the web servers that first provides a complete support for Servlet 2.1 and JSP 1.0 specification. Although Sun has now turned to Netscape / I-Planet Server, Java Web Server is no longer developed, but it is still a popular servlet, JSP learning platform. To get a free trial version, please visit http://www.sun.com/software/jwebserver/try/.
Servlet and JSP Tutorial (3)
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 calling 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, then 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 definition of the alias of the servlet, so servlets may also call URLs in http: //host/any-path/any-file.html. 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>");
}
}
Servlet with JSP Tutorial (4)
Fourth, deal with form data
4.1 Form Data Overview
If you have used the web search engine, or browse online bookstores, stock prices, ticket information, may pay attention to some weird URLs, such as "http: // host / path? User = marty hall & origin = bwi & dest = LAX" . This URL is located behind the question mark, ie "User = Marty Hall & Origin = BWI & DEST = LAX" is form data, which is the most common method of sending web page data to the server program. For the GET request, the form data is attached to the question mark of the URL (as shown in the above example); for the POST request, form data is sent to the server with a separate row. Previously, from this form of data extraction, the required form variables were one of the troublesome things in CGI programming. First, the data extraction method of the GET request and the POST request is different: for the GET request, it is usually extracted by the Query_String environment variable; for the POST request, the data is generally extracted by standard input. Second, the programmer must be responsible for truncating the variable name-variable pair at the "&" symbol, then separating the variable name (left side) and variable value (equal sign right). Third, the variable value must be performed on the URL anti-encoding operation. Because the letters and numbers are sent in the original form, the spaces are converted into a plus sign, and the other characters are converted into "% xx" form, where XX is the character ASCII represented by hexadecimal (or ISO Latin " 1) Code value. For example, if the domain value named "USERS" in the HTML form is "~ Hall, ~ Gates, and ~ McNEAL", the data sent to the server is "UserS =% 7EHALL% 2C % 7EGATES% 2C AND % 7emcnealy) ". Finally, the fourth causes the fourth result of the analysis of the parsing form data is that the variable value may be omitted (such as "param1 = var_ param2 = & param3 = val3"), and it is possible that a variable has more than one value, that is, the same variable Among the above (such as "param1 = val1 & param2 = VAL2 & param1 = val3).
One of the benefits of Java Servlet is that all of the above parsed operations can be done automatically. Just simply call the getParameter method of HTTPSERVLETREQUEST, providing the name of the form variable in the call parameter (case sensitive), and the GET request and the POST request are identical.
The return value of the getParameter method is a string, which is the corresponding value specified in the parameter, the corresponding value is obtained by the countercodes (can be used directly). If the specified form variable exists, but no value, getParameter returns an empty string; returns NULL if the specified form variable does not exist. If the form variable may correspond to multiple values, you can use GetParameterValues to replace GetParameter. GetParameterValues can return a string array.
Finally, although the servlet is likely to use the form variables of those known words in practical applications, it is often very useful in debugging environments, which can be easily implemented using the GetParameRnames method. . getParameRNames returns an enumeration, each of which can be converted to a string that calls getParameter. 4.2 Example: Read three table single variables
Here is a simple example that reads three form variable param1, param2, and param3, and lists them in the form of an HTML list. Note that although the response type (including the content type, status, and other HTTP header information) must be specified before sending the answer content, but the servlet does not require any requirements.
In addition, we can easily make the servlet to process the GET request, and can handle the POST request, which only needs to call the Doget method in the dopost method, or override the service method (Service method call doget, dopost, dohead, etc. ). This is a standard method in actual programming because it only needs little additional work, but it can increase the flexibility of client encoding.
If you are used to using traditional CGI methods, read POST data through standard input, then there are similar methods in the servlet, namely GetReader or GetInputStream upon httpservletRequest, but this method is too troublesome for ordinary form variables. However, if you want to upload files, or POST data is sent through a dedicated client instead of an HTML form, then this method is used.
Note When you read the POST data in a second method, you cannot read these data again with GetParameter.
Threeparams.java
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Import java.util. *;
Public class threeparams extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
String Title = "Read three request parameters";
Out.println (servletutilities.headwithtitle (title)
"
\n""
"
Request.GetParameter ("param1") "\n"
Request.getParameter ("param2") "\N" "
Request.GetParameter ("param3") "\n"
" Ul> \n"
" Body> html>");
}
Public void dopost (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
DOGET (Request, Response);
}
}
4.3 Example: Output All Form Data
The following example looks for all the variable names sent by the form, and put them in the table, no value or variables with multiple values are highlighted.
First, the program gets all the variable names through the GetParameterNames method of HTTPSERVLETREQUEST, and getParameterNames returns an enumeration. Next, the program uses a loop to traverse this Enumeration, determine when to end the loop via HasMELEMENTS, use the nextElement to get the enumerations in the enumeration. Since NexTelement returns an Object, the program converts it into a string and uses this string to call GetParameterValues.
getParameterValues returns a string array if this array has only one element and is equal to the empty string, indicating that this form variable does not value, and servlet outputs "no value" in a slope body; if the number of elements is greater than 1, how many of this form is more Values, servlets output these values in the form of an HTML list; the servlet puts the variable value into the form in other cases.
Showparameters.java
Note that ShowParameters.java uses servletutilities.java described earlier.
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Import java.util. *;
Public class showparameters extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
String Title = "Read all request parameters";
Out.println (servletutilities.headwithtitle (title)
"
\n""
Parameter Name | Parameter Value");
Enumeration paramnames = request.getParameterNames (); While (paramnames.hasmoreElements ()) { String paramname = (string) paramnames.nextelement (); Out.println (" |
---|---|
" paramname "\ N | ");
String [] Paramvalues = Request.getParameterValues (paramname); IF (paramvalues.length == 1) { String Paramvalue = paramvalues [0]; IF (paramvalue.length () == 0) Out.print (" NO value i>); Else Out.print (Paramvalue); } else { Out.println ("
For (int i = 0; i OUT.PRINTLN (" } Out.println (" ul>"); } } Out.println (" Table> \ N Body> html>"); } Public void dopost (httpservletRequest Request, Httpservletresponse response Throws servletexception, ioException { DOGET (Request, Response); } } Test form Here is a form Postform.html that sends data to the servlet described above. Just like all forms containing password input domains, the table sends data with the POST method. We can see that the two methods of doget and dopost have brought convenience to form production in the servlet. HEAD> with post method to send data form h1> |