Javaweb Note One, Servlet detailed

Source: Internet
Author: User

First, create a servlet simple implementation Class 1, create a HelloServlet class (Test Servlet interface method)
1//Create a HelloServlet class and implement the Servlet Interface 2 public class HelloServlet implementsservlet {3 4//Tomcat Destroy method when stopping service 5@Override 6 public voidDestroy () {7 System.out.println ("Destroy ...")); 8} 9  @Override11 public  servletconfig getservletconfig () {System.out.println ("Getservletconfig ), return null , }15  @Override17 public  String getservletinfo () {System.out.prin TLN ("Getservletinfo" ); null ; }21//Servlet load-time initialization method  @Override24 public void in It (ServletConfig servletconfig) throws  servletexception {System.out.println ("init" ),}27 28// The Servlet runtime method calls the  @Override30 public void Service (ServletRequest arg0, Servletresponse arg1) throws  Ser for each request Vletexception, IOException {System.out.println ("service" ); }33//HelloServlet Implementation class constructor method is called when loading publ IC  HelloServlet () {System.out.println ("HelloServlet ' constructor" ), Panax Notoginseng }38,   span>                 
2. Configuring and Mapping Servlets
 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 3 Xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "5 id=" webapp_id "version=" 3.1 "> 6 7 <!--configuration and mapping Servlet-- 8 <servlet> 9 <!--servlet registered name-->10 <servlet-name>helloservlet_java</servlet-n Ame>11 <!--Servlet Full-class name-->12 <servlet-class>com.panku.javaweb1.helloservlet</servlet-c Lass>13 <!--can specify the time that the Servlet was created-->14 <load-on-startup>1</load-on-startup>15 &lt         ;/servlet>16 <servlet-mapping>18 <!--need to be consistent with the text nodes of a servlet-name child node of a servlet node-->19 &LT;SERVLET-NAME&GT;HELLOSERVLET_JAVA&LT;/SERVLET-NAME&GT;20 <!--Map specific access path:/represents the root directory of the current Web app. -->21 <url-pattern>/hello</Url-pattern>22 </servlet-mapping>23 </web-app> 

Second, the servlet life cycle servlet Lifecycle method: The following methods are called by the Serlvet container.

1). Constructor: called only once. An instance of the servlet is created only the first time the servlet is requested. Invokes the constructor. This shows a single instance of Serlvet!

2). Init method: called only once. Called immediately after a good instance has been created. Used to initialize the current Servlet.

3). Service: called multiple times. Each request invokes the service method. Actually used in response to a request.

4). Destroy: Called only once. Called before the WEB app where the current Servlet resides is unloaded. Used to release resources occupied by the current Servlet.

Third, ServletConfig objects (Getinitparameternames, Getinitparameter, getservletname (infrequently used), Getservletcontext four interface methods) 1, in Configuration of the servlet's initialization parameters (Init-param node) in the Web. xml file
 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 3 Xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "5 id=" webapp_id "version=" 3.1 "> 6 7 <!--configuration and mapping Servlet-- 8 <servlet> 9 <!--servlet registered name-->10 <servlet-name>helloservlet_java</servlet-n Ame>11 <!--Servlet Full-class name-->12 <servlet-class>com.panku.javaweb1.helloservlet</servlet-c             Lass>13 <!--Configure the Servlet's initialization parameters-->15 <init-param>16 <!--parameter name-->17 <param-name>user</param-name>18 <!--parameter values-->19 <param-value>root& Lt;/param-value>20 </init-param>21 <init-param>23 <param-name>password </param-name>24 &Lt;param-value>123456</param-value>25 </init-param>26 <!--You can specify the time that the Servlet was created--         <load-on-startup>1</load-on-startup>29 </servlet>30 <servlet-mapping>32 <!--need to be consistent with the text nodes of a servlet-name child node of a Servlet node-->33 <servlet-name>helloservlet_java</servlet- Name>34 <!--Map specific access path:/represents the root directory of the current Web app. -->35 <url-pattern>/hello</url-pattern>36 </servlet-mapping>37 </web-app>

2. ServletConfig object instances in the Init () method of the Servlet implementation class (ServletConfig Getinitparameternames, Getinitparameter, Getservletname ( Infrequently used) method instances)
1         @Override 3 public     void init (ServletConfig servletconfig) throws servletexception {4         System.out.println ("Init"); 5  6         //Get initialization parameter value 7         String user = Servletconfig.getinitparameter ("User" ); 8         System.out.println ("User:" + user); 9         //Get initialization parameter name and value one by one         enumeration<string> names = servletconfig.getinitparameternames (); (Names.hasmoreelements ()) {string name = names.nextelement (); string value =  Servletconfig.getinitparameter (name); System.out.println ("^^ Name:" + name + ":" + }17 18//Get Servlet register name Strin G Servletname = System.out.println (servletname);         

3, in the Servlet implementation class of the Init () method through the ServletConfig object to get ServletContext object ServletContext Common method: Getinitparameter (), Getinitparameternames (), Getrealpath (), Getcontextpath (), getResourceAsStream ()
1//Servlet load-time initialization Method 2@Override 3 public void init (ServletConfig servletconfig) throwsservletexception {4 System.out.println ("Init"); 5 6//Web initialization parameters: can be obtained for all servlets, while the servlet initialization parameters are available only with that Serlvet. 7//Get ServletContext object 8 ServletContext ServletContext =Servletconfig.getservletcontext (); 9 10//Gets the current WEB initialization parameter value one String driver = servletcontext.getinitparameter ("Driver"); System.out.println ("Driver:" +driver); 13 14//Gets the current WEB initialization parameter name and value of enumeration<string> name2 =Servletcontext.getinitparameternames ();(Name2.hasmoreelements ()) {String name =Name2.nextelement (); String value =Servletcontext.getinitparameter (name); System.out.println ("--" + name + ":" +value); 20}21 22//Gets the absolute path of a file on the server for the current WEB app, rather than the path before the deployment, String Realpath = Servletcontext.getrealpath ("/111.txt"); 24//Not E:\eclipse\workspace\JavaWeb\WebContent\111.txt25  System.out.println (Realpath); 26 27//Get current The name of the WEB app is String contextpath =  servletcontext.getcontextpath ();  System.out.println (ContextPath); 30 31 Gets the input stream of a file (the path before deployment): Try  {ClassLoader ClassLoader =  getclass (). getClassLoader (); InputStream is = CLA Ssloader.getresourceasstream ("Jdbc.properties" ), System.out.println ("1." +  is); Exception e) {PNS  e.printstacktrace (); }39 40//Gets the input stream of a file (path on the server) try  {InputStream Is2 = Serv Letcontext.getresourceasstream ("/web-inf/classes/jdbc.properties" ), System.out.println ("2." +  Is2); Exception} catch  (e) {e.printstacktrace  (); }47}       /span>          
The servlet implements the service () method of the class in Request object 1, the common method of Request: GetParameter (string name), Getparametervalues (string name), Getparameternames (), Getparametermap ()
1//For answering requests: Because each request invokes the service () Method 2//ServletRequest: Encapsulates the request information from which you can obtain any request Information 3//Servletresponse: Encapsulates the response letter If you want to respond to the user, you can use this interface method to achieve 4@Override 5 public void Service (ServletRequest request, servletresponse response) throwsServletexception, IOException {6 System.out.println ("Request succeeded ..."); 7SYSTEM.OUT.PRINTLN (Request); 8 9//String GetParameter (string name): Returns the parameter value based on the name of the request parameter. String user = Request.getparameter ("User"); String password = request.getparameter ("Password"); System.out.println (user + "," +Password//GetParameter () method can only get one parameter value, String interesting = Request.getparameter ("Interesting"); 16 System.out.println (interesting); +//string[] Getparametervalues (string name): Returns the string array corresponding to the request parameter according to the name of the request parameter. string[ ] Interestings = request.getparametervalues ("Interesting"); (string string:interestings) {System.out.println ("--" + string); }23//Enumeratio n Getparameternames (): Returns the enumeration object corresponding to the parameter name, similar to the Getinitparameternames () method of//ServletConfig (or ServletContext). E numeration<string> names = request.getparameternames (), while (Names.hasmoreelements ()) {-String Name = names.nextelement (), String valuee = request.getparameter (name), and System.out.println ("==>" + name + "," + valuee); }32//Map Getparametermap (): Returns the key-value pair for the request parameter: key: Parameter name, Value: Parameter value, String array type. map<string , string[]> map = request.getparametermap (); map.entry<string, string[]> Entry:map.entrySet ( ) {SYSTEM.OUT.PRINTLN ("* *" + entry.getkey () + ":" + Arrays.aslist (Entry.getvalue ())), PNs }38} /c11> 

Common methods of  2 and HttpServletRequest: Getrequesturi (), GetMethod (), getquerystring (), Getservletpath ()
1 Public     void Service (ServletRequest request, servletresponse response) throws Servletexception, IOException {2         System.out.println ("Request succeeded ..."        System.out.println); 4         //Get URI of the request 5         httpservletrequest httpservletrequest = (httpservletrequest) request; 6         String  RequestUri = System.out.println (requesturi); 8 9//Get Request Method Ten String method = System.out.println (method); 12 13// For a GET request, get the string that corresponds to the request parameter, that is? The string after it. String queryString = System.out.println (queryString); 16 17//Gets the mapped path of the requested Serlvet. String Servletpath =
             
               System.out.println (Servletpath); 
                  

V. The Response object in the service () method of the Servlet implementation class Response the current common method: setContentType (), getwriter ()
1 Public     void Service (ServletRequest request, servletresponse response) throws Servletexception, IOException {2         System.out.println ("Request succeeded ..."        System.out.println); 4         //Set Response 5         response.setcontenttype ("Application/msword"); 6  7         //Response one content in page 8         PrintWriter out = response.getwriter (); 9         out.println ("HelloWorld ...");    
Vi. Genericservlet implements Servelt, ServletConfig interfaceView Code

Vii. HttpServlet inherit Genericservlet classView Code

Javaweb Note One, Servlet detailed

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.