JSP and Servlet

Source: Internet
Author: User
Tags execution header html header sql server session id urlencode web services java web
Js|servlet JSP and Servlet
The main purpose of this article is not simply to introduce JSP, nor is it a detailed introduction to the servlet. This is a basic article about the relationship between JSP and the servlet. This article is mainly written for those who learn JSP. As for the servlet and JavaBean, as well as the servlet and XML, my two classmates will give a clear explanation in their documentation.
The main structure of this article:
1. What is a servlet?
2. JSP and servlet.
3. Servlet Overview
4. Appendix I
5. Appendix II
In the process of the narration, the main is to write about the difference between JSP and servlet relationship.
The content sequence of this article is written in this way to reflect the development order of technology.
Appendix I provides information on how to run a servlet, which is entirely based on my own experience and has been confirmed by me.
Some pure practical notes are collected in Appendix Ii. Reproduced
A. What is a servlet?
Development of client/server computing. Java provides a complete set of client/server solutions in which programs are automatically downloaded to the client and executed, which is the applet. But it's only half the problem. The other half of the problem is the servlet.
A servlet can be considered a server-side applet. The servlet is loaded and executed by the Web server just as the applet is loaded and executed by the browser. The servlet receives the request from the client (through the Web server), performs some job, and returns the result. The basic process for using a servlet is as follows:
• Client requests are made via HTTP.
· The Web server receives the request and sends it to the servlet. If the servlet has not yet been loaded, the Web server will load it onto the Java virtual machine and execute it.
servlet will receive the HTTP request and perform some processing.
Servlet will return an answer to the Web server.
· The Web server sends an answer received from the servlet to the client.
Because the servlet is executed on the server, it is usually not necessary to implement the security issues associated with the applet. Note that Web browsers do not communicate directly with the servlet, and that the servlet is loaded and executed by the Web server.
And the servlet was written in Java, so they started out as platform-independent. In this way, the commitment that Java can write once on any platform (write Once,run anywhere) can be implemented on the server as well. Servlet also has some of the unique advantages of CGI scripts: (I do not know the CGI very well, so these characteristics can not fully understand, this is also excerpted from the forum post, please forgive me)
The servlet is persistent. The servlet only needs a Web server to load once, and can maintain services (such as a database connection) between different requests. In contrast, CGI scripts are ephemeral and transient. Each request for a CGI script will cause the Web server to load and execute the script. Once the CGI script is finished, it is purged from memory and the result is returned to the client. Every time a CGI script is used, it causes a repeat execution of the program initialization process, such as connecting to the database.
The servlet is platform-independent. As mentioned earlier, the servlet is written in Java and it naturally inherits Java platform independence.
The servlet is extensible. Because the servlet is written in Java, it has all the benefits that Java can bring. Java is a robust, object-oriented programming language that can easily be scaled to suit your needs. The servlet naturally has these characteristics as well.
The servlet is secure. The only way to invoke a servlet from outside is through a Web server. This provides a high level of security, especially if your Web server is protected by firewalls.
Setvlet can be used on a wide variety of clients. Because the servlet is written in Java, you can easily use them in HTML, just as you would use an applet.
So how does a servlet do that? How do you write a servlet, and what is its basic architecture?
These questions will be covered later in this section.
Two. JSP and Servlet
Now that we have a general idea of the servlet, let's talk about the relationship between JSP and servlet.
JSP is a scripting language that wraps the Java Servlet System interface, simplifies the use of Java and servlet, and provides the ability to dynamically execute Web pages by extending the JSP tag (tag). However, the JSP is still not beyond the scope of Java and servlet, not only the JSP page can write Java code directly, and JSP is translated into a servlet before the actual operation. The JSP executes on the server and outputs the execution results to the client browser, which we can say is largely irrelevant to the browser. It is different from JavaScript, JavaScript is in the client's scripting language, executed on the client, unrelated to the server.

So what is a JSP? is the servlet.
The main difference between JSP and servlet is that JSP provides a simple set of tags, and HTML blends better, so that people who do not know the servlet can make dynamic Web pages. For people who are unfamiliar with the Java language (like me, for example), JSP development is more convenient. JSP changes can immediately see the results, do not need to manually compile, the JSP engine will do this work, and servelt need to compile, restart the servlet engine and so on a series of actions. But in a JSP, HTML is mixed with program code, and the servlet does not. Maybe we are confused, so what is a servlet? Here we will do a simple introduction to the JSP run, tell you how to execute a JSP file:
When the Web server (or servlet engine, application Server) supports the JSP engine, the JSP engine converts the JSP file into a servlet code source according to the JSP syntax, and the servlet is compiled into a Java executable byte code (bytecode). and load the execution in a normal servlet way
JSP syntax is simple, can be easily embedded in the HTML, it is easy to add dynamic parts, convenient output HTML. The output of HTML in the servlet needs to call a specific method, and for characters such as quotes to do special processing, added to the complex HTML page as a dynamic part, compared to JSP is more difficult.
The difference between a JSP and a servlet is very small except for the conversion and compilation phases.
The JSP engine is usually built on top of the servlet engine, itself a servlet, translating JSP files into servlet source code, then invoking the Java compiler and compiling into a servlet. This is also the reason that the JSP is slower in the first call, and the JSP is the same speed as the servlet after the first compilation. Let's see why they compile the same speed after the first compilation:
Throughout the run, the JSP engine checks whether the compiled JSP (as a servlet exists) is newer than the original JSP file, and if not, the JSP engine is not compiled, and if not, the translation and compilation process is performed again, if it is not.
To have a deep understanding, let's look at the running and development environment of JSP:
Browsers: Common browsers are two kinds of IE and Netscape.
Database: The commonly used database has oracle,sql server,informix,db2,sybase,access,mysql and so on.
Operating system: Common Windows,linux, as well as a variety of UNIX systems.
Web server: Common iis,apache,netscape Enterprise server.
JSP Engine: The general JSP engine is based on the servlet engine and appears as a servlet. At the same time, in the implementation of free and business engines, the servlet engine and the JSP engine often come together, and we become servlet/jsp engines, or from some kind of JSP engine.
The JSP engine is a system-level entity that can provide JSP and servlet run support and manage its lifecycle.
When the JSP page is first requested, the JSP engine converts the JSP raw file into the servlet source code, then invokes the Java compiler, compiles it into a servlet, and executes it in the servlet engine. When there is another request, the JSP engine meets the difference compiled JSP is newer than the original JSP original file, if it is, run the servlet; if not, the file has been updated, and the conversion and compilation process will be performed anew.
Here, also basic JSP and servlet relationship clearly, from my feeling to see with JSP on it, simple and convenient, but also with the bean very good compatible use, the function is very powerful, why the servlet, it has what to use? Moreover, its writing is relatively complex. To make the problem clearer, I would like to say a little bit about history here, and then explain why the benefits of Servlet,servlet.
Historical brief: (Excerpt from a forum with abridged, rewritten)
In short, Sun first developed a servlet, its function is relatively strong, the system design is also very advanced, just, it output HTML statements or used the old CGI way, is a sentence output, so, write and modify HTML is very inconvenient.
Later, Sun introduced a similar to ASP Mosaic JSP (is the product of the development of the servlet), the JSP tag embedded into the HTML statement, so that greatly simplifies and facilitate the design and modification of the Web page. The new type of network language, such as asp,php,jsp, is a mosaic script language.
From the perspective of network three-layer structure, a network project is at least three layers: data layer,business layer, presentation layer. Of course, it can be more complicated. The servlet is powerful for writing business layer, but it is inconvenient to write presentation layer. JSP is mainly for the convenience of writing presentation layer design. Of course, you can write business layer. Write accustomed to asp,php,cgi friend, often unconsciously presentation layer and business layer mixed together. Put the database processing information into the JSP, in fact, it should be placed in the business layer.
According to Sun's own recommendation, JSP should only store content related to presentation layer, that is to say, only the part of the output HTML page. And all the data calculation, data analysis, database connection processing, all belong to business layer, should be placed in the Java beans. Call Java BEANS through JSP to achieve the integration of two tiers.
In fact, Microsoft's DNA technology, simply put, is asp+com/dcom technology. Completely similar to Jsp+beans, all presentation layer are completed by ASP, and all business layer are completed by com/dcom. By calling, you implement consolidation. Now Microsoft has launched. NET is also through this idea, all presentation layer completes by ASP.net, business layer by C # or vb.net or vc.net to complete.
Why do you use these component technologies? Because the simple asp/jsp language is very inefficient, if a large number of user clicks, the Pure script language will soon reach his upper limit, and component technology can greatly increase the upper limit of the function, speed up the execution speed.
On the other hand, the pure script language will presentation layer and business layer mix together, cause the modification is inconvenient, and the code cannot reuse. If you want to modify a place, often involves more than 10 of pages of code, the adoption of component technology only the reorganization of the pieces can be.
To sum up, the servlet is an early imperfect product, write business layer very good, write presentation layer is very bad, and two layers of mixed, it seems very confusing.
So, the introduction of Jsp+baen, with JSP write presentation layer, with Baen write business layer. Sun's own meaning is to use JSP instead of the servlet in the future.
Read the above description, you may have JSP and servlet coexistence has a better understanding. You can see the practicality of JSP and Bean combined, powerful performance, ease of use are not the servlet. So is the servlet replaced? No! In the future development, it still has a huge role. It's just the one thing that's going on, so let's look at the characteristics of the servlet itself.
Because it is written by Java, so the characteristics of the relevant we do not say, the above has been detailed introduction, we have to look at the other:
A servlet is a programming model for developing server-side applications that can be written without a servlet if it is just a common Java application, but if you want to provide web-based service capabilities, you must follow this model to write, The servlet must also allow the servlet-compliant Java Web server or app server to run otherwise. Unless you implement a Web server yourself, but its complexity is relatively high, especially in enterprise applications, the stability and robustness of the system are relatively high, so the servlet model is actually simplified writing a robust server-side application development process. A Servlet can be used as an access way to provide Web services capabilities
Now maybe you can understand what a servlet is and what a JSP is and what the relationship is. Below I will make a brief introduction to the servlet technology.
Servlet overview
A The structure of the servlet
The most important thing in the Servlet API is the servlet interface. All Servlets implement (execute) This interface, in a variety of ways: either directly, or through extending this class to execute it, such as HttpServlet. This servlet interface provides a way to arrange the servlet to contact the client. Servlet writers can provide more or all of these methods when they develop a servlet program.
When a servlet receives a call request from the client, it receives two objects: one is ServletRequest, the other is servletresponse. This ServletRequest class outlines the connection from the client to the server, while the Servletresponse class outlines the connection from the servlet back to the client.
ServletRequest interface can obtain such information as the stated name that is delivered by the client, the protocol that the client is using, and the remote host name of the server that produces the request and receives the request. It also provides the servlet, ServletInputStream, that gets the data stream, which is submitted using the HTTP POST and put method in the client reference. A servletrequest subclass allows the servlet to obtain more protocol attribute data. For example: HttpServletRequest contains methods for obtaining Http-specific header information.
Servletresponse interface gives the corresponding servlet method to the client. It allows the servlet to set the content length and the MIME type of the response, and provides the output stream, Servletoutputstream, through which the author can send back the corresponding data. Servletresponse subclasses can give you more information about the protocol-specific capacity. For example, HttpServletResponse contains methods that allow the servlet to manipulate http-specific header information.
The above description of classes and interfaces constitutes a basic servlet framework. HTTP Servlets has some additional methods that can provide session-tracking capabilities. Servlet writers can use these APIs to maintain the state between the servlet and the client when they have other actions.
Two Writing a servlet
Servlets executes Javax.servlet.Servlet interface. Servlet writers can develop servlet through direct implement interface, but this is usually not necessary. Because most servlet is for Web servers with HTTP protocols, the most common development servlet approach is to use Javax.servlet.http.HttpServlet. HttpServlet class through Extend The Genericservlet base class executes the Servlet interface, providing the ability to handle HTTP protocols. His service method supports the standard http/1.1 request. Generally, servlets written in the class specified by HttpServlet can concurrently run the service method in a multi-threaded manner.
Servlet writers note that the HttpServlet class has several missing methods, you can define the contents of the method yourself, but you must use these method names so that the servlet knows what you want to do,
Doget, used to process get, conditionally got, and header head requests
DoPost, the user processes POST requests
DoPut, for handling put requests
Dodelete, for handling delete requests
HttpServlet service method, generally, when it receives an option request, it invokes the Dooptions method when a trace request is received to invoke Dotrace. Dooptions default execution is to automatically determine what HTTP is selected and which information is returned.
When you use these methods, you must take two elaboration. The first contains data httpservletrequest from the client. The second parameter contains the client's response httpservletresponse. In the following example, this is the case.
A HttpServletRequest object provides access to HTTP header data and also allows you to obtain data from the client. How this data is obtained depends on the HTTP-side request method.
Regardless of any HTTP method, you can use the]getparametervalues method, which returns the parameter value for a particular name.
For an HTTP GET request, the GetQueryString method will return a can be used for anatomical analysis. There are two ways you can choose between using HTTP POST, put, and delete requests. If it is text data, you can use the Getreader method to obtain the BufferedReader, if it is binary data, can be obtained by Getreader method with ServletInputStream.
In response to the client, a HttpServletResponse object provides two methods for returning data to the user. You can return with the Getwriter method, or getoutputstream the method with the output stream. You should use Getwriter to return the text data and use Getoutputstream to return the binary data.
Before using writer or outputstream, HTTP headers should be set first. HttpServletResponse provides such a method that you can then send the response body part back to the user with writer or outputstream. When you are done, close the writer or output stream so that the server knows that the response is complete.


Appendix I
Run your servlet!.
When a servlet has written how to run a test? It took me a long time to study this, perhaps because I was too stupid. But it's not hard to think about it now. I would like to use an example in detail to say that there will be an emotional grasp. I would write down the main problems I had at the time, and I hope everyone would pay attention to the place where I was mainly wasting my days. (I use the operating environment is Tomcat5.0)
First, we'll write the simplest 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 ("<HTML>");
Out.println ("<BODY>");
Out.println ("<p>hello! This is my first Java servlet program.") </p> ");
Out.println ("</BODY>");
Out.println ("</HTML>");
}
}
As we packed it, we put the compiled. class file into the \tomcat folder \webapps\ourappfiles\web-inf\classes\test folder.
Then we need to write an HTML file that calls the servlet:
<title>java Servlets sample-properties</title>
<body>
<form method= "Get" action= "test." HelloServlet ">
<input name= "test" type= "submit" value= "Test HelloServlet servlet" >
</body>
Note: This method can not be used post, otherwise it will not be in the normal display of IE, I was in this place did not fix, wasted a lot of time. As for why to write this, I also do not know very well, because the level is limited, many forgive.
Now we are still in the final step, writing our Web.xml file.
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//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-mapping>
</web-app>
Put the written web.xml file under the \tomcat folder \webapps\ourappfiles\web-inf.
Well, now that everything is ready, it's bad to start Tomcat running our servlet.
These are a few steps to running the servlet.
Appendix II
This appendix is just another reading note, I feel better, so excerpt down. It is written in the crystallization of experience, I have not so much experience, so only excerpts from others to add.
1. ServletConfig
L A ServletConfig object is a servlet container passed to the servlet when the servlet initialization.

ServletConfig includes ServletContext and some name/value pair (from deployment descriptor)

The L ServletContext interface encapsulates the context concepts of Web applications.

2. Session tracking
1) session
L When a client requests multiple Servlets, a session can be shared by multiple servlet.

L Typically, if the server detect to browser to support cookies, the URL will not be overwritten.


2) Cookies
L In the Java servlet, if you light a cookie cookie = new Cookie (name,value)
Then when the user exits browser, the cookie is deleted and not stored on the client's hard disk.

If you want to store cookies, add a sentence cookie.setmaxage (200)

The L cookie is associated with a server, and the servlet running on the same server shares a cookie.

3) URL Rewriting
When you use the URL rewriting to maintain the session ID, each HTTP request requires a encodeurl ()
Typical for use 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.encodeurl ("Sessionexample?database=foo&datavalue=bar"));
OUT.PRINTLN (">url encoded </a>");

3. Singlethreadmodel
By default, each servlet definition in a container has only one instance of Servlet class.
Only the implementation of Singlethreadmodel,container will let the servlet have multiple instances.

The Servlet specification recommends that you do not use synchronized and use Singlethreadmodel.

Singlethreadmodel (no method)
Ensure that the servlet processes only one customer's request at the same time.
Singlethreadmodel is resource-intensive, especially when a large number of requests are sent to the servlet, the Singlethreadmodel is to enable the package container to invoke the service method in a synchronized clock manner.
This equates to the use of synchronized in the service () method of the servlet.

Single Thread model is typically used when you need to respond to a heavy request, such as a connection that requires dealing with the database.


2. After overloading the servlet init () method, be sure to call Super.init ();

3. The client sends a blank line indicating that it has ended the request
The server, by closing the socket, indicates that the response is over.

4. An HTTP servlet can send three of things to the client
1) A single status code
2) Any number of HTTP headers
3) A response body

5. One of the easiest ways to share information among the servlet is
System.getproperties (). Put ("Key", "value");

6. Post and get
Post: Place each field name and content in the form within the HTML header to be routed to the server
Get: After the query string to use UrlEncode, after UrlEncode, the string no longer has a space, the next will be restored on the server with the space.

Get is one of the most frequently used request methods on the Web, and each hyperlink uses this method.

7. Web.xml is the deployment descriptor of Web Applicatin
The function has: organizes each kind of element
Set init param
Set security

8. Request dispatcher is used to processing the received Request forward to another servlet
The request Dispatcher is also used when you want to include output from another servlet in one response.

9. servlet and JSP in the same JVM, you can use the Serveltcontext
SetAttribute ()
GetAttribute ()
RemoveAttribute ()
To share objects
10. String existence using Request.getparameter () has a character set problem.
can use strtitle = Request.getparameter ("title");
strtitle = new String (strtitle.getbytes ("8859-1"), "gb2312");

If you want to get a lot more compatibility
String encoding = response.getcharacterencoding (); Determine what encoding the application server uses to read input.
strtitle = new String (strtitle.getbytes (encoding), "gb2312");





Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.