The public account “Java Programming Notes” record Java learning daily, share learning road dribs and drabs, from entry to give up, welcome to pay attention to

What is the Servlet

Official explanation: Servlets are programs that run on a Web server or application server and act as an intermediary between requests from a Web browser or other HTTP client and a database or application on an HTTP server.

Generally speaking, a servlet is a program running on a Web server such as Tomcat and Jetty. It can respond to HTTP requests, implement the user’s own logic, and finally return the results to the user’s client (browser).

How do I implement a Servlet

Let’s start by looking at how to implement a Servlet.

Create a project

Here we take IDEA(professional version) as an example

  1. File -> new -> Project

  1. Select Java in the left column, and select your own JDK in the Project SDK on the right. If not, you need to add the following by yourself. In the box, you need to check Web Application, indicating that we are creating a Servlet Project

  1. Next Fill in Project name, Project location, and finish

The project has now been created. The default directory is SRC, which holds our Java code, web, which holds some resources about the Web, web-INF, and index.jsp, which is generated by default, and web-INF, which has a web.xml

Download Tomcat

Visit tomcat.apache.org/download-90… , download Tomcat9, and download the corresponding files for your own system

Download it, unpack it, and wait for the following configuration to use

Tomcat is configured in IDEA

Click on the Add Configuration

Choose + -> Tomcat Server -> Local

  • (1) Configure local Tomcat. Configure the tomcat downloaded from the preceding command
  • ② Open the browser by default
  • 3. Open the browser address by default
  • 4 Set VM startup parameters
  • ⑤ Set the JDK for Tomcat
  • ⑥ Set the Tomcat display name

After basic Tomcat information is configured, you need to configure the current project into Tomcat and switch to the Deployment configuration

After switching to Deployment, click the + sign to the right, select Artifact to add the WAR package for the current project, or click Fix below to add the WAR package

After the war package is added, there will be an Application Context path configuration below, which is used to configure the path name of the current project, which is also the project name in the webapps directory of Tomcat. All servlet requests under this project need to be processed in this path. In my configuration above, for example, the subsequent request is localhost:8080/servlet_demo_war_exploded/*, and /servlet_demo_war_exploded must be added to access the current project

Writing a Servlet

Finally, to write a servlet program, according to the servlet specification, we need to introduce the servlet-API jar package, then inherit HttpServlet class, and rewrite the corresponding doGet and doPost methods.

The servlet-API package is in the lib directory of the decompressed Tomcat we downloaded

Copy servlet-api.jar to the new lib directory. Right-click servlet-api.jar and click Add as Library… OK,

Under the SRC directory new DemoServlet, inherit the javax.mail servlet. HTTP. HttpServlet, and rewrite the doGet, doPost method

 PrintWriter writer = resp.getWriter();
 PrintWriter writer = resp.getWriter();
 writer.print("this is servlet html");
 writer.flush();
 writer.close();
Copy the code

Modify the web/WEB-INF/web. XML file to add the Servlet configuration item

 <servlet>
        <servlet-name>demoServlet</servlet-name>/ / define servletname<servlet-class >com.muku.servlet.DemoServlet</servlet-class>// It inherits the class of HttpServlet</servlet>

    <servlet-mapping>
        <servlet-name>demoServlet</servlet-name>/ / servlet - the name above<url-pattern>/ *</url-pattern>// Intercept all requests</servlet-mapping>
Copy the code
Servlet Defines a servlet servlet-name specifies the name of the servlet servlet-classWe did it ourselvesservletclassclassservlet-mappingdefineservletMapping to the requesturl-patternConfigure the request path to intercept, such as /html/ 1 /html/2, /* intercepts all requestsservlet-name url-patternThe interception request path defined inservletTo deal withCopy the code

The overall changes are shown in the following screenshot

Start Tomcat that we have configured. After successful startup, IDEA will automatically open the browser and access the path that we have set. If there is no accident, you can see thatthis is servlet html

At this point, a Servlet has been written and can be accessed successfully

Annotation-based servlets

We need to modify the web. XML, and inherit the HttpServlet class to achieve a Servlet, Servlet3.0 provides annotated way to achieve Servlet development, without saying much, directly on the code

@WebServlet(name = "annotation",urlPatterns = "/*")
public class AnnotationServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.print("this is servlet html"); writer.flush(); writer.close(); }}Copy the code

Simply add the WebServlet annotation to our implementation class

WebServlet annotations have several important properties

  • Name indicates the name of the current servlet, which corresponds to servlet-name in wem.xml
  • UrlPatterns represents the request path map currently being processed by the servlet
  • InitParams indicates the servlet initial configuration

Several important objects in servlets

HttpServletRequest

Each time an HTTP request is received, the current HTTP request is wrapped into an HttpServletRequest object, which is passed as an input through the doGet, doPost, and other methods

  • GetHeader Gets the header information of the request header
  • GetCookies Gets the cookie information for the current request
  • GetMethod Gets the current request method category Get Post
  • GetQueryString Gets the kv string k1=v1=&k2=v2 of the current request parameters
  • GetRequestURI gets the current request path /servlet/a
  • GetRequestURL for current request total path, including domain name http://localhost:8080/servlet/a agreement
  • GetSession Gets the session information of the current request
  • GetParameter Gets the value of the key in the request parameter

HttpServletResponse

Each time an HTTP request comes in, the information returned by the current HTTP is encapsulated as an HttpServletResponse object. You can set the properties of your RESONse to return the corresponding data. HttpServletRequest has several common methods

  • AddCookie Adds a cookie that can be set to the current HTTP request and will be carried back for the next request
  • SendRedirect redirects to the requested address and the code is set to 302
  • AddHeader sets the header data to return
  • SetStatus Sets the corresponding status code. Common status codes include 200, 302, 405, 500, and so on
  • SetContentType set up corresponding data format, such as common text/HTML, text/javascript, text/CSS, application/json, etc., the browser will render the corresponding data according to the contentType
  • The getWriter important method, which gets the output stream object, can be used to output content to the page through the write method, such as this is servlet HTML

ServletConfig

ServletConfig is servlet-level. Each servlet has its own properties, including names, initialization parameters, and so on. These properties are unique to each servlet, and the set of properties is represented by a ServletConfig object

  • GetServletName Gets the current servlet name
  • GetServletContext gets the ServletContext object, and every Web application has one and only one ServletContext object,
  • GetInitParameter Gets the parameters of the servlet initialization configuration
  • GetInitParameterNames Gets the set of names of all the initial configuration information for the servlet

ServletContext

When a Web application is started, a ServletContext object is created, which represents the context of the Web application and can be used to configure and read the global configuration of the current application. Servlets communicate with each other through the ServletContext object. The servletContext object can be obtained from the servletConfig object

  • Get /set Attribute Sets to obtain global servlet attributes
  • GetAttributeNames gets the set of names for all attributes
  • Add the Servlet addServlet
  • AddFilter Adds a filter
  • AddListener Adds a listener

The life cycle of a Servlet

The life cycle of a Servlet, from creation to destruction, mainly includes the following process

  • Call the init method for initialization
  • Call the service method to process the request, and call the corresponding doGet doPost doPut and other methods according to the request method
  • Call the destroy method

Init

The Init method is called only once during the lifetime of a servlet, at creation time, and is typically used for initialization operations such as initializing a connection pool, connecting to a database, and so on

Service

The service method is an important method for handling HTTP requests. Every time a new HTTP request is received, the server will create a new thread to process the request. Then the service method will call doGet,doPost and other methods according to the method type of the current request. These methods are then overwritten, so each request is actually handled by the logic we overwrote

destroy

The destroy method is only called at the end of the Servlet’s life cycle and is mainly used for finalizing operations such as closing the database connection pool, clearing memory writes, and so on