Java Web Technology: Tomcat, servlet

catalogue

Tomcat:web server software

Servlet: an applet running on the server side  

Implementation principle of Servlet

Life cycle method in Servlet

init (create): execute only once

service: execute multiple times

@WebServlet annotation

Architecture of servlet

http: Hypertext Transfer Protocol

Request message data format

Response message data format

Request

Get request message

Get the relevant method of the request line

Method for obtaining request header

Get request body data

General method of obtaining request

Chinese garbled code problem

Request forwarding

shared data

Get ServletContext

BeanUtils tool class to simplify data encapsulation

Response

Set response information

Set response line

Set response header

Set response body

redirect

Garbled code problem

Supplementary knowledge

Response status code

Path writing

ServletContext object

Acquisition method

Other methods

Tomcat:web server software

Server: the computer on which the server software is installed

Web server software: receive user requests, process requests, respond, and deploy web projects

basic operation

  • Software startup: startup.bat. Just run this file
  • Close normally: shutdown.bat, and run the file
  • Force close: click the X of the startup window

How to deploy the project

  • Just put the project directly under the webapps directory
    • Simplify deployment: type the project into a war package (. War file), and then place the war package in the webapps directory. The war package will be decompressed automatically
  • Configure conf/server.xml file (tomcat core configuration file)
    • Configure in < host > tag body   < Context docBase=" "   path=" ">   
      • docBase: the path where the project is stored (the path of the folder)
      • Path: virtual path
      • When accessing, ip: port number / virtual path / file name in the project
    • <Context docBase="D:\test" path="/aaa"/>
  • Create an xml file with any name in conf/Catalina/localhost, and write < context docbase = "" > in the file
    • The virtual directory when accessing is the file name of xml

Directory structure of java Dynamic Project

                        -- The root directory of the project
                            -- WEB-INF Directory:
                                -- web.xml: the core configuration file for a web project
                                -- classes Directory: the directory where bytecode files are placed
                                -- lib Directory: place dependent jar packages

Servlet: an applet running on the server side  

Servlet is an interface that defines the rules for Java classes to be accessed by the browser (recognized by tomcat). In the future, we will customize a class to implement servlet interface and replication method (tomcat will run it only if the rules are followed)

Implementation principle of Servlet

        one   When the server receives the request from the client browser, it will parse the request URL path and obtain the resource path of the accessed Servlet
         two   Find the web.xml file and check whether there is the corresponding < URL pattern > tag body content.
         three   If so, find the corresponding < servlet class > full class name in the
         four   tomcat loads the bytecode file into memory and creates its object
         five   Call its method

Life cycle method in Servlet

init (create): execute only once

Configure the creation time under the < servlet > tab

  • The value of < load on startup > is negative   Created when first accessed (default)
  • The value of < load on startup > is 0 or a positive integer    When the server starts, create

The init method of a Servlet is executed only once, which indicates that there is only one object in memory for a Servlet, and the Servlet is a singleton
Try not to define member variables in servlets. Do not modify the value of a member variable even if it is defined

service: execute multiple times

The Service method is called once every time the Servlet is accessed

destroy: execute only once

  • The destroy method is executed only when the server is shut down normally
  • Generally used to destroy resources

@WebServlet annotation

Instead of creating web.xml, you can use this annotation on the class for configuration

Architecture of servlet

         Servlet -- Interface
            |
         GenericServlet -- abstract class
            |
         HttpServlet   -- abstract class

  • GenericServlet: the default null implementation is made for other methods in the Servlet interface, and only the service() method is used as an abstraction
  • HttpServlet: an encapsulation of http protocol, which simplifies operation and copies doGet/doPost
    • The service method will first determine the transmission mode (get, post), and then call its method

urlpartten:servlet access path

A Servlet can define multiple access paths: @ WebServlet({"/d4","/dd4","/ddd4"})

Path definition rules

  • /xxx: path matching
  • /xxx/xxx: multi-layer path, directory structure
  • *. do: extension matching (can be any suffix name)

http: Hypertext Transfer Protocol

Defines the format of sending data when the client and server communicate

characteristic

  • Advanced protocol based on TCP/IP
  • Default port number: 80
  • Based on request / response model: one request corresponds to one response
  • Stateless: each request is independent of each other and cannot interact with data

Historical version

  • 1.0: each request response will establish a new connection
  • 1.1: multiplex connection (create connection, after use)   It will not be destroyed immediately. It will judge whether subsequent requests will use this connection. If so, it will be reused)

Request message data format

Request line

Format: request mode request url request protocol / version

Request mode

  • get: the request parameter is in the request line, after the url
  • post: the request parameter is in the request body

Request header

Format: request header: request header value

  User agent: the browser tells the server that I can access the version information of the browser you use

  • Can solve browser compatibility problems

Referer: tells the server where the current request comes from

  • Anti theft chain and statistical work (you can count users from baidu, Sina...)

Request blank line

This is the request header and request body used to split the POST request

Request body (body)

Encapsulates the request parameters of the post request message

Example: the browser is egde and uses post request to send user name and password

 

 

analysis:

  The first line is the request line, the last line is the request body (requested data), and the rest is the request header

Response message data format

Response line

  • Composition: Protocol / version response status code status code description

Response header

  • Format: header name: value

Common response headers

  • Content type: the server tells the client the data format and encoding format of this response body
  • Content disposition: the server tells the client in what format to open the response body data
    • In line: the default value, which is opened in the current page
    • attachment;filename=xxx: open the response body as an attachment. Application scenario: File Download

Response blank line

Response body: transmitted data

  • For example, the issued request is a page, and the response body is the page information

String format

			//Response line
            HTTP/1.1 200 OK
            //Response header
			Content-Type: text/html;charset=UTF-8
			Content-Length: 101
            //Response blank line
            
            //Responder
			<html>
			  <head>
			    <title>$Title$</title>
			  </head>
			  <body>
			  hello , response
			  </body>
			</html>

Request

Principle of request object and response object

  • The tomcat server will create a Servlet object according to the resource path in the request url
  • The tomcat server will create request and response objects, which encapsulate the request data
  • tomcat passes the request and response objects to the service method and calls the method
  • In the service method, you can obtain the request message data through request and set the response message data through response
  • Before responding to the browser, the server will retrieve the set response message data from the response

request object inheritance architecture

         ServletRequest         --     Interface
            |     inherit
         HttpServletRequest     -- Interface
            |     realization
         org.apache.catalina.connector.RequestFacade (the formal parameter we use is actually the implementation class object)

Get request message

Get the relevant method of the request line

  • String getMethod()     Get request method
  • String getContextPath()   Get virtual directory
  • String getServletPath()    Get Servlet path (resource path, excluding virtual directory)
  • String getQueryString()    Get get mode request parameters
  • String getRequestURI()      Get request URI: virtual directory / resource path
  • StringBuffer getRequestURL()   Get request URL: http://localhost/ Virtual directory / resource path
  • String getProtocol()     Get agreement and version
  • String getRemoteAddr()     Gets the IP address of the client
@WebServlet("/Servlet3")
public class Servlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //Browser access: http://localhost:8080/test/Servlet3?username=tony
        System.out.println(request.getMethod());//Request mode GET
        System.out.println(request.getContextPath());//Virtual directory / test
        System.out.println(request.getServletPath());//Resource directory / Servlet3
        System.out.println(request.getQueryString());//Get the get method request parameter username=tony
        System.out.println(request.getRequestURI());//uri   /test/Servlet3
        System.out.println(request.getRequestURL());//url   http://localhost:8080/test/Servlet3
        System.out.println(request.getProtocol());//Protocol version HTTP/1.1
        System.out.println(request.getRemoteAddr());//The ip address of the client is 0:0:0:0:0:0:1
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Method for obtaining request header

  • String getHeader(String name)     Get the value of the request header by the name of the request header
  • Enumeration<String> getHeaderNames()     Get all request header names
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        System.out.println(request.getHeader("User-Agent"));//Get request header data Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
        Enumeration<String> headerNames = request.getHeaderNames();//Get all request header names Enumeration enumeration type traversal requires iterators
        while (headerNames.hasMoreElements()){
            System.out.println(headerNames.nextElement());
        }
    }

Get request body data

step

  •   Get stream object
    • BufferedReader getReader(): gets the character input stream. Only character data can be manipulated
    • ServletInputStream getInputStream(): get byte input stream, which can operate on all types of data (scenario: file upload)
  • Then get the data from the stream object
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        BufferedReader reader = request.getReader();
        String line;
        while ((line=reader.readLine())!=null){
            System.out.println(line);//username=admin&password=aaa
        }
        reader.close();
    }

General method of obtaining request

  • String getParameter(String name)     Get parameter value according to parameter name
  • String[] getParameterValues(String name)   Gets an array of parameter values based on parameter names   
  • Enumeration < string > getparameternames(): get the parameter names of all requests
  • Map < string, string [] > getparametermap(): get the map set of all parameters

Chinese garbled code problem

  • request.setCharacterEncoding("utf-8");

Request forwarding

characteristic

  • The browser address bar path does not change
  • It can only be forwarded to the internal resources of the current server
  • Forwarding is a request

step

  • Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
  • Use the RequestDispatcher object to forward: forward (ServletRequest, servletresponse, response)  

shared data

Domain object: an object with scope that can share data within the scope

Request field: represents the scope of a request. It is generally used to share data (data shared in forwarding) among multiple resources requesting forwarding

correlation method

  • void setAttribute(String name,Object obj): stores data
  • Object getattribute (string name): get the value through the key
  • void removeAttribute(String name): remove key value pairs through keys
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
       request.setAttribute("username","aaa");
       request.getRequestDispatcher("/Servlet4").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
@WebServlet("/Servlet4")
public class Servlet4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getAttribute("username"));
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Get ServletContext

  • ServletContext getServletContext()

Case: user login

analysis

//Tool class
public class jdbc {
    private static DataSource dataSource;
    static {
        Properties properties = new Properties();
        try {
            properties.load(jdbc.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static  DataSource getDataSource(){
        return  dataSource;
    }
}
//dao define login method
public class dao {
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(jdbc.getDataSource());//Multiple operations share one JdbcTemplate
    public user login(user u){
        try {
            String sql="select * from user2 where username=? and password=?";
            user user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(user.class), u.getUsername(), u.getPassword());
            return user;
        }catch (DataAccessException e){
            e.printStackTrace();
            return null;//The query failed and returned null
        }
    }
}
//The form data will be sent to servlet5
@WebServlet("/Servlet5")
public class Servlet5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        user user = new user();
        user.setUsername(username);
        user.setPassword(password);
        dao dao = new dao();
        user user1 = dao.login(user);
        if(user1==null){
            //Login failed, return to login page
            request.getRequestDispatcher("login.html").forward(request,response);
        }else{
            //Put the user name into the request field and forward it to the success page
            request.setAttribute("name",username);
            request.getRequestDispatcher("/Servlet6").forward(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
//Successfully logged in to servlet6
@WebServlet("/Servlet6")
public class Servlet6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
      String name = (String) request.getAttribute("name");

        response.getWriter().write(name+"Login succeeded");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

BeanUtils tool class to simplify data encapsulation

For encapsulating JavaBean s (standard Java classes)

JavaBean requirements

  • Class must be public decorated
  • Constructor that must provide null arguments
  • Member variables must be decorated with private
  • Provide public setter and getter methods

Property: the product intercepted by setter and getter methods  

  • For example: getusername() -- > username -- > username (general attributes and member variables are the same)

Member method

  • setProperty()
  • getProperty()
  • Populate (object obj, map map): encapsulates the key value pair information of the map set into the corresponding JavaBean object

Sample code  

//populate example
        Map<String, String[]> map = request.getParameterMap();//Get all request data
        user user = new user();
        try {
            BeanUtils.populate(user,map);//Encapsulate data into user objects
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
//setProperty,getProperty
        user user = new user();
        BeanUtils.setProperty(user,"username","tom");//Set the username property of the user object to tom
        System.out.println(user);
        System.out.println(BeanUtils.getProperty(user,"username"));//Gets the value of the username of the user object

Response

Set response information

Set response line

  • Set status code: setStatus(int sc)

Set response header

  • setHeader(String name, String value)

Set response body

  • Get the output stream (getWriter(), getOutputStream()), and use the output stream to output the data to the client browser

The character set needs to be set to get the byte output stream

  response.getOutputStream().write("Hello".getBytes("utf-8"));

redirect

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
//        To redirect
//        response.setStatus(302);// Set the status code to 302
//        response.setHeader("location","/test/Servlet2");// Set response header
//        Simplified form
        response.sendRedirect("/test/Servlet2");
    }

principle

  characteristic

  • The address bar has changed
  • Redirect resources that can access other sites (servers)
  • Redirection is two requests. You cannot use the request object to share data

Garbled code problem

The default encoding of the obtained stream is ISO-8859-1. You need to set the encoding of the stream

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

Supplementary knowledge

Response status code

  • 1xx: the server receives the client message, but does not accept it. After waiting for a period of time, it sends 1xx multi status code
  • 2xx: successful. Representative: 200
  • 3xx: redirection. Representative: 302 (redirection), 304 (access cache)
  • 4xx: client error.   404 (the request path does not have a corresponding resource)    405: the request method has no corresponding doXxx method
  • 5xx: server side error. Representative: 500 (exception occurred inside the server)

Path writing

  • For client browser: virtual directory (redirection) is required
    • It is recommended to get the virtual directory dynamically: request.getContextPath()
  • For the server: there is no need to add a virtual directory (request forwarding) to forward requests within the server

Case: verification code

//Draw verification code
@WebServlet("/Servlet5")
public class Servlet5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        int width=100;
        int height=50;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//Picture object
        Graphics graphics = bufferedImage.getGraphics();//Get brush
        graphics.setColor(Color.PINK);//Set color
        graphics.fillRect(0,0,width,height);//draw rectangle
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0,width-1,height-1);//bound box 
        String str="QWERTYUIOPASDFGHJKLMNBVCXZ1234567890";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int i1 = random.nextInt(str.length());//Get random value
            char c = str.charAt(i1);//Get element
            graphics.drawString("    "+c+"",width/5*i,height/2);
        }
        //Interference line
        graphics.setColor(Color.GREEN);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

//html page
<body>
<img src="/test/Servlet5" id="img">
<br>
<a id="a_id" href="#"> if you can't see clearly, change another one</a>
<script>
    let img = document.getElementById("img");
    let a_id = document.getElementById("a_id");
    img.onclick=function () {
        img.src="/test/Servlet5?data"+new Date().getTime();
    }
    a_id.onclick=function () {
        img.src="/test/Servlet5?data"+new Date().getTime();
    }
</script>
</body>

ServletContext object

Acquisition method

  • Get through request object   request.getServletContext();
  • Obtained through HttpServlet   this.getServletContext();
  • The two methods get the same object

Other methods

Get MIME type   String getMimeType(String filename)   

  • MIME type: a file data type defined in the process of Internet communication      Format: large type / small type     text/html

Domain objects: sharing data

  • setAttribute(String name,Object value)
  • getAttribute(String name)
  • removeAttribute(String name)
  • Scope: data requested by all users

Get the real path of the file: Method: String getRealPath(String path)  

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletContext servletContext = this.getServletContext();
        System.out.println(servletContext.getRealPath("/c.txt"));//Get the file path under the web directory
        System.out.println(servletContext.getRealPath("/WEB-INF/b.txt"));//File path under WEB-INF directory
        System.out.println(servletContext.getRealPath("/WEB-INF/classes/a.txt"));//File path under src directory
    }

Case: File Download

@WebServlet("/Servlet7")
public class Servlet7 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String filename = request.getParameter("filename");//Get file name
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/WEB-INF/img/" + filename);
        FileInputStream fileInputStream = new FileInputStream(realPath);//read file
        String mimeType = servletContext.getMimeType(filename);//Get file mime type
        response.setHeader("content-type",mimeType);//Set the response header type and the file type that the server tells the client

        String agant = request.getHeader("user-agent");//The purpose of solving the problem of Chinese name is to make the pop-up window display Chinese name
        filename=DownLoadUtils.getFileName(agant,filename);//DownLoadUtils is a tool class that passes in the browser information and file name of the client

        response.setHeader("content-disposition","attachment;filename="+filename);//Open in copy fixed format
        ServletOutputStream outputStream = response.getOutputStream();//Write the read file information to the server memory
        byte[]bytes=new byte[1024*8];
        int len=0;
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<body>
<a href="/test/Servlet7?filename=2.jpg">Picture 1</a>
<a href="/test/Servlet7?filename=Nine tails.jpg">Picture 2</a>
<a href="/test/Servlet7?filename=1.avi"> Video 1</a>
</body>

Tags: html5 Struts Tomcat

Posted on Wed, 13 Oct 2021 09:30:14 -0400 by Jeff4507