First servlet

xiaoxiao2021-03-06  68

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"

" Hello WWW </ title> </ head> \n" </p> <p>"<Body> \n" </p> <p>"<H1> Hello WWW </ h1> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>3.4 Several HTML Tools Functions</p> <p>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.</p> <p>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 <title>. Although many experienced writers will contain many Meta tags and style declarations in HEAD, but here only consider the simplest case.</p> <p>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:</p> <p>ServletUtilities.java</p> <p>Package Hall;</p> <p>Public class servletutilities {</p> <p>Public static final string docType =</p> <p>"<! Doctype html public \" - // w3c // DTD HTML 4.0 Transitional // EN \ ">"</p> <p>Public static string headwithtitle (String Title) {</p> <p>Return (DOCTYPE "\N" </p> <p>"<Html> \n" </p> <p>"<Head> <title>" title "</ title> </ head> \n");</p> <p>}</p> <p>// The code for other tool functions is introduced later this article</p> <p>}</p> <p>Hellowww2.java</p> <p>Below is the HellowW2 obtained after the use of servletUtilities after rewriting the HellowWW class:</p> <p>Package Hall;</p> <p>Import java.io. *;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Public class hellowwww2 extends httpservlet {</p> <p>Public void doget (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Response.setContentType (Text / HTML ");</p> <p>PrintWriter out = response.getwriter ();</p> <p>Out.println (ServletUtilities.Headwithtitle ("Hello WWW") </p> <p>"<Body> \n" </p> <p>"<H1> Hello WWW </ h1> \n" </p> <p>"</ Body> </ html>");</p> <p>}</p> <p>}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110339.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="110339" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.044</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'HOQbcjgt822iLHJPt3vVGwrpn4eudBrchfmQNwWUwBqCqxHEoT91aJv2PW27qzeTDBmr0hgAwCq5fuHbJDphmQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>