Java Web Learning Summary (II)-Servlet and javawebservlet

Source: Internet
Author: User

Java Web Learning Summary (II)-Servlet and javawebservlet
1. Servlet Overview 1. What is Servlet?

Servlet is JavaWebOne of the three major componentsIt is a dynamic resource. Servlet is used to process requests. The server will send the received requests to the Servlet for processing. In Servlet, it usually needs:

  • Receive request data;
  • Process requests;
  • Complete the response.

For example, when a client sends a login request or an output registration request, all these requests should be handled by the Servlet! Servlet needs to be compiled by ourselves. Each Servlet must implement the javax. servlet. Servlet interface.

2. Servlet implementation

Servlet can be implemented in three ways:

  • Implement the javax. servlet. Servlet interface;
  • Inherit the javax. servlet. GenericServlet class;
  • Inherit the javax. servlet. http. HttpServlet class;

Servlet. java

1 public interface Servlet {2     public void init(ServletConfig config) throws ServletException;3     public ServletConfig getServletConfig();4     public void service(ServletRequest req, ServletResponse res)5             throws ServletException, IOException;6     public String getServletInfo();7     public void destroy();8 }

Most methods in Servlet are called by Tomcat rather than by us. In addition, Servlet objects cannot be created by us. Tomcat creates Servlet objects!

3. Create a helloservlet Application

Let's start the first Servlet application! First, create the helloservlet directory under the webapps Directory, which is our application directory, and then create the content required for the JavaWeb application in the helloservlet directory:

  • Create/helloservlet/WEB-INF directory;
  • Create the/helloservlet/WEB-INF/classes directory;
  • Create the/helloservlet/WEB-INF/lib directory;
  • Create/helloservlet/WEB-INF/web. xml file;

 

Next, we start to prepare and complete the Servlet. The Servlet can be completed in two steps:

  • Compile the Servlet class;
  • Configure Servlet in the web. xml file;

HelloServlet. java

public class HelloServlet implements Servlet {    public void init(ServletConfig config) throws ServletException {}    public ServletConfig getServletConfig() {return null;}    public void destroy() {}    public String getServletInfo() {return null;}    public void service(ServletRequest req, ServletResponse res)            throws ServletException, IOException {        System.out.println("hello servlet!");    }}

We temporarily ignore the four other methods in Servlet and only care about the service () method, because it is used to process the request. An output statement is provided in this method!

 

Web. xml

<servlet>    <servlet-name>hello</servlet-name>    <servlet-class>com.jana.servlet.HelloServlet</servlet-class></servlet><servlet-mapping>    <servlet-name>hello</servlet-name>    <url-pattern>/helloworld</url-pattern></servlet-mapping> 

In the web. the purpose of configuring Servlet in xml is to bind the access path with a Servlet. The above configuration is to bind the access path "/helloworld" and "com. jana. servlet. helloServlet "is bound together.

  • <Servlet>: Specify HelloServlet as hello;
  • <Servlet-mapping>: Specify the/helloworld access path, so the name of the accessed Servlet is hello.

<Servlet> and <servlet-mapping> are associated with each other through the <servlet-name> element!

Next, we compile HelloServlet, note that the servlet-api.jar needs to be imported when compiling HelloServlet, because Servlet. class and other classes are in the servlet-api.jar.

Javac-classpath F:/tomcat6/lib/servlet-api.jar-d. HelloServlet. java

Then put HelloServlet. class put in the/helloworld/WEB-INF/classes/directory, and then start Tomcat, access in the browser: http: // localhost: 8080/helloservlet/helloworld can be seen in the console output!

  • /Helloservlet/WEB-INF/classes/com/jana/servlet/HelloServlet. class;

 

Ii. Servlet Interface 1. ServletLifecycle

Lifecycle method:

  • Void init (ServletConfig): after birth (once );
  • Void service (ServletRequest request, ServletResponse response): it is called every time a request is processed;
  • Void destroy (): Before death (1 time );

Features:

  • For example, a class has only one object. Of course, there may be multiple Servlet classes!
  • The thread is not case-insensitive, so its efficiency is high!

The Servlet class is written by us, but the object is created by the server and the server calls the corresponding method.

1.1 create Servlet

The server creates a Servlet when the Servlet is accessed for the first time or when the server is started. If the Servlet is created when the server is started, you need to configure it in the web. xml file. That is to say, by default, the Servlet is created by the server when it is accessed for the first time.

In addition, for a Servlet type, the server only creates one instance object. For example, when we first access http: // localhost: 8080/helloservlet/helloworld, the server finds the bound Servlet name com through "/helloworld. jana. servlet. helloServlet. Then, the server will check whether this type of Servlet has been created. If not, the server will create a HelloServlet instance through reflection. When we access http: // localhost: 8080/helloservlet/helloworld again, the server will not create a HelloServlet instance again, but will directly use the instance created last time.

After the Servlet is created, the server immediately calls the Servlet's void init (ServletConfig) method and calls it only once.

1.2 Servlet Service

Each time the server receives a request, it will call the Servlet service () method to process the request. When the server receives a request, the service () method is called once. Therefore, the service () method is called multiple times.

1.3 destroy Servlet

Servlet is not easy to leave, usually when the server is closed, the Servlet will leave! When the server is shut down, the server will destroy the Servlet. Before the Servlet is destroyed, the server will call the destroy () method of the Servlet first. We can put the last words of the Servlet in destroy () method, such as releasing some resources and other code into the destroy () method.

2. Servlet interface-related types
  • ServletRequest: the parameter of the service () method. It indicates the request object. It encapsulates all request-related data and is created by the server;
  • ServletResponse: the parameter of the service () method, which indicates the response object. This object is used to complete the response to the client in the service () method;
  • ServletConfig: the parameter of the init () method. It indicates the Servlet configuration object. It corresponds to the Servlet configuration information, which corresponds to the <servlet> element in the web. xml file.
2.1 ServletRequest and ServletResponse

ServletRequest and ServletResponse are two parameters of the Servlet # service () method. One is the request object and the other is the response object. You can obtain the request data from the ServletRequest object and use the ServletResponse object to complete the response.

The instances of ServletRequest and ServletResponse are created by the server and passed to the service () method. If you want to use HTTP-related functions in the service () method, you can convert ServletRequest and ServletResponse to HttpServletRequest and HttpServletResponse.

HttpServletRequest method:

  • String getParameter (String paramName): obtains the value of the specified request parameter;
  • String getMethod (): GET request method, such as GET or POST;
  • String getHeader (String name): obtains the value of the specified request header;
  • Void setCharacterEncoding (String encoding): sets the Request body encoding! Because the GET request does not have a request body, this method is only valid for POST requests. When request. setCharacterEncoding ("UTF-8") is called and the parameter value is obtained through the getParameter () method, the parameter values have been transcoded, that is, converted to UTF-8 encoding. Therefore, this method must be called before the getParameter () method is called!

HttpServletResponse method:

  • PrintWriter getWriter (): gets the character response stream, which can be used to output response information to the client. For example, response. getWriter (). print ("
  • ServletOutputStream getOutputStream (): obtains the byte response stream. This stream is used when you need to respond to byte data from the client. For example, you need to respond to an image from the client;
  • Void setCharacterEncoding (String encoding): used to set the encoding of the character response stream. For example, after setCharacterEncoding ("UTF-8") is called, then response. getWriter () obtains the character response Stream object. In this case, the response stream is encoded as UTF-8 and the response stream is used. the Chinese output by getWriter () will be converted to UTF-8 encoding and sent to the client;
  • Void setHeader (String name, String value): Add response header information to the client, such as setHeader ("Refresh", "3; url = http://www.baidu.com "), indicates that the http://www.baidu.com is automatically refreshed 3 seconds later;
  • Void setContentType (String contentType): This method is a simple method of setHeader ("content-type", "xxx"). It is used to add a method named content-type response header. The content-type response header is used to set the MIME type of the response data. For example, if you want to return a jpg image to the client, you can setContentType ("image/jepg"). If the response data is of the text type, set the encoding at the same time. For example, setContentType ("text/html; chartset = UTF-8") indicates that the response data type is html in the text type, the setCharacterEncoding ("UTF-8") method is called;
  • Void sendError (int code, String errorMsg): sends the status code and error message to the client. For example, send 404: response (404, "The resource you want to search for does not exist!") to the client !").
2.1 ServletConfig

The ServletConfig object corresponds to the <servlet> element in the web. xml file. For example, if you want to obtain the configuration name of the current Servlet in the web. xml file, you can use the servletConfig. getServletName () method to obtain it!

The ServletConfig object is created by the server and passed to the Servlet init () method. You can use it in the init () method!

  • String getServletName (): gets the configuration name of the Servlet in the web. xml file, that is, the name specified by <servlet-name>;
  • ServletContext getServletContext (): used to obtain the ServletContext object;
  • String getInitParameter (String name): used to obtain the initialization parameters configured in web. xml, and get the parameter value through the parameter name;
  • Enumeration getInitParameterNames (): used to obtain all the initialization parameter names configured in web. xml;

You can also configure initialization parameters in the <servlet> element:

  <servlet>    <servlet-name>One</servlet-name>    <servlet-class>com.jana.servlet.OneServlet</servlet-class>    <init-param>          <param-name>paramName1</param-name>            <param-value>paramValue1</param-value>    </init-param>    <init-param>            <param-name>paramName2</param-name>            <param-value>paramValue2</param-value>    </init-param>  </servlet>

In OneServlet, you can use the getInitParameter () method of the ServletConfig object to obtain the initialization parameters.

For example, String value1 = servletConfig. getInitParameter ("paramName1"); // obtain paramValue1

 

3. GenericServlet

GenericServlet is the implementation class of Servlet interfaces. We can compile our own Servlet by inheriting GenericServlet.

1. init () method of GenericServlet

In GenericServlet, A ServletConfig config instance variable is defined, and the parameter ServletConfig is assigned to the instance variable in the init (ServletConfig) method. Then, the instance variable config is used in many methods of this class.

If the subclass overwrites the init (StringConfig) method of GenericServlet, then this. the config = config statement will be overwritten. That is to say, if the config value of the GenericServlet instance variable is null, all methods dependent on config cannot be used. If you really want to complete some initialization operations, overwrite the init () method provided by GenericServlet. It is the init () method without parameters, and it will be in init (ServletConfig) method.

2. Implemented the ServletConfig Interface

GenericServlet also implements the ServletConfig interface, so you can directly call ServletConfig methods such as getInitParameter () and getServletContext.

 

4. HttpServlet

The HttpServlet class is a subclass of GenericServlet. It provides special support for HTTP requests. Therefore, we usually inherit HttpServlet to complete custom servlets.

1. HttpServlet overwrites the service () method

The HttpServlet class provides the service (HttpServletRequest, HttpServletResponse) method, which is the method of HttpServlet itself, not inherited from Servlet. In the service (ServletRequest, ServletResponse) method of HttpServlet, ServletRequest and ServletResponse are converted into HttpServletRequest and HttpServletResponse, and then the service (HttpServletRequest, HttpServletResponse) method is called, this means that the subclass can override the service (HttpServletRequest, HttpServletResponse) method, so you do not need to forcibly convert the request and response object.

2. doGet () and doPost ()

The HttpServlet service (HttpServletRequest, HttpServletResponse) method will determine whether the current request is GET or POST. If it is a GET request, it will call the doGet () method of this class, if it is a POST request, the doPost () method will be called, which means we can override the doGet () or doPost () method in the subclass.

5. Servlet details 1. Servlet and thread security

Because a type Servlet has only one instance object, it is possible that a Servlet can process multiple requests at the same time. Is the Servlet thread safe? The answer is "Not thread-safe ". This shows that Servlet is very efficient, but there are also thread security problems!

Therefore, we should not create a member variable cheaply in the Servlet, because one thread may write this member variable, and the other thread may read this member variable.

2. Let the server create a Servlet at startup

By default, the server creates a Servlet when it receives the request for the first time. You can also configure the Servlet in web. xml so that the Servlet is created when the server is started.

    <servlet>        <servlet-name>hello1</servlet-name>        <servlet-class>com.jana.servlet.Hello1Servlet</servlet-class>        <load-on-startup>0</load-on-startup>    </servlet>

Configure the <load-on-startup> element in the <servlet> element so that the server can create the Servlet at startup, the value of the <load-on-startup> element must be an integer greater than or equal to that of the Servlet created at server startup.

3. <url-pattern>

<Url-pattern> is a child element of <servlet-mapping>. It is used to specify the Servlet access path, that is, the URL. It must start!

1) You can provide multiple <url-pattern> in <servlet-mapping>, for example:

  <servlet-mapping>    <servlet-name>AServlet</servlet-name>    <url-pattern>/AServlet</url-pattern>    <url-pattern>/BServlet</url-pattern>  </servlet-mapping>  

In this case, a Servlet is bound to two URLs, no matter whether it accesses/AServlet or/BServlet, It accesses AServlet.

2) You can also use wildcards in <url-pattern>. The wildcard is the asterisk (*). The asterisk can match any URL prefix or suffix, you can use wildcards to name a Servlet and bind a group of URLs. For example:

  • <Url-pattern>/servlet/* <url-patter>:/servlet/a,/servlet/B, all match/servlet /*;
  • <Url-pattern> *. do </url-pattern>:/abc/def/ghi. do,/a. do, all match *. do;
  • <Url-pattern>/* <url-pattern>: matches all URLs;

Note that the wildcard character is either a prefix or a suffix and cannot appear in the middle of the URL or only a wildcard character. For example,/*. do is incorrect because the asterisk appears in the middle of the URL. *. * This is also incorrect because only one wildcard can appear in a URL.

Wildcard is a fuzzy match of URLs. If more specific <URL-pattern> exists, the access path matches the specific <url-pattern>

4. Inheritance of web. xml files

The content in $ {CATALINA_HOME} \ conf \ web. xml is equivalent to being written to the web. xml of each project. It is the parent file of all web. xml files.

Each Complete Java web application requires a web. xml, but we do not know all the web. xml files all have a common parent file, which is stored in the conf/web. xml Path.

Vi. ServletContext

The server creates a ServletContext object for each application:

  • The creation of the ServletContext object is completed at server startup;
  • The destruction of the ServletContext object is completed when the server is shut down.

The ServletContext object is used to share data between dynamic resources of the entire Web application! For example, in AServlet, save a value to the ServletContext object, and then obtain the value in BServlet. This is shared data.

1. Get ServletContext
  • ServletConfig # getServletContext ();
  • GenericServlet # getServletContext ();
  • HttpSession # getServletContext ()
  • ServletContextEvent # getServletContext ()
2. Functions of domain objects

ServletContext is one of the four fields of JavaWeb:

  • PageContext;
  • ServletRequest;
  • HttpSession;
  • ServletContext;

All domain objects have the ability to access data, because the domain object contains a Map to store data. The following describes how the ServletContext object operates data:

  • Void setAttribute (String name, Object value): used to store an Object. It can also be called to store a domain attribute, for example, servletContext. setAttribute ("xxx", "XXX") saves a domain attribute in ServletContext. The domain attribute name is xxx and the domain attribute value is XXX. If this method is called multiple times and the same name is used, the previous value will be overwritten, which is the same as Map;
  • Object getAttribute (String name): used to obtain data in ServletContext. Currently, you must store the data before obtaining the data. For example, String value = (String) servletContext. getAttribute ("xxx");, get the domain attribute named xxx;
  • Void removeAttribute (String name): used to remove the domain attribute in ServletContext. If the domain attribute specified by the parameter name does not exist, this method will not do anything;
  • Enumeration getAttributeNames (): obtains the names of all domain attributes;
3. Get app initialization parameters
  • Servlet can also get initialization parameters, but it is a local parameter. That is to say, a Servlet can only get its own initialization parameters, but cannot get others. That is, the initialization parameters are only prepared for a Servlet!
  • Public initialization parameters can be configured for all servlets! This requires ServletContext!

You can also use ServletContext to obtain the app initialization parameters configured in the web. xml file! Note that the application initialization parameters are different from the Servlet initialization parameters:

 

<web-app ...>  ...  <context-param>    <param-name>paramName1</param-name>    <param-value>paramValue1</param-value>        </context-param>  <context-param>    <param-name>paramName2</param-name>    <param-value>paramValue2</param-value>        </context-param></web-app>
1 ServletContext context = this.getServletContext();2 String value1 = context.getInitParameter("paramName1");3 String value2 = context.getInitParameter("paramName2");4 System.out.println(value1 + ", " + value2);5 6 Enumeration names = context.getInitParameterNames();7 while(names.hasMoreElements()) {8     System.out.println(names.nextElement());9 }
4. Methods for obtaining resources

You can also use the servletcontextobject to obtain resources under the web application. For example, if you create an a.txt file under the root directory of the helloapplication, you can use ServletContext to obtain the resource from the Servlet.

 

4.1. Obtain the real path

  • The actual path of a.txt is obtained: String realPath = servletContext. getRealPath ("/a.txt”), the value of realpathis the absolute path of a.txt file: F: \ tomcat6 \ webapps \ hello \ a.txt;
  • The actual path of B .txt: String realPath = servletContext. getRealPath ("/WEB-INF/B .txt ");

4.2. Obtain the resource stream

You can not only obtain the resource path, but also obtain the resource stream through ServletContext, that is, the resource is obtained as an input stream:

  • Obtained a.txt resource stream: InputStream in = servletContext. getResourceAsStream ("/a.txt ");
  • B .txt resource stream: InputStream in = servletContext. getResourceAsStream ("/WEB-INF/B .txt ");

4.3. Obtain all resource paths in the specified directory

You can also use ServletContext to retrieve all resource paths under a specified directory, such as paths for all resources under/WEB-INF:

Set set = context.getResourcePaths("/WEB-INF");        System.out.println(set);

Output: [/WEB-INF/lib/,/WEB-INF/classes/,/WEB-INF/B .txt,/WEB-INF/web. xml]

Note: This method must start!

 

Related Article

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.