Servlet

zhaozj2021-02-17  44

1. Basic Servlet Structurehere's The Outline of A Basic Servlet That Handles

Get Requests.

Get Requests, for Those Unfamiliar with http, area requests Made by Browsers When the user type in a Url on the address line, follows a link from a web page, or makes an HTML FORM THAT DOES NOT SPECIFY A

Method. Servlets can Also Very Easily Handle

Post Requests, Which Are Generated When Somene Creates An Html Form That Specifies

Method = "post". We'll Discuss That in Later Sections.

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 incoming http headers (e.g. cookies)

// and html form data (e.g. Data the user entered and submitted)

// USE "response" to specify the http response line and headers

// (E.G. Specifying The Content Type, Setting Cookies).

PrintWriter out = response.getwriter ();

// USE "out" to send content to browser

}

}

(Download

Template Source Code - Click with the right mouse on the link or Hold Down Shift while clicking on the link.)

To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST These methods take two arguments:. An HttpServletRequest and an HttpServletResponse The HttpServletRequest has methods. that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set -Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet .http (for httpservletRequest and http ServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, eg for a servlet that handles both GET and POST request.2. A Simple Servlet Generating Plain TextHere is a simple Servlet That Just Generates Plain Text. The Following Section Will Show The More Usual Case Where HTML IS generated.

2.1 HelloWorld.javayou Can Also

Download the Source OR

Try it on-line.

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");

}

}

2.2 Compiling and Installing the ServletNote that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets Are EXPECTED TO BE in a Directory Called

Servlets in The JWS Installation Hierarchy. Hiever, i Placed this Servlet in A Separate Package

hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and does not have a good infrastructure for "virtual servers" to prevent these conflicts Automatically. thus,

HelloWorld.Java Actually Goes in a subdirectory caled

Hall in the

servlets directory. Note that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use Packages Solely to Prevent Name Conflicts with Other Users.

IF You'Ve Never Used Packages Before, There Are Two Main Ways To Compile Classes That Are IN PACKAGES.

One way is to set your CLASSPATH to point to the directory above the one actually containing your servlets You can them compile normally from within the directory For example, if your base directory is C:.. / JavaWebServer / servlets and your package name (and thus subdirectory name) is hall, and you were on Windows, you'd do: DOS> set CLASSPATH = C: / JavaWebServer / servlets;% CLASSPATH% DOS> cd C: / JavaWebServer / servlets / hall DOS> javac YourServlet.javaThe first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH = ..." statement in your autoexec.bat file somewhere after the line that set the CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to the Start menu, select Settings, select Control select System Panel,, select Environment, then enter the variable And value. Note Also That if you package were of the form name1.name2.name3 Rather Than Simply Name 1 as here, You'D Still Have The ClassPath Point To the top-level directory of Your package hierarchy (the one containing name1).

A second way to compile classes that are in packages is to go to the directory above the one containing your servlets, and then do "javac directory / YourServlet.java" (Windows; note the backslash) or "javac directory / YourServlet.java" (Unix; note the forward slash) For example, suppose again that your base directory is C:. / JavaWebServer / servlets and your package name (and thus subdirectory name) is hall, and you were on Windows In that case, you '. d do the following: DOS> cd C: / JavaWebServer / servlets DOS> javac hall / YourServlet.javaNote that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after the directory name This is fixed. in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability.Finally, another advanced option is to keep the source code in a location distinct from the .class files, and use javac's "-d" Option to Install The Location The Web Server EXPECTS.

2.3 Running The Servletwith The Java Web Server, Servlets Are Placed in The

Servlets Directory Within The Main Jws Installation Directory, And Are INVOKED VIA

http:// host / servlet / servletname. Note That The Directory IS

Servlets, Plural, While The URL Refers To

Servlet, Singular. Since this Example Was Placed in The

Hall Package, IT Would Be Invoked Via

http: //host/servlet/hall.HelloWorld Other Web servers may have slightly different conventions on where to install servlets and how to invoke them Most servers also let you define aliases for servlets, so that a servlet can be invoked via..

. Http: //host/any-path/any-file.html The process for doing this is completely server-specific; check your server's documentation for details.3 A Servlet that Generates HTMLMost servlets generate HTML, not plain text as in. To do this

Println Statements to Build a legal web page. The first step is done by setting the

Content-Type Response Header. In General, Headers Can Be Set Via THE

SetHeader Method of

HTTPSERVLETRESPONSE, But Setting The Content Type Is Such A Common Task That There ISO a Special

SetContentType Method Just for this purpose. Note That You need to set response headers

BEFORE ACTUALLY RETURNING Any of The Content Via THE

PrintWriter. Here's an example:

3.1 Hellowwww.javayou can Also

Download the Source OR

Try it on-line.

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>}</p> <p>3.2 HellowW Result</p> <p>4. Simple HTML-Building Utilities IS A Bit Cumbersome To Generate Html with</p> <p>Println Statements. The Real Solution Is To Use Java Server Pages (JSP), Which IS Discussedlater in this Tutorial. However, For Standard Servlets, There Are Two Parts of the Web Page</p> <p>DOCTYPE AND</p> <p>That Are Unlikely to Change and Thus Could Benefit from Being Incorporated Into A Simple Utility File.</p> <p>The DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is very recommended both for static HTML pages and for generated via pages servlets highly, so the use of DOCTYPE is well worth the effort, especially if it can be easily incorporated into a servlet utilities Class.</p> <p>In many Web pages, the HEAD line contains nothing but the TITLE, although advanced developers may want to include META tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns the DOCTYPE, Head, And Title Entries As Output. Here's The Code:</p> <p>4.1 ServletUtilities.java (Download Source Code)</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 /// ">"</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>// Other Utilities Will Be Shown Later ...</p> <p>}</p> <p>4.2 Hellowww2.java (Download Source Code) Here's A Rewrite of The Hellowwww Class That Uses this.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-30663.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="30663" 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.042</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 = 'xhDiRv9DE3SUEdfSFskqsVvXDowPc2BuFAzq264MUojFrNTDE15DFVjLdu_2F05qaFJ1pIsytBWzvhcVcibvz8iw_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>