Learning notes on knowledge points of HttpServlet

Servlet concept step Principle of execution life cycle Servlet 3.0 annotation configuration The architecture...
Servlet
HTTP
Request
BeanUtils tool class to simplify data encapsulation
HTTP protocol
Response object
ServletContext object

Servlet

concept step Principle of execution life cycle Servlet 3.0 annotation configuration The architecture of Servlet
  • GenericServlet: the default null implementation of other methods in the Servlet interface, only the service() method as an abstraction
    • When defining a Servlet class in the future, you can inherit GenericServlet and implement the service() method
  • HttpServlet: an encapsulation of http protocol to simplify operation
    • Definition class inherits HttpServlet
    • Copy doGet/doPost method (judge request method)
    • GET on browser direct request
Servlet / interfaceGenericServlet / abstract class Servlet related configuration
  1. 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 match
@WebServlet("/servletDemo") public class ServletDemo extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }

HTTP

  • Concept: Hyper Text Transfer Protocol
  • Transmission protocol: the format of sending data when client and server communicate

characteristic

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

Historical version

  • 1.0: new connection will be established for each request response
  • 1.1: multiplexing connection

Request message data format (request)

POST /login.html HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Referer: http://localhost/login.html Connection: keep-alive Upgrade-Insecure-Requests: 1 username=zhangsan
Request line
  • Request mode request url request protocol / version
  • GET /login.html HTTP/1.1
  • Request mode (there are 7 request modes in HTTP protocol and 2 in common use)
    1. GET:
      1. The request parameter is in the request line, after the url.
      2. The requested url length is limited
      3. Not very safe
    2. POST:
      1. Request parameter in request body
      2. The requested url length is unlimited
      3. Relative safety
Request header
  • Request header name: request header value

  • The client browser tells the server some information

  • Common request headers

    • User agent: the browser tells the server that I access the browser version information you are using
      • The information of the header can be obtained on the server side to solve the compatibility problem of the browser
    • Referer: http://localhost/login.html
      • Tell the server where the current request comes from
      • Function: anti theft chain, statistical work
Request blank line
  • A blank line is used to split the request header and body of a POST request
Request body (body)
  • That encapsulates the request parameters of the POST request message

Request

The principle of request object and response object

  • The request object is to get the request message
  • The response object is to set the response message
Request and response steps
  1. The tomcat server will create the corresponding ServletDemo object according to the resource path in the request url

  2. The request and response objects are created by the server (the request message data is encapsulated in the request object). Let's use them

  3. tomcat passes two objects, request and response, to the service method, and calls the service method

  4. We can get the request message data through the request object and set the response message data through the response object

  5. Before the server responds to the browser, it will take out the response message data we set from the response object

request object inheritance architecture

ServletRequest / interfaceHttpServletRequest / interface

request function

Get request message data Get request line data (method)
  • GET /day14/demo1?name=zhangsan HTTP/1.1
  • GET: String getMethod()
  • Get virtual directory (/ day): String getContextPath()
  • Get Servlet path (/ demo1): String getServletPath()
  • Get get method request parameter (name=zhangsan): String getQueryString()
  • Get request URI
    • String getRequestURI(): /day14/demo1
    • StringBuffer getRequestURL(): http://localhost/day14/demo1
    • URI (Uniform Resource Identifier): / day14/demo1
    • URL (uniform resource locator): http://localhost/day14/demo1
  • Get protocol and Version (HTTP/1.1): String getProtocol()
  • Get the IP address of the client: String getRemoteAddr()
Get request header data (method)
  • Get the value of the request header by the name of the request header: String getHeader(String name)
  • Get all request header names: enumeration < string > getheadernames()
// Get request header data @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get all request header names Enumeration<String> headerNames = request.getHeaderNames(); // ergodic While(headerNames.hasMoreElements()){ // Get the value of the request header by name String value = request.getHeader(name); System.out.println(name+":"+value); } // Get request header data: user agent String agent = request.getHeader("user-agent"); // Judge browser version of agent if(agent.contains("Chrome")){ // Google browser }else{ // Other browsers } }
Get request body data (method)
  • Request body: only POST request mode has a request body, which encapsulates the request parameters of POST request
  • step
    1. Get stream object
      • Get character input stream (only character data can be manipulated): BufferedReader getReader()
      • Get byte input stream (all types of data can be manipulated): ServletInputStream getInputStream()
    2. Then take the data from the flow object
<!--html in form Form's action Path writing: virtual directory+Servlet Resource path for--> <form action="demo/requestDemo" method="post"> <input type="text" placeholder="enter one user name" name="username"><br> <input type="text" placeholder="Please input a password" name="password"><br> <input type+"submit" value="register"> </form>
@WebServlet("/requestDemo") public class ServletDemo extends HttpServlet { // Get request message body (request parameter) @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get character stream BufferedReader br = request.getReader(); // Read data String line = null; while((line = br.readerLine())!=null){ System.out.println(line); // Output a line of user name and password information } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Other functions General way to get request parameters
  • The following methods can be used to GET the request parameters in both GET and POST request modes

  • Get parameter value according to parameter name: String getParameter(String name)

    String name1 = request.getParameter("username"); // Get the value of name1 for username according to the value of the tag name attribute
    • username=zs&password=123
  • Get the array of parameter values according to the parameter name: String[] getParameterValues(String name)

    String[] hobbies = request.getParameterValues("hobby"); for(String hobby : hobbies){ System.out.println(hobby); }
    • hobby=football&hobby=game
  • Get parameter names of all requests: enumeration < string > getparameternames()

    Enumeration<String> parameterNames = request.getParameterNames(); while(parameterNames.hasMoreElements()){ String name = parameterNames.nextElement(); System.out.println(name); // Parameter name requested String value = request.getParameter(name); System.out.println(value); // Get parameter value according to parameter name }
  • Get the map set of all parameters: Map < string, string [] > getparametermap()

    Map<String,String[]> parameterMap = request.getParameterMap(); Set<String> keySet = parameterMap.keySet(); // Get key for(String name : keySet){ String[] values = parameterMap.get(name); // Get value from key System.out.println(name); for(String value : values){ System.out.println(value); } }
  • Chinese code scrambling:

    • GET mode: tomcat 8 has solved the problem of getting mode scrambling
    • POST mode: random code
    • Solution: before obtaining parameters, set the code of request request.setCharacterEncoding("utf-8");
Request forwarding
  • A way of resource jump inside the server

  • step

    1. Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
    2. Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response)
    request.getRequestDispatcher("/requestDemo").forward(request, response);
  • matters needing attention

    1. Browser address bar path does not change
    2. Can only forward to internal resources of the current server
    3. Forwarding is a request
shared data
  • Domain object: a scoped object that can share data within the scope
  • Request domain: represents the scope of a request, which is generally used to share data among multiple resources for request forwarding
  • method
    • Store data: void setAttribute(String name,Object obj)
    • Get value through key: object getattribute (string name)
    • Remove key value pair by key: void removeaattribute (string name)
Get ServletContext
  • ServletContext getServletContext()

BeanUtils tool class to simplify data encapsulation

For encapsulating JavaBean s

JavaBean: a standard Java class

requirement
  1. Class must be public decorated
  2. Constructor of null parameter must be provided
  3. Member variables must be decorated with private
  4. Provide public setter and getter methods
Function: encapsulate data

concept

Member variable
  • Property: the result of intercepting setter and getter methods
  • For example: getusername() -- > username – > username

method

  1. Setting: setProperty()
  2. Get: getProperty()
  3. Encapsulate the key value pair information of the map collection into the corresponding JavaBean object: populate (object obj, map map map)
User user = new User(); try{ BeanUtils.setProperty(user,"username","zhangsan"); // Save zhangsan's string into user's username Strign username = BeanUtils.getProperty(user,"username"); //Take the value of username }catch(IllegalAccessException e){ e.printStackTrace(); }catch(InvocationTargetException e){ e.printStackTrace(); }

HTTP protocol

Request message: data sent by client to server

  • data format

    • Request line
    • Request header
    • Request blank line
    • Requestor

Response message: data sent by the server to the client

data format Response line
  • Composition: Protocol / version response status code status code description
  • Response status code (all status codes are three digits): the server tells the client
    • 1xx: the server received the client message but did not accept the completion. After waiting for a period of time, 1xx status code will be sent
    • 2xx: success. Two hundred
    • 3xx: redirect.
      • 302: redirection
      • 304: access cache
    • 4xx: client error
      • 404: request path has no corresponding resource
      • 405: there is no corresponding doXxx method for request mode
    • 5xx: server side error. 500 (exception in the server)
Response header
  • Format: header name: value
  • Common response headers
    • The server tells the client the data format and encoding format of the response body: content type
    • The server tells the client in what format to open the response body data: content disposition
      • In line: default value, open in the current page
      • attachment;filename=xxx: open the response body as an attachment, and download the file
Response empty line Response body: data transferred
  • Response string format

    HTTP/1.1 200 OK Content-Type: text/html;charset=UTF-8 Content-Length: 101 Date: Wed, 06 Jun 2018 07:08:42 GMT <html> <head> <title>$Title$</title> </head> <body> hello , response </body> </html>

Response object

Function: set response message

Set response line
  • Format: HTTP/1.1 200 ok
  • Set status code: setStatus(int sc)
Set response header
  • setHeader(String name,String value)
Set response body Use steps
  1. Get output stream
    • Character output stream: PrintWriter getWriter()
    • Byte output stream: ServletOutputStream getOutputStream()
  2. Output data to client browser using output stream

Redirection (how resources jump)

  • a resource cannot be completed, b resource can be completed
  • Tell browser to redirect: status code 302
  • Tell browser b resource path: response header location: b resource path
// Accessing / responseDemo0 will automatically jump to / responseDemo //1. Set status code to 302 response.setStatus(302); //2. Set response header location response.setHeader("location","/day/responseDemo"); //A simple redefinition method response.sendRedirect("/day/responseDemo");
Characteristics of redirection: redirect
  • Address bar changed
  • Redirect resources that can access other sites (servers)
  • Redirection is two requests. Cannot use request object to share data
Forwarding features: forward
  • Forwarding address bar path unchanged
  • Forwarding can only access resources under the current server
  • Forwarding is a request that can be shared using a request object
Path writing
  • Relative path: a unique resource cannot be determined by relative path

    • For example:/ index.html
    • Path does not start with /
    • Rule: find the relative position relationship between the current resource and the target resource
      • . /: current directory
      • .. /: back one level catalog
  • Absolute path: unique resources can be determined by absolute path

    • For example: http://localhost/day/responseDemo
    • day/responseDemo
    • Path starting with /
    • Rule: judge who uses the defined path? ->Determine where the request will come from in the future
      • For client browser: need to add virtual directory (access path of project)
        • It is recommended to obtain the virtual directory dynamically: request.getContextPath()
        • <a>, < form > redirect
      • For servers: no need to add virtual directory
        • Forwarding path

Server output character data to browser

step
  1. Get character output stream
  2. output data
// Before getting the stream object, set the default encoding of the stream to utf-8 response.setCharacterEncoding("utf-8"); // Tell the browser the encoding of the message body data sent by the server. It is recommended that the browser use this encoding to decode // response.setHeader("content-type","text/html;charset=utf-8"); // Simplify to the following code response.setContentType("text/html;charset=utf-8"); // Get character output stream PrintWriter pw = response.getWriter(); // Automatically destroyed after a response // Output data to page pw.write("<h1>hello response</h1>");
Pay attention to the confusion
  • PrintWriter pw = response.getWriter();: the default encoding of the obtained stream is ISO-8859-1
  • Set the default encoding for the stream
  • Tell the browser the encoding used by the response body
  • Simple form (set the encoding before getting the stream): response.setContentType("text/html;charset=utf-8");

Server output byte data to browser

step
  1. Get character output stream
  2. output data
// Get byte output stream ServletOutputStream sos = response.getOutputStream(); // output data sos.write("hello".getBytes());

ServletContext object

concept

  • It represents the whole web application and can communicate with the container (server) of the program

obtain

  • Get from the request object: request.getServletContext();

  • Get from HttpServlet: this.getServletContext();

ServletContext context1 = request.getServletContext(); ServletContext context2 = this.getServletContext(); // context1 == context2

function

  • Get MIME type

    • MIME type: a file data type defined in the process of Internet communication
    • Format: large type / small type text / HTML image / jpeg
    • Get: String getMimeType(String file)
  • Domain objects: sharing data

    • setAttribute(String name,Object value)
    • getAttribute(String name)
    • removeAttribute(String name)
    • ServletContext object scope: all users all requested data
@WebServlet("/servletContextDemo1") public class ServletContextDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // Set data context.setAttribute("msg","hello"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } @WebServlet("/servletContextDemo2") public class ServletContextDemo2 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // get data Object msg = context.getAttribute("msg"); System.out.println(msg); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
  • Method to get the real (server) path of the file: String getRealPath(String path)
@WebServlet("/servletContextDemo3") public class ServletContextDemo3 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get through HttpServlet ServletContext context = this.getServletContext(); // Get the server path of the file String realPath = context.getRealPath("/b.txt");// Resource access under web Directory String realPath2 = context.getRealPath("/WEB-INF/c.txt");// Resource access under WEB-INF directory String realPath3 = context.getRealPath("/WEB-INF/classes/a.txt");//Resource access in src directory } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }

11 June 2020, 02:31 | Views: 7402

Add new comment

For adding a comment, please log in
or create account

0 comments