Third, the first servlet

zhaozj2021-02-16  138

3.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 SomeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// Use "request" Reading and requesting information (such as cookies) // and form data // use "response" to specify HTTP response status code and response head // (such as specifying the content type, setting cookie) printwriter out = response.getwriter (); // Use "OUT" to send the answer content to the browser}} If a class is to be a servlet, it should inherit from httpservlet, and send one or all of the DOGET, DOPOST method according to 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 Servlets Output Pure Text Next 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 Servlet compiling and installing specific details of installing servlets on different web servers, please refer to the web server documentation Understand 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 main directory of the servlet is C: \javawebserver\servlets, 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 second compilation package is to enter the servlet home directory, perform "Javac Directory ..." (Windows) 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, the compilation process in Windows is as follows: DOS> CD C: \javawebserver\servlets dos> Javac Hall Hall WOURSERVLET.JAVA Note Under Windows, Most JDK 1.1 version of Javac requires the directory name to add to the slope (\). 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 Running 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 Output HTML's servlets most 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: 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 ( "! \N" " \n" " Hello WWW </ title> </ head> \n" "<body> \N" "<H1 > Hello WWW </ h1> \n " " </ body> </ html> ");}} 3.4 Several HTML tool functions Output HTML through the PrintLn statement is inconvenient, 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 <title>. Although many experienced writers will contain many Meta tags and style declarations in HEAD, but here only consider the simplest case. The following Java method only accepts the page title as a parameter, then outputs the DOCTYPE, Head, Title section of the page.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-9015.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="9015" 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.040</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 = 'bQpR15FTzRv3xdC_2F5f5aCk5vBh0UeOp0RPdhOjvv3Dndpg38GoZEj0yVdcMYu_2FUx3QK07n_2F2oW3cPOWU3edaSQ_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>