Java Servlet introduction and Examples

Source: Internet
Author: User

What is Servlet?
Java applications loaded and run on the Web Server
Run on the JVM managed by the servlet engine.
The servlet container is responsible for the communication between the servlet and the user and the method for calling the servlet.
Servlet and user communication adopt the request/response mode.
It is used to expand the Web server (Web Container) function in the form of dynamic response to client requests.

Servlet is a good choice for developing server-side applications. It can be used with JSP to provide more powerful server-side functions.

 

Three basic servlet engines
Most J2EE servers, such as BEA WebLogic, websphere application, and JBoss.
Web servers with built-in servlet containers, such as Tomcat.
For products that use Servlet Engine plug-ins, such as JRun, Apache Web server, and Microsoft IIS, Web plug-ins must be installed to integrate the Java Runtime Environment.

 

Working Principle

Servlet Request Processing Process

  1. The user sends an HTTP request from the client to the web server.
  2. The Web Container instantiates the servlet and creates a thread.
  3. The Web server sends the request to the servlet.
  4. Servlet processes the request.
  5. The servlet sends the response to the web server.
  6. The Web server forwards the response to the client.

The servlet is activated by the first request sent, and then continues to run in the background to process the request in the form of a thread. The request is very fast and will not be loaded again until the servlet is modified.
A servlet has only one instance at a time and will be retained during use of the sevlet.

Multi-threaded processing of multiple requests

Servlet Lifecycle
(1) initialization phase
In the following circumstances, the Web container loads the servlet, creates a servlet instance, and calls the servlet Init () method to initialize the servlet instance:

  • When the servlet container is started.
  • After the servlet container is started, the customer sends a request to the servlet for the first time.
  • After the servlet class file is modified, it is reloaded.

(2) Service phase
If the container receives a request for this servlet, it forwards the request to the servlet Service () method based on the URL-servlet ing relationship in the configuration file web. xml. Call doget () or dopost () in the Service () method ().

(3) termination phase

The instance is destroyed. The servlet is destroyed by calling the destory () method of servlet, closing database connections, and interrupting background threads.

 

Instance 1.

// ================================== Program description ========================== ============< br/> // program name: helloworldservlet. java <br/> // Reference URL: http://www.8isp.cn/news.jsp? Id = 165 <br/> // purpose: Compile the simplest servlet program, familiar with the Process <br/> // ========================================== =================================< br/> Import javax. servlet. *; <br/> Import javax. servlet. HTTP. *; <br/> Import Java. io. *; <br/> public class helloworldservlet extends httpservlet {<br/> Public void Service (httpservletrequest req, httpservletresponse res) throws ioexception {<br/> res. setcontenttype ("text/html"); <br/> PRI Ntwriter out = res. getwriter (); <br/> out. println ("<HTML> <pead> <title> Hello world! </Title> </pead> "); <br/> out. println ("<body>"); <br/> out. println ("<p> out. println ("<p> Hello world! </H1> </body> </ptml> "); <br/>}< br/>}

Compile helloworldservlet. Java to get the. Class file,

Copy the helloworldservlet. Class file to the intall_dir/webapps/root/WEB-INF/classes file,

Open the Web. xml file in the intall_dir/webapps/root/WEB-INF/path and add the following content between <web-app>... </Web-app>:

<Servlet>
<Servlet-Name> helloworldservlet </servlet-Name>
<Servlet-class> helloworldservlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> helloworldservlet </servlet-Name>
<URL-pattern>/helloworldservlet/* </url-pattern>
</Servlet-mapping>

Save the Web. xml file. Note that the Web. xml file before modification is backed up.

Restart the Tomcat server and enter http: // localhost: 8080/helloworldservlet in the address bar to access helloworldservlet. Class.

NOTE: If tomcat has been started, restart tomcat.

 

The directory structure is as follows:

 

Program explanation:

This program uses the service () method to respond to the client. In this response, setcontexttype ("text/html") is called to set the response content type. To send text, use the getwriter () method to obtain the printwriter object, 15th ~ Line 18 is the message sent to the client, a string "Hello World", a program that appears in almost every language. We didn't explicitly close the printwriter object, and the servlet engine will automatically close it, which will improve the performance.

 

Possible problems:

Indicates that the servlet package does not exist during compilation.

The cause of these errors is that the Java compiler does not find the class in the javax. servlet package.

To solve this problem, we need to let the Java compiler know the location of the servlet api library. Tomcat has included the servlet api library in its release, which is provided in the form of a jar file. The complete path name of this jar file is:
% Catalina_home %/lib/servlet-api.jar

(I don't know why, I still cannot add the above path. I just need to change it to the full path. C:/program files/Apache Software Foundation/tomcat 7.0/LIB)
You only need to add the path name of the JAR file under the classpath environment variable of the system.

 

Note: You need to restart your computer after modifying the system variables.

 

 

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.