Java Web-Servlet Development

Source: Internet
Author: User

Java Web-Servlet Development

1. Servlet Introduction

Servlet is a technology provided by sun for developing dynamic web resources.
Sun provides a servlet interface in its API. To send a dynamic web Resource (that is, to develop a Java program to output data to the browser), follow these two steps:

1. Compile a Java class to implement the servlet interface.
2. Deploy the developed Java class to the web server.
 
According to a conventional naming convention, we usually call the java program that implements the servlet interface Servlet

Ii. Servlet running process

The Servlet program is called by the WEB server. After the web server receives the Servlet access request from the client:
① The Web server first checks whether the Servlet instance object has been loaded and created. If yes, perform Step 4. Otherwise, perform step 2.
② Load and create an instance object for the Servlet.
③ Call the init () method of the Servlet instance object.
④ Create an HttpServletRequest object that encapsulates the HTTP request message and an HttpServletResponse object that represents the HTTP Response Message. Then call the Servlet service () method and pass the request and response object as parameters.
⑤ Before the WEB application is stopped or restarted, the Servlet engine will uninstall the Servlet and call the Servlet's destroy () method before uninstalling it.

3. Servlet call Diagram

4. Develop Servlet in Eclipse

Create a new web project in eclipse. eclipse automatically creates the directory structure shown in:

4.1 Servlet interface implementation class

Servlet interface SUN defines two default implementation classes: GenericServlet and HttpServlet.
HttpServlet is a servlet that can process HTTP requests. It adds some HTTP protocol processing methods to the original Servlet interface. It is more powerful than the Servlet interface. Therefore, when writing a Servlet, developers should generally inherit this class, instead of directly implementing the Servlet interface.
When HttpServlet implements the Servlet interface, it overwrites the service method. The code in this method automatically determines the user's request method. For example, if it is a GET request, it calls the doGet method of HttpServlet, for a Post request, the doPost method is called. Therefore, when writing a Servlet, developers generally only need to override the doGet or doPost method, rather than the service method.

4.2 create and compile a Servlet through Eclipse

Select the gacl. servlet. study package, right-click → New → Servlet, as shown in:
  


In this way, we can use Eclipse to create a Servlet named ServletDemo1. The following code is provided in the created ServletDemo01:

package gacl.servlet.study;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo1 extends HttpServlet {    /**     * The doGet method of the servlet.      *     * This method is called when a form has its tag value method equals to get.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("");        out.println("
"); Out. println (" "); Out. println (" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" "); Out. println (" "); out.flush(); out.close(); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
"); Out. println (" "); Out. println (" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" "); Out. println (" "); out.flush(); out.close(); } }

These codes are automatically generated by Eclipse, and there are two more tags in the web. xml file. The two tags configure ServletDemo1, as shown in:

Then we can access the Servlet ServletDemo1 in a browser, as shown in:

5. Servlet development considerations

5.1 configure Servlet URL ing

Because the client accesses resources on the web server through the URL address, if the Servlet program is to be accessed by the outside world, the servlet program must be mapped to a URL address, which works on the web. use elements and elements in the xml file.
The element is used to register the Servlet. It contains two main sub-elements: And, which are used to set the Registration Name of the Servlet and the complete Class Name of the Servlet respectively.
An element is used to map an external access path of a registered Servlet. It contains two sub-elements: and, respectively, used to specify the Registration Name of the Servlet and the external access path of the Servlet. For example:


      
   
    ServletDemo1
       
   
    gacl.servlet.study.ServletDemo1
     
    
      
   
    ServletDemo1
       
   
    /servlet/ServletDemo1
     
  

The same Servlet can be mapped to multiple URLs. That is, the set value of the child element of multiple elements can be the Registration Name of the same Servlet. For example:


      
   
    ServletDemo1
       
   
    gacl.servlet.study.ServletDemo1
     
    
      
   
    ServletDemo1
       
   
    /servlet/ServletDemo1
     
   
      
   
    ServletDemo1
       
   
    /1.htm
     
     
      
   
    ServletDemo1
       
   
    /2.jsp
     
     
      
   
    ServletDemo1
       
   
    /3.php
     
     
      
   
    ServletDemo1
       
   
    /4.ASPX
     
  

Through the above configuration, when we want to access the Servlet named ServletDemo1, we can use the following addresses to access:

Http: /localhost: 8080/JavaWeb_Servlet_Study_20140531/servlet/ServletDemo1

Http: /localhost: 8080/JavaWeb_Servlet_Study_20140531/1.htm

Http: // localhost: 8080/JavaWeb_Servlet_Study_20140531/2.jsp

Http: // localhost: 8080/JavaWeb_Servlet_Study_20140531/3.php

Http: /localhost: 8080/JavaWeb_Servlet_Study_20140531/4. ASPX
ServletDemo1 is mapped to multiple URLs.

5.2 use * wildcard ing for Servlet access URLs

You can also useWildcard, but there can only be two fixed formats: one format is". Extension ". The other format starts with a forward slash (/) and ends. For example:


      
   
    ServletDemo1
       
   
    gacl.servlet.study.ServletDemo1
     
     
      
   
    ServletDemo1
      
   
    /*
   
  

* It can match any character, so you can use any URL to access the Servlet ServletDemo1, as shown in:

For the following mappings:
Serving Servlet1 to/abc /*
Serving Servlet2 /*
Serving Servlet3 to/abc
Serving Servlet4 to *. do
When the request URL is "/abc/a.html", "/abc/And/"Matching, which servlet response
The Servlet Engine calls Servlet1.
When the request URL is "/abc", "/abc/*" and "/abc" Both match and the servlet response
The Servlet Engine calls Servlet3.
When the request URL is "/abc/a. do/And. Do "all match, which servlet response
The Servlet Engine calls Servlet1.
When the request URL is "/a. do",And. Do "all match, which servlet response
The Servlet Engine calls Servlet2.
When the request URL is "/xxx/yyy/a. do",And. Do "all match, which servlet response
The Servlet Engine calls Servlet2.
The matching principle is "Who looks more like who is looking"
  
5.3 differences between servlets and common Java classes

Servlet is a Java class called by other Java programs (Servlet Engine). It cannot run independently. Its running is controlled and scheduled by the Servlet engine.

For multiple Servlet requests from the client, the server usually creates only one Servlet instance object. That is to say, once the Servlet instance object is created, it will reside in the memory, for other subsequent request services, the servlet instance object will not be destroyed until the web Container exits.

During the entire Servlet lifecycle, the Servlet init method is called only once. Each access request to a Servlet causes the Servlet engine to call the servlet service method once. For each access request, the Servlet engine will create a new HttpServletRequest request object and a new HttpServletResponse response object, and then pass these two objects as parameters to the Servlet service () It calls () the service method then calls the doXXX Method Based on the Request Method.

If an element is configured in the element, the WEB application loads and creates the Servlet Instance Object and calls the init () method of the Servlet instance object at startup.

Example:
          
   
    
Invoker
           
   
    
Org. apache. catalina. servlets. InvokerServlet
           
   
    
1
       
  

Purpose: Write an InitServlet for a web application. This servlet is configured to start the loading and create necessary database tables and data for the entire web application.

5.4 default Servlet

If the Servlet ing path of a Servlet is only a forward slash (/), the Servlet becomes the default Servlet of the current Web application.

All in the web. no matching element URL is found in the xml file. All access requests are sent to the default Servlet. That is, the default Servlet is used to process access requests not processed by other servlets. For example:


      
   
    
ServletDemo2
       
   
    
Gacl. servlet. study. ServletDemo2
       
   
    
1
     
    
    
      
   
    
ServletDemo2
       
   
    
/
     
  

When accessing a non-existent Servlet, use the configured default Servlet for processing, as shown in:

In <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> default org.apache.catalina.servlets.DefaultServlet debug 0 listings false 1 default /

When accessing a static HTML file and image on the Tomcat server, the default Servlet is actually accessed.

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.