JSP and servlet

xiaoxiao2021-03-06  54

The main purpose of JSP and Servlet This article is not simply introducing JSP, nor is it a detailed introduction of servlet. This is a basic article that tells the relationship between JSP and Servlet. This article is mainly written for those who study JSP. As for Servlet and JavaBean and Servlet and XML I will give a clear explanation in their documentation. The main structure of this article: What is servlet? 2. JSP and servlet.3. Servlet Overview 4. Appendix 1 5. Appendix II In the process of telling, it is mainly for JSP and servlet relationships. The reason why this article is written in this way is to reflect the development of technologies. Appendix one provides the content of how to run a servlet, which is completely written according to my own experience, and its content has been confirmed by himself. There are some pure practice notes in Appendix II. (Reproduced) 1. What is servlet? The development of client / server calculations. Java provides a complete set of client / server solutions, in which program can automatically download the client and execute, this is the applet. But it is just half of the problem. The other half of the problem is servlet. The servlet can be considered a server-side applet. Servlet is loaded and executed by the web server, just like the applet is loaded and executed by the browser. Servlet receives a request from the client (via the web server), executes a job, and then returns the result. The basic procedure using the servlet is as follows: • The client will request a request via HTTP. • The web server receives the request and send it to the servlet. If this Servlet has not been loaded, the web server will load it into the Java virtual machine and execute it. · Servlet will receive the HTTP request and perform some processing. · Servlet will return to the web server. • The web server sends a response received from the servlet to the client. Since the servlet is executed on the server, the problem that is usually related to Applet does not need to be implemented. Note that the web browser is not directly communicating with servlet, and servlet is loaded and executed by the web server. The servlet is written in Java, so they are not related to the platform. In this way, Java writes a commitment of Write Once, Run Anywhere, can also be implemented on the server. Servlet also has some unique advantages that CGI scripts: (I don't know how to understand CGI, so these features can not fully experience, this is also a post from the forum, please forgive me) Servlet is lasting. Servlet requires only a web server to load it once, and the service can be kept between different requests (such as a database connection). In contrast, the CGI script is short, transient. Every time a request for the CGI script will make the web server load and execute the script. Once this CGI script ends, it will be cleared from memory and then return the result to the client. Each time the CGI script is used, it will cause the program initialization process (such as the connection database). Servlet is not related to the platform. As mentioned earlier, servlet is written in Java, which naturally inherits the Java platform independence. servlet is scalable. Since servlet is written in Java, it has all the advantages that Java can bring. Java is robust, object-oriented programming language, it is easy to expand to adapt to your needs. Servlet also has these features. Servlet is safe. The only way to call a servlet from the outside is through the web server. This provides a high level of security, especially when your web server has firewall protection. Setvlets can be used in a variety of clients. Since servlet is written in Java, you can easily use them in HTML, just like you use Applet.

So, how is the servlet? How to write a servlet, how is its basic architecture? These issues will be introduced in the back section. II .jsp and servlet now has a probably understanding of servlet, and now we will say the relationship between JSP and Servlet. JSP is a scripting language that is packaged in the interface of the Java Servlet system, which simplifies the difficulty of Java and Servlet, and provides the ability to dynamically perform web pages by extending JSP tags (TAG). Despite this, JSP still does not exceed Java and servlet, not only to write Java code directly on the JSP page, but the JSP is actually run after being translated into a servlet. JSP is executed on the server and outputs the execution result to the client browser, and we can say that it is basically unrelated to the browser. It is different from JavaScript. JavaScript is on the scripting language of the client, executes on the client, unrelated to the server.

So what is JSP? The main difference between servlet.jsp and servlet is that JSP provides a simple label, and HTML fusion is better, and people who don't know the servlet can make dynamic web pages. For those who are unfamiliar with Java language (like me), I will feel that JSP is relatively convenient. After the JSP is modified, you can immediately see the result, do not need to be manually compiled, the JSP engine will do these work; while Servelt is a series of actions such as compilation and restart the Servlet engine. But in JSP, HTML is mixed with program code, but the servlet is not the case. Maybe everyone is more chaotic, then what is the servlet? Let's make a simple introduction to the JSP's run, tell you how to perform a JSP file: When the web server (or servlet engine, application server) supports the JSP engine, the JSP engine will follow the JSP's grammar and will join the JSP file. Convert to a servlet code source file, then servlet will be compiled into Java executable bytecode, and load a JSP syntax in a general servlet method, it is easy to embed HTML, it is easy to join the dynamic part. Convenient output HTML. Output HTML in the servlet requires a specific method. For characters such as quotation marks, it is also difficult to perform a special processing in a complex HTML page, which is more difficult than JSP. Remove the conversion and compilation phase, the difference between JSP and servlet is really not big. The JSP engine usually architecture above the servlet engine, itself is a servlet, translates JSP files into servlet source code, then call Java compiler, compile into servlet. This is also the reason why JSP is slower during the first call. After the first compilation, JSP is the same speed. Let's take a look at why they have the same speed after the first compilation: run throughout In the process, the JSP engine checks if the compiled JSP (existing in the form of servlet) is more new than the original JSP file, if so, the JSP engine will not compile; if not, it means that the JSP file is new, will re-execute the translation and Compile process. In order to have a deep understanding, let's take a look at the operation and development of JSP: Browser: Common browsers have two types of IE and Netscape. Database: Commonly used databases have Oracle, SQL Server, Informix, DB2, Sybase, Access, MySQL, etc. Operating system: Common Windows, Linux, and various UNIX systems. Web Server: Common IIS, Apache, Netscape Enterprise Server, etc. JSP engine: The general JSP engine is based on a servlet engine and appears in the form of servlet. At the same time, in the implementation of various free and business engines, the Servlet engine and JSP engine usually appear together, we become a servlet / JSP engine, or from some kind of JSP engine. The JSP engine is a system-level entity that can provide JSP and Servlet running support and managed for its survival cycle. When the JSP page is previously requested, the JSP engine converts the JSP original file into a servlet source code, then calls the Java compiler, compiles to servlet, and executes in the servlet engine. When there is a request again, the JSP engine meets if the difference is better than the original JSP is new, if yes, run the servlet; if not, the file has been updated, will execute the conversion and compilation from the new .

Speaking here, it is basically clear that JSP and servlet is clear, and from my feelings you can use to use JSP, simple and convenient, and it can be used well with Bean, and it is very powerful, why appears Servlet, what is it? Moreover, its writing is relatively complicated. In order to make a clearer, I want to talk about history here, by the way, why should I use servlet, servlet? History: (taken from a forum has a deletion, rewriting) Simply said that Sun first develops servlet, its function is relatively strong, the system design is also very advanced, just, it outputs an HTML statement or an old CGI mode, is a sentence Output, so it is very inconvenient to write and modify HTML. Later, Sun launched a mosquating JSP similar to the ASP (the product of servlet development), inlaid in the HTML statement, which greatly simplifies and makes the design and modification of the web page. New network languages ​​such as ASP, PHP, JSP are all inlaid Script languages. From the perspective of the three-layer structure of the network, a network program minimum 3 layers: Data Layer, Business Layer, Presentation Layer. Of course, it can also be more complicated. Servlets are very powerful, but it is very inconvenient to write Presentation Layer. JSP is mainly designed for convenience to write Presentation Layer. Of course, you can also write Business Layer. Write a friend who is used to ASP, PHP, and CGI, often uncomfortably mixing Presentation Layer and Business Layer. Putting the database processing information in JSP, in fact, it should be placed in Business Layer. According to Sun's own recommendation, JSP should only store content related to Presentation Layer, that is, only part of the HTML web page is output. All data calculations, data analysis, database linkage processing, all of which belong to Business Layer, should be placed in Java Beans. Call JAVA Beans through JSP to implement two layers of integration. In fact, Microsoft launched DNA technology, simply, is ASP COM / DCOM technology. Similar to JSP Beans, all Presentation Layer is done by ASP, and all Business Layer is done by COM / DCOM. Integration by calling and implementing. Now Microsoft launched .Net also passed this concept, all of the Presentation Layer is done by ASP.NET, and Business Layer is done by C # or VB.NET or VC.NET. Why use these components technology? Because simple ASP / JSP language is very low efficiency, if a large number of users click, the pure script language will arrive quickly from his functional upper limit, and component technology can greatly improve the functional upper limit, speed up the execution speed. On the other hand, pure script language is mixed with Presentation Layer and Business Layer, causing inconvenience, and code cannot be reused. If you want to modify a place, you will often involve a dozen pages of Code. You can only change the components using component technology.

In summary, servlet is an early imperfect product, written for Business Layer, Write presentation layer is very bad, and two layers are mixed, it is very confusing. So, launch JSP BAEN, Write Presentation Layer with JSP, write business layer with Baen. Sun you mean is also an alternative servlet in the future. I have seen the above narrative, and everyone may have a better understanding of JSP and servlet. It can be seen that the practicality of JSP and Bean is combined, and the powerful performance function, and the ease of use is the cavity of servlet. So is the servlet is replaced? Not! It still has a huge role in the future development. The above is just an aspect of the problem. Let's take a look at the characteristics of the servlet itself. Since it is written by Java, we don't say it. We have a detailed introduction, let's take a look at other: servlet is a programming model for developing server-side applications. If only a normal Java application, you can write it without using the servlet, but if you want to provide web-based service capabilities, you must write according to this model, and servlet must also allow Java Web Server OR compliant with the Servlet specification. APP Server, otherwise you can't run. Unless you implement a web server, its complexity is relatively high, especially in enterprise applications, the stability and robustness of the system requires a relatively high stability, so the model of servlet is actually simplified to write robust. The application development process of the server side. Servlet can be used as an access method that provides web service capabilities. Maybe it can be understood what servlet is JSP, what is the relationship between them? Below I will make a brief introduction to the technology of servlet.

Servlet outlines one. Servlet's Structure The most important thing in the Servlet API is servlet interface. All servlets IMPLEMENT (execution) this interface, way multiple: or direct, or through the extending Class, such as httpservlet. This servlet interface provides Arranging servlet Methods with client contacts. Servlet writers can provide more or all such methods when they develop servlet programs. When a servlet receives a call request from the client, it receives two objects: one is servletRequest, and the other is ServletRequest Class summarizes the contact between the client to the server, and the servletResponse class is summarized from servlet to the client's contact. ServletRequest interface can get some information such as the name of the client, the client is using the protocol Generate requests and receive requests remote host name. It also provides servlet, servletinputstream, servletinputstream, servletinputStream, which is submitted in client references. A servletRequest subclass allows servlet to get more Multi-protocol characteristics. For example: httpservletRequest contains methods for obtaining HTTP-SPECIFIC header information. ServletResponse interface gives a servlet method for the corresponding client. It allows servlet to set content length and response MIME type, and provide output flow, servletoutputstream, pass through The writer can send back the corresponding data. The servletResponse subclass can give more information about Protocol-Specific capacity.

For example, HTTPSERVLETRESPONSE contains methods that allow servlets to operate HTTP-SPECIFIC header information. Above About Classes and Interfaces describes a basic servlet framework. HTTP servlets have some additional ways to provide session-tracking capabilities. Servlet writers can use These API maintain the state between the servlet and the client when there is anyone's operation. Second. Write servlet servlets to perform Javax.Servlet.Servlet Interface. Servlet writers can develop servlets by direct import implement interface, but this is usually not necessary. Because most servlets are a web server for HTTP protocols, the most common development servlet method is to use Javax .Servlet.http.httpservlet The.httpservlet class Performs Servlet Interface by the Extend GenericServlet class, provides the function of handling the HTTP protocol. His service method supports standard HTTP / 1.1 request. Generally, servlets written in the class specified by httpservlets Multi-threaded concurrency running service method .Servlet Writer Note that the HTTPServlet class has several lacking methods, you can define the content in your own method, but you must use these method names to make the servlet know what you want to do, doget, used to handle GET Conditional GET and header HEAD request DOPOST, the user handles the POST request DOPUT to process the PUT request Dodelete to process the delete request Httpservlet's service method, generally, call doOptions when it receives an Options request Method, when a TRACE request is called dotrace. Dooptions default execution method is automatically decided to select and return which information. When you use these methods, you must take two elaboration. The first contains from the client The second parameter contains the client's response httpservletResponse. In the following example, an HTTPSERVLETREQUEST object provides access to the HTTP header data, which also allows you to get the client's data. How to obtain the HTTP side request method. Regardless of any http mode, you can use the GetParameterValues ​​method, which is used to return a specific name. For the way with the HTTP GET request, this getQueryString method will return to anatomical analysis. For ways with HTTP POST, PUT, and DELETE requests, you have two ways to choose. If you are text data, you can get it with BufferedReader via the getReader method; if it is binary data, you can get servletinputStream through the GetReader method. To respond The client, an HTTPServletResponse object provides two ways to return data to the user. You can return to the getWriter method, or the getOutputStream method returns to the output stream. You should use getWriter to return text data, return binary data with GetOutputStream. Use Writer or Before OutputStream, the HTTP header should be set first. This method is provided in HttpservletResponse, which can then send the response body portion back to the user later. After completion, turn off the Writer or Output Stream so that the server knows that the response has been completed.

Appendix one runs your servlet! What is the test of a servlet? I spent a long time to study this, maybe because I am stupid. But it is not very difficult to think about it. I want to talk in detail by an example, this will have a sense of grasp. I would write the main problem I encountered with the black body. At that time, I was wasted at the time, I hope everyone will pay attention. (I use the running environment is Tomcat5.0) First we will write a simpler servlet: package test; import java.io. *; Import javax.servlet. *; Import javax.servlet.http. *;

public class HelloServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html; charset = UTF-8"); response.setCharacterEncoding ( "UTF-8"); PrintWriter OUT = response.getwriter (); out.println (""); out.println (""); out.println ("

Hello! This is my first Java servlet program . "); out.println (" "); out.println (" ");}} Because we pack it, this compiles .class The file is placed under the / Tomcat folder / webApps / ourappfiles / web-inf / class of the folder. Then we need to write an HTML file calling the servlet: java servlets sample-property </ title> </ head> <body> <form method = "get" action = "TEST.HELLOSERVLET > <input name = "test" type = "submit" value = "test helloservlet servlet"> </ body> </ html> Note: The Method here cannot use POST, otherwise it will not be displayed normally in IE, I originally It is not well done in this place, wasted for a lot of time. As for why I wrote this, I also can't get it clear, because the level is limited, there will be a lot of men. Now we have the last step, write our web.xml file. <? XML Version = "1.0" Encoding = "UTF-8"?> <! doctype web-app public "- // sun microsystems, incaps//dtd web application 2.3 // en" "http: // java. Sun.com/dtd/web-app_2_3.dtd "> <web-app> <servlet> <servlet-name> helloservlet </ servlet-name> <servlet-class> test.helloservlet </ servlet-class> </ servlet > <Servlet-mapping> <servlet-name> helloservlet </ servlet-name> <url-pattern> /test.helloservlet </ url-pattern> </ servlet-maping> </ web-app> Write a good Web The .xml file is placed in / tomcat folder / webApps / ourapfiles / web-infers.</p> <p>Ok, now everything is ready, start Tomcat to run our servlet. The above is a few steps running the servlet. Appendix II This appendix is ​​purely another reading note, I feel better, so take it down. I wrote the experience of experience, I haven't had so much experience, so I only have to use someone else to supplement. 1. ServletConfigl A servletconfig object is passed to servlet when servlet initialization is sent. ServletConfig contains servletContext and some name / value pair (from deployment descriptor)</p> <p>l ServletContext interface encapsulates the context concept of the web application.</p> <p>2. Session Tracking 1) Sessionl When a client requests multiple servlets, a session can be shared by multiple servlets.</p> <p>l Normally, if Server Detect is supported to Browser support cookies, the URL will not rewrite.</p> <p>2) Cookiel In Java Servlet, if you light cookie cookie = new cookie (Name, Value) Then when the user exits Browser, the cookie will be deleted without being stored on the client's hard drive.</p> <p>If you want to store cookies, you need to add a cookie.setmaxage (200)</p> <p>l cookie is related to a Server and runs a cookie in the servlet running on the same server.</p> <p>3) URL REWRITIG When using URL Rewriting to maintain the session ID, each HTTP request requires eNCodeURL () typically in two places 1) Out.print ("form action = /"); out.print Response.EncodeURL ("sessionexample"); out.print ("form action = /"); out.print ("Method = Get>"); 2) Out.print ("<p> <a href = / ""); Out.print (Response.Encode = foo & datavalue = bar "); out.println (" / "> URL ENCODED </a>);</p> <p>3. SingLethreadModel default, each servlet definition in a Container has an instance of a servlet class. Only SingleThreadModel, Container will make servlets multiple instances.</p> <p>SENCHRONIZED, do not use SingLethreadModel.</p> <p>SingleThreadModel (no way) guarantees that servlet is only processed by a customer request at the same time. SingLethreadModel is a resource, especially when there is a large number of requests to send to servlets, the role of SingLethreadModel is to cause the package container to call the service method in a synchronous clock. This is equivalent to the service () method of the servlet uses Synchronized.</p> <p>Single Thread Model is generally used when you need to respond to a Heavy Request, such as a connection that needs to be deal with the database.</p> <p>2. After the SERVLET INIT () method, you must remember to call super.init (); 3. The Client indicates that it has ended the Socket by sending a Blank Line indicating that the Socket is ended by closing the socket. .</p> <p>4. A http servlet can send three things to client1) a Single Status code2) ANY Number of http headers3) a response body</p> <p>5. A simple way for information sharing between servlets is System.getProperties (). Put ("Key", "Value");</p> <p>6. POST and GETPOST: Place each field name and content in the FORM in the HTML Header pass to Serverget:? The query string should be used with Urlencode, after urlencode, this string no longer has space, will be in Server Restore the spaces you have. GET is the most frequently used request method on the Web, and each hyperlink uses this method.</p> <p>7. Web.xml is the use of Web Applicatin's DEPLOYMENT DEScriptor: Organize all kinds of elements Setting init param Settings security 8. Request Dispatcher is used to include the received request forward processing to another servlet to include another servlet in a response When Output, Request Dispatcher is also used.</p> <p>9. Servlet and JSP In the same JVM, you can share objects 10 through ServelTContext's setAttribute () GetAttribute () to use the string to use the string of the string existing character set. You can use strTITE = Request.getParameter ("Title"); start.getbytes ("8859-1"), "GB2312");</p> <p>If you want to get a bigger compatibility string eNCoding = response.getCharacterencoding (); / / Determine what encoding for Application Server to read the input. Strtitle = new string (start.getbytes (eNCoding), "GB2312");</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-116646.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="116646" 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.059</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 = '_2BJdy44qgt5vGjjBNEOEExQsvOQUL1zRlbpHLLaXRqGl9hPgZP6M8JPc7R1EnV40DbxM_2B7oprS2QiihNMoTXazQ_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>