Servlet -- Summary of core content

Posted by Yrogerg on Fri, 28 Jan 2022 19:33:26 +0100

Servlet summary

Because looking at the company code, there is a cookie + JWT Token login authentication interface, so review servlet, cookie, session, front and back end separation restful, JWT Token related content. Although it is now popular for the gateway to encapsulate various interfaces, the foundation is still relatively important and needs to be reviewed again.

Servlet - basic theory, practical code training: https://how2j.cn/k/servlet/servlet-eclipse/558.html

Servlet – extended theory, examples and reference links: https://github.com/ZhongFuCheng3y/3y/blob/master/README.md#dollarservlettomcat




☕ Background Introduction to Servlet related objects

Introduction Servlet

Firstly, Tomcat is a servlet container, which is used to accept and return requests from the server and client (before that, socket was used for listening and processing without Tomcat).

Secondly, in the above interaction process, HTTP protocol is used. HTTP protocol is a communication format between client and server.

Finally, the life cycle of Servlet is generated with the call of built-in tomcat and destroyed with the shutdown of tomcat. The Servlet related objects are listed below.

  • ServletConfig

Get the web through this configuration Parameters in XML

  • ServletContext

    Get the configuration file of the whole application when tomcat starts.

  • Request,Response

    Corresponding to http request header and response header respectively

  • Cookie,Session

    Cookie: store and client, store user identity. Session: the storage and server side to judge the user's identity.



☕ ️ 1.Servlet Part 1 (tomcat, http protocol)

At present, it is the method of HTTP servlet to implement servlet, rewriting doget and dopost methods.

1.tomcat

The bottom layer of tomcat is socket program, jsp and servlet container.

This paper introduces the virtual directory and virtual host in tomcat

Virtual directory: files are not necessarily placed in webapps, so you need to configure the virtual directory to access files on other disks after the project is started

Virtual host: configure multiple domain names in a tomcat, so that you can access the same Tomcat through multiple domain names


2.Http protocol

Http protocol: Hypertext Transfer Protocol, which interacts between client and server

​ Http1.0: client and server are short-lived connections. They will be disconnected after obtaining resources

​ Http1.1: The client and server remain connected, and multiple web resources can be obtained



🎃 2.Servlet Part 2 (request, response)

1.request
#Introduction to request parameter
request.getRequestURL(): Complete when the browser makes a request URL,Include protocol hostname port(If so)"
request.getRequestURI(): In the resource name part of the request issued by the browser, the protocol and host name are removed"
request.getQueryString(): The parameter part in the request line can only be displayed in get Parameters issued by, post Can't see the way
request.getRemoteAddr(): The name of the client on which the browser is located IP address
request.getRemoteHost(): The hostname of the client where the browser is located
request.getRemotePort(): The network port used by the client where the browser is located
request.getLocalAddr(): Server IP address
request.getLocalName(): Host name of the server
request.getMethod(): The general way to get the client request is GET perhaps POST

#header information in browser
host: Host address
user-agent: Browser basic information
accept: Indicates the data type accepted by the browser
accept-language: Indicates the language accepted by the browser
accept-encoding: Indicates the compression method accepted by the browser. It is compression method, not coding
connection: Keep connected
cache-control: Cache time limit
2.response

Anti theft chain: A precious resource B can only be accessed through link A, so the anti-theft chain function needs to be added to the interface of request B

        //Anti theft chain
        String referer = request.getHeader("Referer");
        if (referer == null || !referer.contains("localhost:9090/huyuqiao")){
            response.sendRedirect("huyuqiao");
            return "Steal links";
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("Genuine link");



📖 3.Servlet Part 3 (cookie,session)*

1.Cookie

Cookie: used in the browser to save user identity / browsing records. Combined with other technologies (session,token,sso, etc.) to realize the user login authentication function.

        //Assemble cookies
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        String name = "Hu Yuqiao";
        Cookie cookie = new Cookie("country", URLEncoder.encode(name, "UTF-8"));
        cookie.setMaxAge(2000);

        response.addCookie(cookie);
        printWriter.write("Server issued cookie,Saved Chinese data");


        //Decoding cookie s
        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(c ->{
            String cookieName = c.getName();
            try {
                String value = URLDecoder.decode(c.getValue(), "UTF-8");
                printWriter.write(name + "-----" + value);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        });
2.Session

Session: save in the browser (30 minutes by default, and disappear after closing the browser). Save the user information in the login registration, and then the front end can extract the user information through el expression.

#session get, get, set and destroy
HttpSession session = request.getSession
httpSession.getAttribute("name")
httpSession.setAttribute("name", "huyuqiao")
session.removeAttribute("name")