In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use Servlet, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
I. Overview of Servlet
Dynamic web resource development technology provided by 1.sun company. In essence, the previous paragraph of java Mini Program requires that this Mini Program must implement the Servlet interface so that the server can call it.
two。 Two steps to developing Servlet
* Lab: getting started with Servlet
(1) step 1: write a java program to implement the Servlet interface (here directly inherits the default implementation class GenericServlet)
Package cn.itheima;import java.io.*;import javax.servlet.*;public class FirstServlet extends GenericServlet {public void service (ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException {res.getOutputStream () .write ("My FirstServlet!" .getBytes ());}}
(2) put the compiled .class with package outside the WEB-INF/classes, and configure the web.xml registration Servlet of the web application
FirstServlet cn.itheima.FirstServlet FirstServlet / FirstServlet
3. Using MyEclipse to develop Servlet
Second, the detailed description of Servlet
1. Life cycle: when a thing is born, when it dies, and what it is bound to do during its existence, all taken together is the declaration cycle of that thing.
The life cycle of 2.Servlet: typically, the first time an servlet is accessed, an object is created in memory, and immediately after creation, the init () method is called for initialization. For each request, the service (req,resp) method is used instead, and the request information is encapsulated with a Request object, and the response message is represented by a Response object (initially empty), which is passed into the service method for use. When the service method is processed, the server returns the response message to the browser according to the information in the Response. After the response, the servlet is not destroyed and resides in memory waiting for the next request. Until the server shuts down or the web application is removed from the virtual host, the servlet object is destroyed and the destroy () method is called before it is destroyed to do something about it.
Inheritance structure of 3.Servlet interface
Servlet interface: defines a method that servlet should have, and all Servlet should implement this interface directly or indirectly
| |
| |-GenericServlet: the default implementation of the Servlet API, generic Servlet, which is an abstract class. Most of the methods are implemented by default, except that the service method is an abstract method that needs to be implemented by the inheritor. |
| |
|-HttpServlet: Servlet that optimizes the HTTP protocol, inherits from the GenericServlet class, and implements the service abstract method in it. The default implementation determines the request method and calls different doXXX () methods according to the request method. Usually we just inherit HttpServlet directly.
Considerations for 4.web.xml to register for Servlet
4.1 registering a Servlet with tags
FirstServlet cn.itheima.FirstServlet
Note: what you want here is the full class name of Servlet, not the file path that contains .java or .class extensions.
FirstServlet / FirstServlet
4.2 one can correspond to multiple
4.3 can be configured with a * match, but note that it must be a path that begins with * .do or ends with / *.
~ due to the introduction of matches, it is possible that a virtual path will correspond to multiple servlet-mapping, which one is the most likely to find which servlet, and the lowest level of * .do.
4.4 you can configure the subtag to specify that the servlet is loaded with the startup of the server, where the configured values specify the order in which to start
Servlet > invokerorg.apache.catalina.servlets.InvokerServlet2
4.5 default servlet: if a servlet's external access path is set to /, the servlet is the default servlet, which handles all other requests that servlet does not handle.
The default servlet is configured in conf/web.xml, and the access to static resources and the output of error pages are handled by this default servlet. If we write a default servlet that overrides the default servlet in Dad's web.xml, it will cause static web resources to be inaccessible. So configuration is not recommended.
Thread Safety of 4.6servlet
4.6.1 because normally, there is only one instance of a servlet in memory to process requests, when multiple requests are sent, multiple threads will operate on the servlet object, which may cause thread safety problems.
(1) the member variables of serlvet may have thread safety problems.
* experiment: define a member variable, inti=0;, to perform the "I" + operation in the doXXX () method and output the I value to the client. At this time, the delay may cause thread safety problems.
(2) when serlvet operates resource files, thread safety problems arise when multiple threads operate on the same file.
* experiment: the request comes with a parameter. Servlet writes the request parameter to a file, reads the file, and prints the read value to the client. There may be thread safety problems.
4.6.2 solution
(1) using synchronous code block to solve the problem. The defect is that the synchronization code block can only handle one request at a time, which is very inefficient, so the synchronization code block contains only the core code that causes thread safety problems.
(2) implement the SingleThreadModel interface for the servlet, which is a tagged interface. The marked servlet will save a servlet pool in memory. If a thread comes and there is no servlet object in the pool, create a new one. If there is a free servlet in the pool, use it directly. This does not really solve the thread safety problem. This interface has been deprecated.
(3) neither solution is perfect, so try not to have member variables in servlet.
III. ServletConfig
1. Objects that represent servlet configuration, which can be configured in web.xml
Demo5Servlet cn.itheima.Demo5Servlet data1 value1
In servlet, you then use this.getServletConfig () to get the ServletConfig object, which provides getInitParameter () and getInitParameterNames () methods to traverse the configuration items in the configuration.
Content that you don't want to write dead in servlet can be configured here.
IV. ServletContext
1. Represents the object of the current web application.
two。 Used as a domain object to transfer data between different servlet, the scope of action is the entire web application
Lifecycle: create ServletContext objects that represent the entire web application when the ServletContext application is loaded into the container. When the server is shut down or the web application is removed from the container, the ServletContext object is destroyed.
~ domain: a domain is understood as a box in which data can be placed. Since a domain is called a domain, it has a scope that can be seen, within which the data in this domain can be manipulated. Such objects are called domain objects.
3. The initialization parameters of the whole web application can be configured in web.xml, which can be obtained by using ServletContext.
Param1pvalue1this.getServletContext () .getInitParameter ("param1") this.getServletContext () .getInitParameterNames ()
4. Forward between different servlet
This.getServletContext () .getRequestDispatcher ("/ servlet/Demo10Servlet") .forward (request, response)
At the end of the method execution, the service will return to the server, and then the server will call the target servlet, where the request will be recreated and the data of the previous request will be copied in.
5. Read resource files
5.1 since the relative path defaults to the directory started by the java virtual machine, we will not get the resources because we directly write the relative path relative to the tomcat/bin directory. If it is written as an absolute path, the absolute path is wrong when the project is published to another environment.
To solve this problem, ServletContext provides this.getServletContext (). GetRealPath ("/ 1.properties"), which gives a virtual path to a resource and will return the real path of the resource in the current environment. This.getServletContext (). GetResourceAsStream ("/ 1.properties"), a stream that returns the virtual path of a resource to the real path of that resource.
5.3 when getting resource files under non-servlet, there is no ServletContext object to use, so you can only use the classloader.
ClassLoader.getResourceAsStream (".. /.. / 1.properties"), this method uses the classloader to load resources directly into memory, has the problem of update delay, and takes up too much memory if the file is too large.
ClassLoader.getResource (".. / 1.properties"). GetPath (), which directly returns the real path to the resource without the problem of update delay.
Thank you for reading this article carefully. I hope the article "how to use Servlet" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.