Java Web-----servlet

Source: Internet
Author: User

Servlet (Server Applet), full name Javaservlet, no Chinese translation. is a server-side program written in Java. Its main function is to interactively browse and modify data to generate dynamic Web content. The narrow-sense servlet refers to the Java language implementation of an interface, the generalized servlet refers to any implementation of the Servlet interface class, in general, people will understand the servlet as the latter.

The servlet runs in a Java-enabled application server. In principle, servlets can respond to any type of request, but in most cases the servlet is used only to extend the HTTP protocol-based Web server. [Baidu Encyclopedia]

* * How do I use Servlets?

#1. Writing a Java class that inherits and HttpServlet

#2. Overriding the Doget and Dopost methods

#3. Configuring the Web. xml file, configuring the servlet node

Myfirstservlet.java

 PackageCom.ibatis01.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classMyfirstservletextendsHttpServlet {protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.getwriter (). Append ("My frist servlet"); }         protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

Xml

...<servlet>    <Servlet-name>Myfirstservlet</Servlet-name>    <Servlet-class>Com.ibatis01.servlet.MyFirstServlet</Servlet-class>  </servlet>  <servlet-mapping>    <Servlet-name>Myfirstservlet</Servlet-name>    <Url-pattern>/myfirst</Url-pattern>  </servlet-mapping>...

Operation Result:

* * URL Match

Url-pattern Browser input

Exact Match/first Http://localhost:8080/day/first

/itcast/demo1 Http://localhost:8080/day/itcast/demo1

Fuzzy matching/* http://localhost:8080/day/any path

/itcast/* http://localhost:8080/day/itcast/arbitrary path

*. suffix name http://localhost:8080/day/any path. do

*.do

*.action

*.html (pseudo-static): Not a real static file

Default path [default path, minimal use]/Http://localhost:8080/day

Attention:

#1. The path is either/start or start, and the two cannot be mixed together.

#2. When multiple servlets are matched at the same time, the exact match takes precedence

#3. Default path: When the path does not match the URL path of any custom servlet, go to Tomcat to find the corresponding static file under the application of Defaultservlet to the object, and if you cannot find it, return 404 Not found[Find the dynamic resource first, then find the static file ]

* * The life cycle of the servlet

Construction method: Called when the servlet is first accessed

Init method: Called when the servlet is finished creating

Service method: called at each request

Destroy method: Called when the servlet is destroyed

Attention:

#1. The service method was originally used to distribute calls to the Dopost method or the Doget method, and if we override the service method, the Doget or Dopost method is not called.

#2. The Init method has parameters and no parameters of the two methods, the parameters of the fact will be called no argument, so the Servlet method initialization code is written in the parameterless Init method can be

#3. Servlet objects are single-instance multithreading in Tomcat [Servlet definitely uses multithreading]

 PackageCom.ibatis01.servlet;Importjava.io.IOException;ImportJavax.servlet.ServletConfig;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse, Publicclass myfirstservletextendsHttpServlet {/*** Construction Method*/     PublicMyfirstservlet () {System.out.println ("1. I was created ..."); }       /*** Init method*/@Override Public voidInit (servletconfig config)throwsservletexception {System.out.println ("2. Init method is called ..."); }       /*** Service Method*/@Overrideprotected voidService (HttpServletRequest arg0, HttpServletResponse arg1)throwsservletexception, IOException {System.out.println ("3. Service method is called ..."); } @Override Public voiddestroy () {System.out.println ("4. Call the Destroy method ..."); }       protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("The Doget method is called ..."); Response.getwriter (). Append ("My frist servlet"); }     protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("The DoPost method is called ...");    Doget (request, response); }} 

* * Automatic loading of servlets

Add Load-on-startup in Web. XML [the higher the value in the middle, the lower the priority]

<servlet>    <Servlet-name>Myfirstservlet</Servlet-name>    <Servlet-class>Com.ibatis01.servlet.MyFirstServlet</Servlet-class>    <!--let the servlet create the server when it is started -    <Load-on-startup>1</Load-on-startup>  </servlet>

* * Thread safety issues for Servlets

Because Servlets are single-instance multithreading, it is possible to cause multithreading problems!

 PackageCom.ibatis01.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classThreadservletextendsHttpServlet {Private intNum=0; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try{num++; Thread.Sleep (2000); Response.getwriter (). Append ( This. toString () + "<br/>"). Append ("num=" +num); } Catch(interruptedexception e) {e.printstacktrace (); }                }         protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}


The result: [There is a problem to ask]

You can fix the problem by locking it up.

 PackageCom.ibatis01.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classThreadservletextendsHttpServlet {Private intnum = 0; protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {synchronized( This) {                            Try{num++; Thread.Sleep (2000); Response.getwriter (). Append ( This. toString () + "<br/>"). Append ("num=" +num); } Catch(interruptedexception e) {e.printstacktrace (); }                   }         }          protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

Java Web-----servlet

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.