Servlet related knowledge points


1.Servlet: short for Server Applet, it is a server-side program (code and function implementation), which can interactively process the requests sent by the client to the server and complete the operation response.

  • Dynamic web technology
  • The basis of Java Web program development and an integral part of Java EE specification (a set of interfaces).

Servlet function:

  • Receive the client request and complete the operation.
  • Dynamically generate web pages (variable page data).
  • Respond the dynamic web page containing the operation results to the client.

The Servlet container is used to load servlets. Its main function is to provide the superior container (Tomcat) with methods such as doGet() and doPost(). Its life cycle instantiation, initialization, invocation and destruction are controlled by Tomcat container.

2. Method:

  • init(ServletConfig config)

  • ServletConfig getServletConfig()

  • service(ServletRequest req,ServletResponse res)

  • String getServletInfo()

  • destroy( )

3. Creation method

  • The first way to create a Servlet is to implement the interface Servlet

  • The second way to create a Servlet is to inherit HttpServlet

4. Life cycle
(1) Instantiation

When the user visits for the first time Servlet Called by the container when Servlet Constructor to create a concrete Servlet Object.

Execute only once

(2) Initialize

In the initialization phase, init()Method will be called. This method is in javax.servlet.Servlet Defined in the interface. Among them, the method takes one ServletConfig Object of type as a parameter.

The init method is executed only once

(3) Service

When the client has a request, the container will send the request ServletRequest And response ServletResponse Object transfer to Servlet,Pass to in the form of parameters service method.
 This method executes multiple times

This method executes multiple times

(4) Destroy

When Servlet Container stop or restart will cause destruction Servlet Object and call destroy method.

The destroy method executes once

5. Garbled code
Garbled Code: it is caused by the different character coding format used in the process of coding and section coding.
Scenario:

(1)Garbled code from client browser to back-end server
   Guaranteed front-end coding bit utf-8
   Before accepting request parameters  request.setCharacterEncoding("utf-8");
(2)back-end(java program) Garbled code in database
   Ensure that the database and tables are utf-8
   If the code is garbled db.properties Add?useUnicode=true&characterEncoding=utf-8
	url=jdbc:mysql:///student?useUnicode=true&characterEncoding=utf-8
(3)Back end to front end garbled code
   Ensure that the front-end code is utf-8
   Before responding to data  response.setContentType("text/html;charset=utf-8");

6.Servlet, GenericServlet and HttpServlet are three methods to implement servlet, in which servlet is an interface.

7. What content does HTTP protocol contain

HTTP request message

1. Request line request method / address URI protocol / version
2. Request header
3. Empty line
4. Request body

HTTP response message

The HTTP response message is similar to the HTTP request message. The HTTP response also consists of four parts:
1. Status line
2. Response header
3. Empty line
4. Response body

8. Difference between get and post

get request

  • The data submitted by get will be placed after the URL with "get"? Split the URL and transmit data, and connect the parameters with &
  • get mode is transmitted in clear text, and the amount of data is small and unsafe
  • High efficiency. The browser's default request method is GET request
  • The corresponding Servlet method is doGet

post request

  • The post method is to put the submitted data into the Body of the HTTP package
  • Ciphertext transmits data, which is large and safe
  • The efficiency is not high
  • The corresponding Servlet method is doPost
  1. Difference between forwarding and redirection

The role of forwarding is on the server side. It sends the request to other resources on the server to jointly complete the processing of a request.

Redirection works on the client. After the client sends the request to the server, the server responds to the client with a new request address, and the client resends the new request.

10.HTTP protocol is stateless and cannot save the information submitted each time

11.cookie properties
(1)path attribute
It specifies the web page associated with the cookie. By default, a cookie is associated with the web page that created it

(2)secure attribute
It is a Boolean value that specifies how to transmit cookie s on the network. By default, it is unsafe and transmitted through an ordinary http connection;

(3)expires attribute
Specifies the lifetime of the cookie, which is temporary by default
(4).setMaxAge(-1);// Memory storage. There are three values: > 0 validity period, in seconds= 0 failure< 0 memory storage

(5) Use Chinese cookies Both name and value are encoded in UTF-8
URLEncoder.encode("name", "UTF-8"),

12. Two implementation methods of session
(1)sessionId

sessionId works through the browser's Cookie. When cookies are prohibited in the client browser, the Servlet container cannot obtain the Session ID as a Cookie from the client browser, so it cannot track the client's status.
The server stores the cookie in the browser. When sending the request to the server, the cookie value stored in the browser is transmitted to the server as the value of the cookie attribute of the http request header to maintain the identity.

(2) URL rewriting

When the browser accesses an address on the server, it no longer uses the original address, but uses the rewritten address (that is, the sessionID is added after the original address).

13. Difference between cookie and session:

  • Different data storage locations:

The cookie data is stored on the client bai's browser, and the session data is placed on the server.

  • Different levels of safety:

Cookies are not very secure. Others can analyze the cookies stored locally and cheat them. Considering security, session should be used.

  • Different degrees of performance use:

The session will be saved on the server for a certain period of time. When access increases, it will occupy the performance of your server. Considering reducing the performance of the server, cookie s should be used.

  • Different data storage sizes:

The data saved by a single cookie cannot exceed 4K. Many browsers restrict a site to save up to 20 cookies, while the session is stored on the server, and the browser has no restrictions on it.

14. (1) request object

The request object used in the Servlet to process client requests requires the doGet or doPost method.

(2) response object

The response object is used to respond to customer requests and output information to the client.

(3) ServletContext overview

  • The global object also has a scope, corresponding to a Web application in Tomcat

  • When the Web server starts, a shared storage area (ServletContext) will be created for each Web application

  • ServletContext is created when the Web server starts and destroyed when the server shuts down

15. On the web When configuring servlets in XML, you can configure some initialization parameters. In the Servlet, these parameters can be obtained through the methods provided by the ServletConfig interface. (in fact, parameters can also be obtained through ServletContext, but the parameters obtained by ServletConfig are initialized when the container is started, and ServletConfig is initialized when the Servlet class calls the init() function.
16.

@WebServlet("/login")
public class LoginServlet  extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String user = req.getParameter("user");
        String pwd = req.getParameter("pwd");

        if("tom".equals(user)&&"123".equals(pwd)){//Successful login

            HttpSession session = req.getSession();
            session.setMaxInactiveInterval(20);
            session.setAttribute("user",user);//Save the login user name information in the session

            //Jump to a home page  
        }else{
           


        }
        resp.sendRedirect("index");

    }
}

@WebServlet("/index")
public class IndexServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");

        HttpSession session = req.getSession();

        String name=  (String)session.getAttribute("user");
        String str="";
        if(name==null){
            str="<a href='login.html'>Go login</a>";
        }else{
            str="<h1>welcome"+name+"</h1><a href='logout'>Log out</a>";
        }
        PrintWriter out = resp.getWriter();


        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset='utf-8'/>");
        out.println("<title>home page</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(str);
        out.println("</body>");
        out.println("</html>");




    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <form action="login" method="post">
        <input name="user" placeholder="enter one user name"><br/>
        <input name="pwd" type="password" placeholder="Please input a password"><br/>
        <input type="submit" value="land">


    </form>


</body>
</html>

Tags: Java servlet

Posted by ridster on Tue, 19 Apr 2022 12:52:17 +0930