Notes-JavaWeb Learning Tour 10

Posted by blunt on Sun, 09 Jun 2019 00:53:27 +0200

Servlet

The server applet runs a server-side applet, which is an interface that defines the rules that Java classes are accessed by the browser (Java classes override this interface and can be recognized by the browser (tomcat)

Servlet method:

Init method: Executes only once, and the init method is executed when the Servlet is first accessed or created at server startup.

service method: can be executed multiple times, once per access to the server

destroy method: execute once before the server is shut down

ServletConfig getSerletConfig method: Get ServletConfig object

String getServletInfo: Get some information about the Servlet

Annotation Configuration

This web.xml is required to configure the project's path prior to Servlet3.0

After Servlet3.0 you can choose the project path by annotating the configuration

Subclasses of Servlet

A servlet is an interface that has two abstract subclasses, GenericServlet and HttpServlet.

package com.Data.HttpServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//Http has a common request method
//You can use the HttpServlet method to determine how requests are made
//Inherit HttpServlet
@WebServlet("/demo1")
public class HttpServletDemo extends HttpServlet{
    //Override parent method

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Execute this statement if it is a Get request
        System.out.println("doGet.....");//The browser directly accesses the server's address using Get
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Execute this statement if it is a Post request
        System.out.println("doPost");//Output result doPost
    }
}

Use post to access the server

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--Specify Address demo3-->
    <!--Specify access post-->
    <form action="/demo1" method="post">
        <input name="username" placeholder="enter one user name">
        <input type="submit" value="Sign in">
    </form>
</body>
</html>

HTTP:

Concept: Hyper Text Transfer Protocol Hypertext Transfer Protocol, which defines the format in which data is sent when communicating between client and server

Request message data format

1. Request line:

Format: Request Method (GET) Request url(/Hello.html) Request Protocol/Version (HTTP1.1)

When the request protocol is GET, the requested parameters are in the request line, and POST, the requested parameters are in the request body

2. Request Header: My browser tells the server what information I have

String format: Request header name: Request header value

Common request headers:

Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0

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

Referer: http://localhost:8080/Hello.html (my Firefox browser doesn't know how to display this header....)), which tells the server where I come from

3. Request blank line: is a blank line, separating the request header from the request body

Requestor: Encapsulates the request body parameters of a POST request message, username: zhangsan

Request principle:

1. The request and response objects are created by the server.

2. The request object is to get the request message, and the response object is to set the response message

request object inheritance architecture:

ServletRequest (Parent Interface)-->HttpServletRequest (Subinterface)--->RequestFacade (Implementation Class)

Functions of request

Get data for the requested row
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//Demonstrate Request Object Getting Request Row Data
@WebServlet( "/demo")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Request method for getting request rows
        //request object has tomcat server creation
        String method = request.getMethod();
        System.out.println(method);//GET
        //Get the virtual directory of the requested row
        String method1 = request.getContextPath();
        System.out.println(method1);//  /day13
        //Get the URI of the request line
        String method2 = request.getRequestURI();
        System.out.println(method2);//  /day13/demo
        //Get the IP address of the client
        String method3 = request.getRemoteAddr();
        System.out.println(method3);//  0:0:0:0:0:0:0:1
        //Get Request Parameters for Request Rows
        String method4 = request.getQueryString();
        System.out.println(method4);// name=zhangsan
    }
}
Get data for the request header
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


@WebServlet("/RDemo1")
public class RuquestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //Get the names of all request headers
        Enumeration<String> headerNames = request.getHeaderNames();
        //Traversal, equivalent to an iterator
        //True if there is the next element
        while(headerNames.hasMoreElements()){
            //Get Elements
            String name = headerNames.nextElement();
            //Find value by key
            String value = request.getHeader(name);
            System.out.println(name+"------"+value);
            
//          All Heads, Get Out
//            host------localhost:8080
//            connection------keep-alive
//            upgrade-insecure-requests------1
//            user-agent------Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
//            accept------text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
//accept-encoding------gzip, deflate, br
//accept-language------zh-CN,zh-HK;q=0.9,zh;q=0.8,en;q=0.7
//cookie------JSESSIONID=0329F34A83457E749B1818AFBE4C0A57; Idea-a0bb733=23efa255-9ce7-42d9-8d0b-9853348226b8; JSESSIONID=8FE68A2847DC38B4290ADBCE1BFD164F

        }
    }
}
Get Request Body Data

Request body: Request body only exists in POST request mode, which encapsulates request parameters for POST requests.

First, create an html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--Address of the binding server-->
    <form action="/day13/RDemo1" method="post">
    <input type="text" name="username"><br>
    <input type="text" name="password"><br>
        <!--Submit data to the server-->
    <input type="submit" value="register">
    </form>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/RDemo1")
public class RuquestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get Request Parameters of Requestor
        //Get the character stream
        BufferedReader reader = request.getReader();
        String line=null;
        while((line=reader.readLine())!=null){
            //Read a line and write a line
            System.out.println(line);// username=zhangsan&password=123
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }
}

Other functions:

The common way to get request parameters, whether a get request or a post request, can use the following methods to get parameter values

1.String getParameter(String name): Get the parameter value from the parameter name

2.String[] getParameterValues(String name): An array of parameter values based on the parameter name

3.Enumeration getParameterNames(); get parameter names for all requests

4.Map<String, String[]> getParameterMap(): Get a map set of all parameters (unlike 3, where three key-value pairs are obtained, one key gets only one value, and one key can cope with one value if the method is 4)

Demonstration of the Map method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--Address of the binding server-->
    <!--//Both post and get requests are the same -->
    <form action="/day13/Demo3" method="GET">
    <input type="text" name="username"><br>
    <input type="text" name="password"><br>
    <input type="checkbox" name="hobby" value="Play games">Play games
    <input type="checkbox" name="hobby" value="Watch movie">Watch movie
        <!--Submit data to the server-->
    <input type="submit" value="register">
    </form>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@WebServlet("/Demo3")
//Either GET or POST requests can use the following method to get the parameters of the request
public class RequestDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String,String[]> map = request.getParameterMap();
        //Save all keys in a collection
        Set<String> strings = map.keySet();
        for(String key : strings){
            //Get every key
            System.out.println(key);
            //Get the set of values
            String[] values = map.get(key);
            //Get each value
            for(String key2 : values){
                System.out.println(key2);
            }
            System.out.println("---------------");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Topics: PHP Java xml Tomcat Windows