[JavaWeb] Request and Response study notes

table of Contents

Request

Request Get request information

   Get request line information

    Get request header information:

    Get request parameters:

    Processing post request Chinese garbled

Request other functions

    Domain object (shared data)

    Request forwarding: Click to see the difference between request forwarding and redirection

Response

Response operation response information

    Operation response line

    Set the response header

    Operation response body:

Response to Chinese garbled processing


Request

        When the user accesses the server through the browser, Tomcat encapsulates all the information in the Http request in the Request object, and the developer can obtain all the information sent in the browser through the request object method.

Request Get request information

   Get request line information

Request line information includes: request method request path (get request will carry parameters) protocol/version

Related API:

        reqeust.getMethod() ---->Get the request method

        request.getContextPath() ----->Get the application path of the project

        request.getRemoteAddr() ----->Get the requester's ip

        request.getQueryString() ------>Get all request parameters of get request

        request.getProtocol() ------->Get the protocol and version

request.getRequestURI() ----->Get the request path

getRequest URL (): Uniform resource locator (absolute path)

getRequest URI (): Uniform Resource Descriptor (relative path)

Code case:

public class RequestLineServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.1 获得请求方式
        String method = request.getMethod();
       //1.2 获得项目的虚拟发布名称(别名) - 用于动态的项目路径
        String contextPath = request.getContextPath(); 
        //1.3 获得远程主机的ip地址(指的是客户端的ip)
        String remoteAddr = request.getRemoteAddr();

        //1.4 获得?号后面的数据部分
        String queryString = request.getQueryString();

        //1.5 获得协议版本
        String protocol = request.getProtocol();

        //1.6统一资源定位符(绝对路径)
        StringBuffer requestURL=request.getRequestURL();
    
        //1.7统一资源描述符(相对路径)
        String requestURI = request.getRequestURI();
    }
}

    Get request header information:

getHeader(String): ---->Get string data according to key

Common request headers:

referer: ---->Get the source of the resource, if you enter directly, there is no referer

user-agent ---->System version and browser version

        Referer is often used to display the previous resource path, in the application process, used to prevent the hot link : for example, when someone visits news, if they are transferred from a correct and legal website, they can browse normally, if they point to specific news from an illegal website , The source of the page is someone else's website (the website address is unique). This forms a hotlink. So we can judge whether it is provided by our own website during a connection visit.

Code case:

public class RefererServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("网站内部后台被访问了");
        //多个人可以访问服务器 需要判断
        String referer = request.getHeader("referer");
        if("http://localhost:8080/day09/index.html".equals(referer)){
            System.out.println("自己网站的路径 可以继续访问");
        }else{
            System.out.println("钓鱼网站的路径 提示用户修改密码");
        }
    }
}

    Get request parameters:

string getParameter(String s) ------>Get the value according to the key

Map<String,String[]> getParameterMap() ------>Get all the key-value pair data and encapsulate it in the map

string[] getParameterValues() ------>Get a set of values ​​according to the key

Code case:

public class RequestParamServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");

       String[] hobbies = request.getParameterValues("hobby");

        Map<String, String[]> parameterMap = request.getParameterMap();
        //遍历
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println(entry.getKey() + "@@" + Arrays.toString(entry.getValue()));
        }
    }
}

    Processing post request Chinese garbled

        Regarding the problem of garbled code: it only occurs when the storage and reading codes are inconsistent. When the form submits data, the default code of the http protocol is iso-8859-1. The characteristic of this code is that it does not support Chinese, but it is There is no garbled problem when executing get requests. This situation is related to the version of tomcat. Tomcat 8.5 has already processed the Chinese garbled of get requests, but the post has not been processed, and we need to deal with it by ourselves. The way to deal with it is to just Just deal with it before getting the parameters.

//Set the requested encoding
request.setCharacterEncoding("utf-8");

This processing code must be placed first:

        The information of the request parameter is placed in the buffer.The code of the buffer can only be initialized once and set the code before the data is obtained.If the data is obtained from the buffer first, the code of the buffer is fixed and can no longer be modified.

Request other functions

    Domain object (shared data)

  • Domain object: an object with a scope that can share data within the scope
  • The reqeust domain: represents the scope of a request, and data can be shared between two resources that are forwarded in a request
  • The life cycle of the request: the request object is created when the request comes, and the request is destroyed when the response is generated

    Request forwarding: Click to see the difference between request forwarding and redirection

Response

Response operation response information

    Operation response line

The response line information includes the protocol/version number and status code:

status code:

  • 200: request response succeeded
  • 302: Redirect, the browser re-initiates the second request
  • 304: The browser reads the local cache by default
  • 404: File not found
  • 405: The get or post method is not found or the parent class get or post method is manually called
  • 500: Server internal code error.   

    Set the response header

Common response headers:

  • location: set the redirected address
  • refresh: regular refresh
  • content-type: set the mime type and encoding of the returned data
  • content-disposition: Set the content to open the response back in the declaration mode, used for file download, the value is attachment; filename=file name. Suffix

API:

     setHeader(String response header, String value): Set the value to the response header of string type, and the later setting will overwrite the previous setting

     addHeader (Strign response header, String value): add a response header of type String

Code case: redirect

public class ThreeServletServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置状态吗
        //response.setStatus(302);
        //2.设置响应头地址信息 可以跳转站外地址
        //response.setHeader("location", "http://www.baidu.com/");
        //可以跳转站内资源  跟请求转发不一样的时候 需要加上项目的虚拟路径名称
        //请求转发: 只是服务器内部的动作 , 重定向是可以跳转服务器外部信息
        //response.setHeader("location", "/day09/fourServlet");


        //重定向的简化api
        response.sendRedirect( "/day09/fourServlet");
    }
}

   Operation response body:

 API
    PrintWriter getWriter();//Generally write character data with
    ServletOutputStream getOutputStream();//General file download use
    Note:
        Two streams cannot appear in the same logic, and the two streams are mutually exclusive

Response to Chinese garbled processing

setContentType("mime type,charset=utf-8")

  • Set the data mime type for response back
  • Set the character encoding of the data
  • Tell the browser what encoding to parse the data
public class ResponseBodyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 响应体其实就是流
         *  字节流 : 一般用于输出 图片 视频 文件..信息
         *      response.getOutputStream() 字节流
         *  字符流 : 一般用于输出 文本信息
         *      response.getWriter() 打印流 字符流
         *  api : 都是write 用于输出内容
         *      print的底层都是write  建议都用print方法输出内容
         *      注意: 字节流和字符流不能同时使用(会报错)
         */

        //我们需要特殊设置内容 通知浏览器 以什么方式 什么编码解析内容
        //设置响应的数据格式及编码 设置输入法  在中文下使用英文标点
        //出现在第一行
        request.setCharacterEncoding("utf-8");
        //response.setHeader("content-type" , "text/html;charset=utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("aaa<a href=''>百度一下</a>");
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/108628847