JavaWeb -- Servlet1 (idea creates Servlet project)

1. What is a Servlet
1. Servlet is one of the Java EE specifications. A specification is an interface
2. Servlet is one of the three major components of Java Web. The three components are: servlet program, Filter filter and Listener listener.
3. Servlet is a java applet running on the server. It can receive the request sent by the client and respond to the data to the client.
2. Manually implement Servlet program
1. Create a Java Web project

Select Java enterprise - > Web Application - > next

Modify Model name: finish

At this time, some versions do not directly generate subdirectories and directories under the web xml file. You need to add it yourself at this time
file - project structure - > faces - > click the project just created on the right - > click the plus sign on the right of path to add


At this time, note that the newly created WEB-INF is not under the web, and you should modify it yourself


Click OK

At this point, it has been added successfully, and an initial Servlet has been created successfully!!!
2. Create a class in the package created by src to implement servlet

public class HelloServelt implements Servlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hello Servlet!!!");
    }

3. Go to the web Configure the address accessed by the servlet program in XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--servlet Label to Tomcat to configure Servlet program-->
    <servlet>
        <!--servlet-name label Servlet The program has an alias (usually the class name)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class yes Servlet Full class name of the program-->
        <servlet-class>HelloServelt</servlet-class>
    </servlet>
    <!--servlet-mapping Label to servlet Program configuration access address-->
    <servlet-mapping>
            <!--servlet-name The tag is used to tell the server to which address I currently configure Servlet Program use-->
        <servlet-name>HelloServlet</servlet-name>
        <!--url-pattern Label configuration access address<br/>/The slash indicates that the address is: http://IP: port / Project path < br / > / Hello indicates that the address is: http://ip:port/ Project path / Hello < br / > -- >
        <url-pattern>/test1</url-pattern></servlet-mapping>
</web-app>

4. Modify Tomcat Name: generally modify it to the name of your own project, so as to facilitate identification

Change Tomcat to ServletTest - > click run - > and it will appear Contents in jsp file - > Add / test1 in < URL pattern > / url pattern > < / servlet mapping > after the browser path - > output defined in the browser display class


3. Access from URL address to Servlet program

localhost locate host
8080: locate Tomcat by port number
Servletest determines the access project
/test1 determines the resource path: access the class through the resource path - > alias - > alias
4.Servlet life cycle
1. Execute Servlet constructor method
2. The first and second steps of init initialization method are to create a Servlet program and call it during the first access.
3. Execute the third step of the service method, which will be called every time.
4. Execute the fourth step of destroy method, and call it when the web project stops.
5. Distribution processing of get and post requests
5.1 implements Servlet interface to realize distribution processing

@Override
/***service Methods are designed to handle requests and responses
     *
     * *@param servletRequest
     * *@param servletResponse
     * *@throws ServletException
     * *@throws IOException*/
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    System.out.println("3.Hello Servlet!!!");//Every access is executed
    //Type conversion: because it has the getMethod() method
    HttpServletRequest httpservletRequest1 = (HttpServletRequest)servletRequest;
    //How to get the request
    String method = httpservletRequest1.getMethod();
    if ("GET".equals(method)){
        Doget();
    }
    if ("Post".equals(method)){
        DoPost();
    }
}
public void Doget(){
    System.out.println("GEt request");
    System.out.println("GEt request");
}
public void DoPost(){
    System.out.println("Post request");
    System.out.println("Post request");
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>  //visit http://localhost:8080/a.htlm Click Submit method="post"/"get"
    <form action="http://localhost:8080/test1" method="post">
    <input type="hidden" name="action" value="login" />
    <input type="hidden" name="username" value="root" />
    <input type="submit">
</form>
</body>
</html>

5.2 realize Servlet program by inheriting HttpServlet
Generally, in the actual project development, the Servlet program is implemented by inheriting the HttpServlet class.
1. Write a class to inherit the HttpServlet class
2. Override doGet or doPost methods according to business needs
3. To the web The access address of the configuration Servlet program in XML
Step 1:

public class HelloServlet2 extends HttpServlet{//It needs to be configured in xml
    /***doGet()Called when a get request is made
     * *@paramreq
     * *@paramresp
     * *@throwsServletException
     * *@throwsIOException*/
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 in Doget");//When a web page submits a get request, it will execute the code inside
    }

    /***doPost()Called when a post request is made
     * *@paramreq
     * *@paramresp
     * *@throwsServletException
     * *@throwsIOException
     * */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 in Dopost");//Execute the code when doing post
    }
}

Configure HelloServlet2 in xml

<servlet>
        <servlet-name>HelloServlet2</servlet-name>
        <servlet-class>servlettest.HelloServlet2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet2</servlet-name>
        <!--Access path at that time/test2-->
        <url-pattern>/test2</url-pattern>
    </servlet-mapping>

6.idea create Servlet program


7. Inheritance system of servlet class
Custom Servlet program - > httpservlet class - > gengricservlet class - > Servlet interface

8.ServletConfig class
From the perspective of class name, ServletConfig class is the configuration information class of Servlet program.
Both the Servlet program and the ServletConfig object are created by Tomcat and used by us.
By default, servlet programs are created during the first access. ServletConfig is * * * * when each servlet program is created, a corresponding ServletConfig object * * is created. (each servlet program has one, because the configuration of each class in xml is different)
//Three functions of ServletConfig class
//1. You can get the value of the alias Servlet name of the Servlet program
//2. Get the initialization parameter init param
//3. Get ServletContext object

@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2 init Initialization method");
// 1. You can get the value of the alias Servlet name of the Servlet program
System.out.println("HelloServlet The alias of the program is:" + servletConfig.getServletName());
// 2. Get initialization parameter init param
System.out.println(" Initialization parameters username The value of is;" + servletConfig.getInitParameter("username"));
System.out.println(" Initialization parameters url The value of is;" + servletConfig.getInitParameter("url"));
// 3. Get ServletContext object
System.out.println(servletConfig.getServletContext());
}
xml Configuration in
   <servlet>
        <servlet-name>HelloServlet5</servlet-name>
        <servlet-class>servlettest.HelloServlet5</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet5</servlet-name>
        <!--Access path at that time/test2-->
        <url-pattern>/test5</url-pattern>
    </servlet-mapping>

9.ServletContext class (it looks at some properties and descriptions of the whole project, so there is only one process)
1. ServletContext is an interface that represents a Servlet context object
2. A web project has only one ServletContext object instance.
3. The ServletContext object is a domain object.
4. ServletContext is created when the web project deployment starts. Destroy when the web project stops
Domain object setAttribute() getAttribute() removeAttribute();

Four functions of ServletContext class
1. Get web The context parameter context param configured in XML
2. Get the current project path, format: / Project path
3. Get the absolute path on the server hard disk after project deployment
4. Access data like Map

public class HelloServlet5 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Get web The context parameter context param configured in XML
        ServletContext context = getServletConfig().getServletContext();

        String username = context.getInitParameter("username");
        System.out.println("context-param parameter username The value of is:" + username);
        System.out.println("context-param parameter password The value of is:" + context.getInitParameter("password"));
//        2. Get the current project path, format: / Project path
        System.out.println( "Current project path:" + context.getContextPath() );
//        3. Get the absolute path on the server hard disk after project deployment
        /**
         *  / The address of the slash resolved by the server is: http://ip:port/ Project name / web Directory mapped to IDEA code < br / >
         */
        System.out.println("The project deployment path is:" + context.getRealPath("/"));
        System.out.println("Under engineering css The absolute path to the directory is:" + context.getRealPath("/src"));
        System.out.println("Under engineering imgs Catalog 1.jpg The absolute path is:" + context.getRealPath("/web/index.jsp"));
    }
}
public class HelloServlet6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get ServletContext object
        ServletContext context=getServletContext();
        System.out.println(context);
        System.out.println("Before saving:Context1 obtain key1 The value of is:"+context.getAttribute("key1"));
        context.setAttribute("key1","value1");//Set the value of key1
        System.out.println("Context1 Get domain data from key1 The value of is:"+context.getAttribute("key1"));}//Get the value of key1 value1
    }
//Access key1 just set in another class: the description is applicable to the whole project
public class HelloServlet7 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context=getServletContext();
        System.out.println(context);
        System.out.println("Context2 Get domain data from key1 The value of is:"+context.getAttribute("key1"));
    }
}

Keywords: Java Tomcat servlet

Added by xenoalien on Tue, 08 Feb 2022 23:54:56 +0200