Servlet & JSP (2)

Source: Internet
Author: User

In servlet parsing (1), we discussed servlet, servlet container, and a servlet container-Tomcat (including installation and configuration, directory structure, operation, startup analysis, architecture and how to manage programs ). In this article, we will continue to discuss Servlet technology, including Servlet
The UML class diagram structure, how the servlet container handles requests, how to find the correct servlet, why the ing mechanism, a simple web application instance, and Servlet interface. First, we will introduce the main interfaces and classes required for servlet development, as shown in figure 1 of its UML class.

Figure 1 UML diagram of main interfaces and classes in servlet APIs

Servlet Container Processing request process

Before starting the text, let's review and refine the servlet container's request processing process.

1) the user clicks a link and points to a servlet instead of a static page.

2) The container "sees" that the request is a servlet, so it creates two objects: httpservletrequest and httpservletresponse.

3) The container finds the correct servlet Based on the URL in the request, creates or allocates a thread for the request, and passes the request and response object to the servlet thread.

4) The container calls the servlet Service () method. The Service () method calls the doget () or dopost () method based on different types of requests. Assume that the doget () method is called.

5) The doget () method generates a dynamic page and inserts the page into the response object. Note that the container also has a reference to the response object!

6) when the thread ends, the container converts the response object to an HTTP response, sends it back to the customer, and then deletes the request and response object.

Why can a servlet become a Servlet?

We can draw a conclusion by analyzing the code of a servlet. 2.

Figure 2 simple Servlet implementation code

How do servlet containers find the correct Servlet?

We just talked about how the servlet container looks for the correct servlet when processing requests?

In fact, the URL requested by the user is mapped to a specific servlet on the server in some way. A servlet has multiple names, mainly for three different objects.

1) What the user knows is a public URL name. The user sees the URL of a servlet in HTML, but does not know how the servlet name maps to the directory and file on the server. This URL name is just a virtual name for your convenience.
2) for deployment personnel, they can create a name that is only known to themselves and others in the actual operating environment. Similarly, this is a virtual name that is only used to deploy servlets. This internal name does not necessarily match the public URL name used by the user, nor does it need to be the same as the actual file and Path Name of the servlet class.
3) for developers, the servlet class has a fully qualified name, including the class name and package name. The servlet-type file has an actual path and file name, depending on the location of the package directory structure on the server.

Why is the ing mechanism used?

Think about how we can use the servlet container to find the correct Servlet? One way is to hard encode the real path name and file name to all JSP and other HTML pages using the servlet. But if you reorganize your application, what if the directory changes? If you use the ing method, there will be great flexibility. If you change the application directory, you only need to modify it in the ing. Besides, based on security considerations, do you always want users to know the directories on your servers? Therefore, the ing mechanism allows users to access a virtual name, which improves security.

Let's take a look at the overall web development mechanism through a typical MVC instance. MVC refers to model, view, and controller. Model, view, and controller. MVC extracts the business logic from the servlet and puts it into a model (that is, a reusable Java class ). A model is a combination of business data and methods. Views use JSP, HTML, and other functions to interact with the system. In MVC,ViewResponsible for representation. It gets the state of the model from the Controller (not actually, the Controller will find a place where the model data can be found ). In addition, the view also obtains user input and submits it to the Controller.ControllerObtain user input from the request, specify the impact of the input on the model, notify the model to update itself, and enable the view (JSP) to obtain a new model status.ModelStores the actual business logic and status. It knows the rules used to get and update the status. In addition, the model is responsible for communicating with the database.

The following describes the development and deployment environments of Web applications, as shown in figure 3 and figure 4.

Figure 3 Web Application Development Environment

Figure 4 Web Application Deployment Environment

A simple Web Application

Mydemo is a simple web application. The main function is to select an English word of color, and then "expert" will give a corresponding Chinese word. The servlet is the Controller Code as follows:

package com.shan.web;import com.shan.model.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;/** ** A simple Servlet Demo ** @author shan **/public class MyDemoServlet extends HttpServlet{public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {response.setContentType("text/html; charset=UTF-8");PrintWriter out= response.getWriter();String color = request.getParameter("color");out.println("You select color:" + color);Expert expert = new Expert();out.println(expert.getResult(color));out.println("<br/>Expert's result:" + expert.getResult(color));}}

The model code is as follows:

Package COM. shan. model; import Java. util. *; public class expert {private Map <string, string> Results = new hashmap <string, string> (); public expert () {results. put ("white", "White"); results. put ("black", "black"); results. put ("blue", "blue"); results. put ("red", "Red"); results. put ("green", "green");} Public String getresult (string color) {return results. get (color);} public static void main (string [] ARGs) {Expert expert = new expert (); system. out. println (expert. getresult ("white "));}}

The deployment description file (dd) is as follows:

<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"  metadata-complete="true">    <description>      My Demo.    </description><servlet><servlet-name>selectServlet</servlet-name><servlet-class>com.shan.web.MyDemoServlet</servlet-class></servlet><servlet-mapping><servlet-name>selectServlet</servlet-name><url-pattern>/SelectColor.do</url-pattern></servlet-mapping></web-app>

Figure 5 shows the detailed explanation of the web. xml file.

Figure 5 deployment description file (dd)

The following figure shows the HTML source code of a single page of a table (my name is form.html ):

Because the example is simple, the running result is no longer displayed here. If you are interested, you can develop and deploy the project as mentioned above, and then run it on your own. Compile the servlet at runtime. You can win + R, Enter cmd, and switch to the project directory. Input statement:

javac -d classes src\com\shan\model\Expert.java
javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar;classes -d .\classes src\com\shan\web\MyDemoServlet.java

After the compilation is complete, copy the files such as the classes folder to the location shown in figure 4, and enter startup to start Tomcat (Note: tomcat configuration can be configured according to the previous article ). Enter localhost: 8080/mydemo/form.html in the browser URL bar, select a color, and click OK to get the result.

Now, let's talk about this simple example. Let's continue to look at the entire running process of the server.

1 (( form.html page 2) forform.html page 3) the container returns this page to the browser, and the user answers the question in the Form 4) the browser sends the request data to the container 5) the container finds the correct servlet Based on the URL, and pass the request to this servlet 6) Serlvet calls expert for help 7) the expert class returns an answer, and the servlet adds this answer to the request object 8) the servlet forwards the request to jsp9) JSP gets an answer from the request object 10) JSP generates a page for the container 11) the container returns this page (final result) to the user.

In this example, the process for the container to find the correct servlet is as follows:

In 110000form.html, the call method is post, and the action is selectcolor. do, so after you fill out the form, the following URL will be generated: localhost: 8080/mydemo/selectcolor. do, where selectcolor. do is the logical Resource Name.
2) Search for the deployment description file of the container and find a <servlet-mapping> that matches <URL-pattern> with/selectcolor. Do.
3) The servlet-name of the <URL-pattern> container is selectservlet, but this is not the name of the actual servlet class file. Selectservlet is just a servlet name, not the servlet class name.
4) The container search servlet-Name> is the <servlet> tag of selectservlet.
5) according to the <servlet-class> label in the <servlet> tag, the container knows which servlet class is responsible for processing the request. If the servlet class has not been initialized, the class will be loaded, and initialize the servlet.
6) The container starts a new thread to process the request and sends the request to the thread (the Service () method passed to the servlet). Because the user sends an http post request, therefore, the Service () method will call the servlet dopost () method and pass the request and response object as parameters to it ).
7) The Service () method ends, so the thread is either canceled or returned to a thread pool managed by the container. Request and response object references are out of scope, so they will be reclaimed by the garbage collection mechanism. The container sends the response (through the Web server) back to the user.

Servlet Interface

In Java, we have learned Java Applet, a small Java application, and it runs in the browser of the client. Here, we can compare the similarities and differences between Java Applet and Java Servlet to deepen our understanding of Java Servlet.

What they have in common:

Neither of them is an independent application and does not have the main () method.
They are not directly called by users or programmers, but stored in containers and managed by containers. The applet runs in the browser, and the servlet runs in the servlet container.
They all have lifecycles, including the init () and destroy () methods.

Differences between the two:

Java Applet has a graphical interface and runs in the browser of the client. java servlet does not have a graphical interface and runs in the servlet container of the server.
To compile a Java Applet, you must derive a subclass from the java. Applet. Applet Class. Similar to Java Applet, to compile a Java Servlet, you must implement the javax. servlet. servlet interface.

The javax. servlet. servlet interface defines the following five methods:

public void init(ServletConfig config) throws ServletExceptionpublic void service(ServletRequest req, ServletResponse res)throws ServletException, java.io.IOExceptionpublic void destroy()public ServletConfig getServletConfig()public java.lang.String getServletInfo()

The following describes the functions of these five methods.

Init (): After the servlet is instantiated, the servlet container will call the init () method to initialize the object, the main purpose is to allow servlet objects to complete initialization before processing customer requests, such as establishing database connections and obtaining configuration information. For each servlet instance, the init () method can be called only once. The init () method has a parameter of Type servletconfig. The servlet container uses this parameter to transmit configuration information to the servlet. Servlet uses the servletconfig object to obtain the initialization parameters provided in name-value pairs from the Web application configuration information. In addition, you can use the servletconfig object to obtain the servletcontext object describing the servlet runtime environment. With this object, the servlet can communicate with its servlet container.

Service (): The container calls the Service () method to process client requests. Note that the init () method must be completed correctly before the service () method is called by the container. The container constructs a request object (type: servletrequest) that represents the client request information and a response object (type: servletresponse) that is used to respond to the client as a parameter and passes it to the Service () method. In the service () method, the servlet object obtains the client-side information and request information through the servletrequest object. After processing the request, it calls the method of the servletresponse object to set the response information.

Destroy (): When the container detects that a servlet object should be removed from the service, the container will call the destroy () method of the object, this allows the servlet object to release its resources and store data to persistent storage devices. For example, it saves data in memory to the database and closes the database connection. When the memory needs to be released or the container is closed, the container will call the destroy () method of the servlet object. Before the servlet container calls the destroy () method, if other threads are executing in the Service () method, the container will wait for these threads to finish execution or wait for the timeout value set by the server to arrive. Once the destroy () method of the servlet object is called, the container no longer sends other requests to the object. If the servlet needs to serve the client again, the container will generate a new servlet object to process the client's requests. After the destroy () method is called, the container will release the servlet object and the object will be recycled by the Java garbage collector in the following time.

Getservletconfig (): This method returns the servletconfig object passed to the servlet object when the container calls the init () method. The servletconfig object contains the servlet initialization parameters.

Getservletinfo (): returns a string containing Servlet Information, such as the author, version, and copyright. This method returns a plain text string instead of any type of tag (HTML, XML, etc ).

Each request is run in a separate instance.

As we know above, after the servlet instance is created, the container will call the init () method on the servlet instance before the servlet can provide services for the customer's request. If you have initialization code, you should overwrite the init () method of the servlet class; otherwise, the init () method of genericservlet will be called. The container creates a new request and response object and a new thread/stack for each customer request (no matter who it is, whether it is the same person or not, only for requests. No servlet class will have multiple instances. Except for a special case (singlethreadmodel is really bad), we will not discuss this special situation.

Reprinted please indicate the source: http://blog.csdn.net/iAm333

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.