Common methods of Request object in java web

Posted by ecg on Sat, 15 Feb 2020 16:51:00 +0100

Request principle

1. The request object and the response object are created by the server. Let's use them.

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

Request function

Get request message data

  • Get request line data
    Request line format:
    GET /learning/demo1?name=zhangsan HTTP/1.1
    Method:

     			1,Get request method 
     			 String getMethod()
     			2,(**)Get virtual directory
     			 String getContextPath()
     			3,Obtain Servlet Path (resource path)
     			String getServletPath()
     			4,Obtain get Mode request parameters
     			 String getQueryString()
     			5,(***)Get request uri and url
     					String getRequestURI()  /learning/demo1
     					StringBuffer getRequestURI() http:localhost/learning/demo1
     				URI: Uniform resource locator, wide range, e.g. Republic
     				URL: Uniform resource identifier, small scope, such as the People's Republic of China
     			6,Get agreement and version HTTP/1.1
     					String getProtocol()
     			7,Get client's IP address
     					String getRemoteAddr()
    
@WebServlet( "/requestDemo1")
public class RequestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 GET request method get
        String method = request.getMethod();
        System.out.println(method);
        //2 get virtual directory
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
        //3 get resource directory / requestDemo1
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        //4 get get request parameter name=lisi
        String queryString = request.getQueryString();
        System.out.println(queryString);
        //5 get uri/requestDemo1
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURI);
        System.out.println(requestURL);
        //http://localhost:8080/requestDemo1
        //6 get host 0:0:0:0:0:0:0:0:1
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
        //7 get Protocol HTTP/1.1
        String protocol = request.getProtocol();
        System.out.println(protocol);

    }
}

  • Get request header
    Method:
    (1) Get all the name s of the request header:
    Enumeration getHeaderNames();
    (2) Get the value of the request header
    String getHeader(name);
@WebServlet("/request/RequestDemo2")
public class RequestDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Get request header
        Enumeration<String> headerNames = request.getHeaderNames();
    //ergodic
        while(headerNames.hasMoreElements()){
            //System.out.println(headerNames.nextElement());
            String name = headerNames.nextElement();
            //(* *) get the value of the request header
            String header = request.getHeader(name);
            System.out.println(name+":"+header);

        }
    }
}

(3) Solve the compatibility of different browsers according to the value of user agent in request header
@WebServlet("/request/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String header = request.getHeader("user-agent");
        if(header.contains("Firefox"))
            System.out.println("Here comes the Firefox.");
        else if(header.contains("IE"))
            System.out.println("ie Coming");
    }
}

  • Get request body
    Only through post can there be a request body
    Step: 1. Get the flow object
    Byte input stream getInputStream()
    Character input stream getReader()
    2. Then take the data from the flow object
@WebServlet( "/RequestDemo5")
public class RequestDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get request message body - message parameters
        BufferedReader br = request.getReader();
        //Read data, read data from br
        String line = null;
        while((line=br.readLine())!=null){
            System.out.println(line);
            //username=lll&password=123
        }
    }

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

    }
}

Request other functions

1,General way to get request parameters: regardless of get still post Fine
(1)String getParamter(String name)
(2)String[] getParamterValues(String name)
(3)getParamterNames()
(4)Map<String,String[]> getParamterMap
(5) tip:Before obtaining parameters, set the coding
request.setCharacterEncoding("utf-8");
2,Request forwarding: a kind of url Jump mode
(1)step
①adopt request Object get request forwarder object:
②Use to forward: forward (*****)
request.getRequestDispatcher(Forward resource path).forward(request,response);
(2)Characteristic
①Browser address bar path does not change
②Can only forward to internal resources of the current server
③Forwarding is a request
3,shared data
*Domain object: a scoped object that shares data within a scope
request Domain: represents the scope of a request, which is used to share data among multiple resources for request forwarding
*Method:
(1)setAttribute():Store data
(2)getAttribute(): Obtain
(3)removeAttribute(): remove
4,Obtain ServletContext
ServletContext servletContext = request.getServletContext();

//General way to get request parameters
@WebServlet( "/RequestDemo6")
public class RequestDemo6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
//        System.out.println("post");
//        System.out.println(username);
        String[] hobbies = request.getParameterValues("hobby");
//        for (String hobby : hobbies) {
//            System.out.println(hobby);
//        }
        Enumeration<String> parameterNames = request.getParameterNames();
//        while(parameterNames.hasMoreElements()){
//            String name = parameterNames.nextElement();
//            System.out.println(name);
//            String parameter = request.getParameter(name);
//            System.out.println(name+":"+parameter);
//        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        //Two methods of traversing entrySet and keySet
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iterator = keySet.iterator();
        while(iterator.hasNext()){
            String it = iterator.next();
            System.out.println(it);
            String[] values = parameterMap.get(it);
            for (String value : values) {
                System.out.println(value);
            }
            System.out.println("------");
        }


    }

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

//Request forwarding and sharing data
@WebServlet( "/RequestDemo7")
public class RequestDemo7 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo7 comes");
        //Store data in the request domain
        request.setAttribute("msg","hello");
        //Forward to demo8 resource
        request.getRequestDispatcher("/RequestDemo8").forward(request,response);
    }
}

Published 16 original articles, won praise 0, visited 250
Private letter follow

Topics: Firefox IE