JavaWeb-Http request message-Request to get the request message (basic) code demo

Http

Concept : Hyper Text Transfer Protocol Hyper Text Transfer Protocol

Transmission protocol: defines the format of the data sent when the client and the server communicate

Features :

  1. Advanced protocol based on TCP/IP

  2. Default port number: 8080

  3. Based on the request/response model; one request corresponds to one response

  4. Http protocol is stateless, each request is independent of each other, and data cannot be exchanged

Request message data format:

  • Request line

    Request method request url request protocol/version

    Request method: (the Http protocol has 7 request methods, 2 commonly used)

    get:

    1. The request parameter is in the request line, after Url
    2. The requested URL is limited
    3. Not very safe

    post:

    1. Request parameters are in the request body
    2. There is no limit to the URL length of request parameters
    3. Relatively safe
  • Request header : The client browser tells the server some information

    Request header name: request header value

    1. User-Agent: The browser tells the server that I visit the version of the browser you are using

      The information of the header can be obtained on the server side to solve the compatibility problem of the browser

    2. Referer: Tell the server, where does the current request come from?

      ​ Role:

      Anti-hotlinking : Principle: On the download server, judge whether the URL (source) submitted in the previous step is what I requested, if it is requested by me, then it can be downloaded, if not, it is not allowed to download

      quantity survey job

  • Request blank line

    Blank line is used to separate the request header of the POST request and the request body

  • Request body (body)

    Encapsulate the request parameters of the post request message

Request: (Get request message)

Principles of Request and Response Objects

  1. First, our browser sent me a request (request message), and then our request came with the request message to find our resources, because we configured the url-pattern on the server side and found this class, Tomcat will automatically execute this method, which is : The tomcat server will create the corresponding ServletDemo01 object according to the resource path in the requested URL
  2. tomcat server is created requestand responsethe object, requestthe object encapsulates the request message data
  3. Will requestand responsetwo objects passed to the service method, and the method is called Service
  4. We can requestget the request message data through the responseobject, and set the response message data through the object
  5. (Browser replies with response message) Before the server responds to the browser, it will responsetake out the response message data set by the programmer from the object

Request inheritance architecture

ServletRequest interface inherits HttpServletRequest

The HttpServletRequest interface implements the RequestFacade class (Tomcat)

Request Get request line data

GET /Demo02_war_exploded /sd/demo?name=zhangsan HTTP/1.1

method:

  1. Get request method: GET

    String getMethod()

  2. Get the virtual directory: Demo02_war_exploded

    String getContextPath()

  3. Get the Servlet path: sd

    String getServletPath()

  4. Get the request parameter of get method: name=zhangsan

    String getQueryString()

  5. Get request URI: /Demo02_war_exploded /sd

    String getRequestURI(); /Demo02_war_exploded /sd

    StringBuffer getRequestURL() http://localhost//Demo02_war_exploded /sd

    URI: Uniform Resource Identifier (URI is smaller than URL)

    URL: Uniform Resource Locator

  6. Get the protocol and version: HTTP/1.1 (just understand)

    String getProtocol()

  7. Get the IP address of the client: (just understand it)

    String getRemoteAddr()

The code demonstrates the above method

@WebServlet("/sd")
public class ServiceDemo01 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取请求方式  GET
        System.out.println(request.getMethod());
        //获取虚拟目录  Demo02_war_exploded
        System.out.println(request.getContextPath());
        //获取Servlet路径  sd
        System.out.println(request.getServletPath());
        //获取get方式请求参数
        System.out.println(request.getQueryString());
        //获取请求URI
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());
        //协议和版本
        System.out.println(request.getProtocol());
        //获取客户机IP
        System.out.println(request.getRemoteAddr());
    }
}

Insert picture description here

Get request header data

method:

  1. String getHaeder (String name): Get the requested value by the name of the request header
  2. Enumeration getHeaderNames(): Get the names of all request headers
@WebServlet("/sd2")
public class ServiceDemo02 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
       //获取所有的请求头名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
    
    
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.out.println(s+header);
        }
    }
}

Insert picture description here

//演示获取请求头数据:user-agent 来查看当前我们用的什么浏览器
String agent = request.getHeader("user-agent");
if (agent.contains("Chrome")){
    
    
    System.out.println("谷歌");
}else if (agent.contains("Firefox")){
    
    
    System.out.println("火狐");
}

Insert picture description here

Anti-hotlinking: (demonstrate to obtain request header data: referer)

The first project simulation official is called Demo02

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

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //演示获取请求头数据 : referer
        String referer = request.getHeader("referer");
        if(referer != null){
    
    
            if (referer.contains("/Demo02_war_exploded")){
    
    
                System.out.println("看电影");
            }else {
    
    
                System.out.println(referer);
                System.out.println("来我这里看电影");
            }
        }
    }
}

page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>官方的电影院</title>
  </head>
  <body>
 <a href="/Demo02_war_exploded/sd4">点我上天堂</a>
  </body>
</html>

When you create a new project, it is called Demo04 (note that you need to create a new Tomcat and distinguish the port number)

index.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>我自己的电影院</title>
  </head>
  <body>
  <a href="http://localhost:8080/Demo02_war_exploded/sd4">点我上天堂</a>
  </body>
</html>

First start Demo04 and then start Demo02

After entering Demo02 click point me to heaven

Insert picture description here
Insert picture description here

Click in Demo04

Insert picture description here
Insert picture description here

Get request body data

Request body: Only the POST request method has a request body, and the request parameters of the POST request are encapsulated in the request body

  1. Get the stream object

    BufferedReader getReader( ) ; Get character input stream, the corresponding can only manipulate character data

    ServletInputStream getInputStream (): Get byte input stream, can operate all types of data

  2. Then get the data from the stream object

Code demo:

@WebServlet("/std4")
public class ServletDemo04 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        BufferedReader reader = request.getReader();
        response.setContentType("text/html;charset=utf-8");
        String len=null;
        while ((len=reader.readLine())!=null){
    
    
            response.getWriter().write(len);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }
}

page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<body>
  <form action="${pageContext.request.contextPath}/std4" method="post"  enctype="text/plain" accept-charset="UTF-8">
    用户名:<input type="text" placeholder="请输入用户名" name="username"/> <br>
    密  码: <input type="password"  placeholder="请输入密码" name="pwd"/> <br>
      <input type="submit" value="提交">

  </form>
</body>

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/agood_man/article/details/108567245