Java Web Note 1. Servlet details: javawebservlet

Source: Internet
Author: User

Java Web Note 1. Servlet details: javawebservlet
1. Create a simple Servlet implementation class. 1. Create a HelloServlet class (test the Servlet interface method)

1 // create a HelloServlet class and implement Servlet interface 2 public class HelloServlet implements Servlet {3 4 // destroy method of Servlet when Tomcat stops Service 5 @ Override 6 public void destroy () {7 System. out. println ("destroy ..... "); 8} 9 10 @ Override11 public ServletConfig getServletConfig () {12 System. out. println ("getServletConfig"); 13 return null; 14} 15 16 @ Override17 public String getServletInfo () {18 System. out. println ("getServletInfo"); 19 return null; 20} 21 22 // Servlet loading Initialization Method 23 @ Override24 public void init (ServletConfig servletConfig) throws ServletException {25 System. out. println ("init"); 26} 27 28 // servlet runtime method each request calls 29 @ Override30 public void service (ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {31 System. out. println ("service"); 32} 33 34 // the construction method of the HelloServlet implementation class is called 35 public HelloServlet () {36 System. out. println ("HelloServlet's constructor"); 37} 38 39}
2. Configure and map Servlet
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 <! -- Configure and map Servlet --> 8 <servlet> 9 <! -- Servlet registration name --> 10 <servlet-name> HelloServlet_java </servlet-name> 11 <! -- Complete Servlet class name --> 12 <servlet-class> com. panku. javaWeb1.HelloServlet </servlet-class> 13 <! -- Specify the time when the Servlet is created --> 14 <load-on-startup> 1 </load-on-startup> 15 </servlet> 16 17 <servlet-mapping> 18 <! -- Must be consistent with the text node of the Servlet-name subnode of a servlet node --> 19 <servlet-name> HelloServlet_java </servlet-name> 20 <! -- Specific access path of the ing:/Represents the root directory of the current Web application. --> 21 <url-pattern>/hello </url-pattern> 22 </servlet-mapping> 23 24 </web-app>

 

Ii. Servlet lifecycle Methods: The following methods are called by the Serlvet container.

1). constructor: called only once. The Servlet instance is created only when the Servlet is requested for the first time. The constructor is called. This indicates the single instance of Serlvet!

2). init method: called only once. Called immediately after the instance is created. used to initialize the current Servlet.

3). service: it is called multiple times. The service method will be called each request. actually used to respond to the request.

4). destroy: called only once. called before the WEB application of the current Servlet is detached. Used to release resources occupied by the current Servlet.

Iii. ServletConfig object (getInitParameterNames, getInitParameter, getServletName (not commonly used), and getServletContext) 1. Configure the servlet initialization parameter (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 <! -- Configure and map Servlet --> 8 <servlet> 9 <! -- Servlet registration name --> 10 <servlet-name> HelloServlet_java </servlet-name> 11 <! -- Complete Servlet class name --> 12 <servlet-class> com. panku. javaWeb1.HelloServlet </servlet-class> 13 14 <! -- Configure Servlet initialization parameters --> 15 <init-param> 16 <! -- Parameter name --> 17 <param-name> user </param-name> 18 <! -- Parameter value --> 19 <param-value> root </param-value> 20 </init-param> 21 22 <init-param> 23 <param-name> password </param-name> 24 <param-value> 123456 </param-value> 25 </init-param> 26 27 <! -- Specify the time when the Servlet is created --> 28 <load-on-startup> 1 </load-on-startup> 29 </servlet> 30 31 <servlet-mapping> 32 <! -- It must be consistent with the text node of the Servlet-name subnode of a servlet node --> 33 <servlet-name> HelloServlet_java </servlet-name> 34 <! -- Specific access path of the ing:/Represents the root directory of the current Web application. --> 35 <url-pattern>/hello </url-pattern> 36 </servlet-mapping> 37 38 </web-app>

 

2. Examples of the ServletConfig object instance (getInitParameterNames, getInitParameter, and getServletName (not commonly used) in the init () method of the servlet implementation class)
1 // Servlet initialization method 2 @ Override 3 public void init (ServletConfig servletConfig) throws ServletException {4 System. out. println ("init"); 5 6 // get the initialization parameter value 7 String user = servletConfig. getInitParameter ("user"); 8 System. out. println ("user:" + user); 9 10 // obtain the initialization parameter name and value 11 Enumeration <String> names = servletConfig. getInitParameterNames (); 12 while (names. hasMoreElements () {13 String name = names. nextElement (); 14 String value = servletConfig. getInitParameter (name); 15 System. out. println ("^ name:" + name + ":" + value); 16} 17 18 // get the Servlet registration name 19 String servletName = servletConfig. getServletName (); 20 System. out. println (servletName); 21}

 

3. Use the ServletConfig object in the init () method of the servlet implementation class to obtain the ServletContext object's common methods: getInitParameter (), getInitParameterNames (), getRealPath (), getContextPath (), getResourceAsStream ()
1 // Servlet initialization method 2 @ Override 3 public void init (ServletConfig servletConfig) throws ServletException {4 System. out. println ("init"); 5 6 // WEB initialization parameters: can be obtained by all Servlets, while Servlet initialization parameters can be obtained only by the Serlvet. 7 // obtain the ServletContext object 8 ServletContext servletContext = servletConfig. getServletContext (); 9 10 // get the current WEB initialization parameter value 11 String driver = servletContext. getInitParameter ("driver"); 12 System. out. println ("driver:" + driver); 13 14 // get the current WEB initialization parameter name and Value 15 Enumeration <String> name2 = servletContext. getInitParameterNames (); 16 while (name2.hasMoreElements () {17 String name = name2.nextElement (); 18 String value = servletContext. getInitParameter (name); 19 System. out. println ("-->" + name + ":" + value); 20} 21 22 // obtain the absolute path of a file of the current WEB application on the server, instead of the pre-deployment path 23 String realPath = servletContext. getRealPath ("/111.txt"); 24 // not E: \ eclipse \ workspace \ JavaWeb \ WebContent \ 111.txt 25 System. out. println (realPath); 26 27 // obtain the name of the current WEB application 28 String contextPath = servletContext. getContextPath (); 29 System. out. println (contextPath); 30 31 // get the input stream of a file (path before deployment) 32 try {33 ClassLoader classLoader = getClass (). getClassLoader (); 34 InputStream is = classLoader. getResourceAsStream ("jdbc. properties "); 35 System. out. println ("1. "+ is); 36} catch (Exception e) {37 e. printStackTrace (); 38} 39 40 // get the input stream of a file (path on the server) 41 try {42 InputStream is2 = servletContext. getResourceAsStream ("/WEB-INF/classes/jdbc. properties "); 43 System. out. println ("2. "+ is2); 44} catch (Exception e) {45 e. printStackTrace (); 46} 47}
Iv. Request object in service () method of servlet implementation Class 1. Common Request Methods: getParameter (String name), getParameterValues (String name), getParameterNames (), getParameterMap ()
1 // used to respond to a request: because each request will call the service () method 2 // ServletRequest: encapsulates the request information and can obtain any request information. 3 // ServletResponse: the response information is encapsulated. If you want to give the user a response, you can use this interface to implement 4 @ Override 5 public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException {6 System. out. println ("the request is successful ....... "); 7 System. out. println (request); 8 9 // String getParameter (String name): return the parameter value based on the request parameter name. 10 String user = request. getParameter ("user"); 11 String password = request. getParameter ("password"); 12 System. out. println (user + "," + password); 13 14 // The getParameter () method can only get one parameter value 15 String interesting = request. getParameter ("interesting"); 16 System. out. println (interesting); 17 18 // String [] getParameterValues (String name): returns the String array 19 String [] interestings = request. getParameterValues ("interesting"); 20 for (String string: interestings) {21 System. out. println ("-->" + string); 22} 23 24 // Enumeration getParameterNames (): returns the Enumeration object corresponding to the parameter name, similar to 25 // ServletConfig (or ServletContext) getInitParameterNames () method. 26 Enumeration <String> names = request. getParameterNames (); 27 while (names. hasMoreElements () {28 String name = names. nextElement (); 29 String valuee = request. getParameter (name); 30 System. out. println ("=>" + name + "," + valuee); 31} 32 33 // Map getParameterMap (): return the key-value pair of the request parameter: key: parameter Name, value: parameter value, String array type. 34 Map <String, String []> map = request. getParameterMap (); 35 for (Map. entry <String, String []> entry: map. entrySet () {36 System. out. println ("**" + entry. getKey () + ":" + Arrays. asList (entry. getValue (); 37} 38}

 

2. Common Methods of httpServletRequest: getRequestURI (), getMethod (), getQueryString (), getServletPath ()
1 public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException {2 System. out. println ("the request is successful ....... "); 3 System. out. println (request); 4 // obtain the requested URI 5 HttpServletRequest httpServletRequest = (HttpServletRequest) request; 6 String requestURI = httpServletRequest. getRequestURI (); 7 System. out. println (requestURI); 8 9 // obtain the Request method 10 String method = httpServlet Request. getMethod (); 11 System. out. println (method); 12 13 // if it is a GET Request, obtain the string corresponding to the Request parameter, that is? The string. 14 String queryString = httpServletRequest. getQueryString (); 15 System. out. println (queryString); 16 17 // gets the ing path of the request's Serlvet 18 String servletPath = httpServletRequest. getServletPath (); 19 System. out. println (servletPath); 20}

 

5. The Response object Response in the service () method of the servlet implementation class currently commonly used methods: setContentType (), getWriter ()
1 public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException {2 System. out. println ("the request is successful ....... "); 3 System. out. println (request); 4 // set the response Method 5 response. setContentType ("application/msword"); 6 7 // response to a content on the page 8 PrintWriter out = response. getWriter (); 9 out. println ("HelloWorld... "); 10}
6. GenericServlet implements the Servelt and ServletConfig Interfaces
1 public abstract class MyGenericServlet implements Servlet, ServletConfig {2 3 // The following method is the Servlet Interface Method 4 @ Override 5 public void destroy () {6} 7 8 @ Override 9 public ServletConfig getServletConfig () {10 return servletconfig; 11} 12 13 @ Override14 public String getServletInfo () {15 return null; 16} 17 18 private ServletConfig servletconfig; 19 20 @ Override21 public void init (ServletConfig arg0) throws ServletException {22 this. servletconfig = arg0; 23 init (); 24} 25 26 public void init () throws ServletException {27} 28 29 @ Override30 public abstract void service (ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException; 31 32 // The following method is the ServletConfig Interface Method 33 @ Override34 public String getInitParameter (String arg0) {35 return servletconfig. getInitParameter (arg0); 36} 37 38 @ Override39 public Enumeration <String> getInitParameterNames () {40 return servletconfig. getInitParameterNames (); 41} 42 43 @ Override44 public ServletContext getServletContext () {45 return servletconfig. getServletContext (); 46} 47 48 @ Override49 public String getServletName () {50 return servletconfig. getServletName (); 51} 52 53}
View Code

 

 

 

VII. inherit the GenericServlet class from HttpServlet
1 public class MyHttpServlet extends MyGenericServlet {2 3 @ Override 4 public void service (ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {5 6 if (arg0 instanceof HttpServletRequest) {7 HttpServletRequest request = (HttpServletRequest) arg0; 8 9 if (arg1 instanceof HttpServletResponse) {10 HttpServletResponse response = (HttpServletResponse) arg1; 11 12 service (request, response ); 13} 14} 15} 16 17 public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {18 19 // 1. request method 20 String method = request. getMethod (); 21 22 // 2. call the corresponding processing method based on the Request Method 23 if ("get ". inclusignorecase (method) {24 doGet (request, response); 25} else if ("set ". inclusignorecase (method) {26 doPost (request, response); 27} 28} 29 30 public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {31 32} 33 34 public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {35 36} 37 38}
View Code

 

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.