10.5_HttpServletRequest 和 HttpServletResponse

A, Servlet configuration

   1. The full path match

    Begin with / / a / aa / bb

    localhost: 8080 / Project Name / aa / bb

   2. path matching, matching first half

    To / start, but in the end * / a / * / *

    * In fact, it is a wildcard, matches any character

     localhost: 8080 / Project Name / aa / bb

  3. extension matches

    Writing: no / to * start * extension * .aa * .bb.


二、ServletContext

  Servlet context

     Each web project is only one ServletContext object. To put it plainly is, no matter what the servlet inside, get to the objects of this class are the same.

  How to get objects

  1. Get the object
    ServletContext context = getServletContext ();

  what's the effect

    1. Obtain global configuration parameters
    2. Get Resource Project web
    3. The data access, sharing of data between fields servlet objects

  2. To achieve the absolute path in access to resources inside tomcat

    First get the path, and then himself InpuStream new new

    context.getRealPath ( "") // here is that the project root directory in tomcat inside.


    D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\


    String path = context.getRealPath("file/config.properties");

    D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties


      getResourceAsStream access to resources flow object

    Directly opposite to the path, and then obtaining the stream object.


  When 3.ServletContext created when destroyed?

    Server startup, will be for each web application hosting to create a ServletContext object

    Managed removed from the server, or shut down the server.

    ServletContext the scope

    Long on this project, you can take. As long as the same project. A project to deposit, withdraw at B project, is to take less of? Different ServletContext object.


三、HttpServletRequest

  This object encapsulates all the data submitted by the client over.

    1. The client requests may be acquired header information

      得到一个枚举集合
      Enumeration<String> headerNames = request.getHeaderNames();
      while (headerNames.hasMoreElements()) {
      String name = (String) headerNames.nextElement();
      String value = request.getHeader(name);
      System.out.println(name+"="+value);

      }

    2. Get the data submitted by the client over


      String name = request.getParameter("name");
      String address = request.getParameter("address");
      System.out.println("name="+name);
      System.out.println("address="+address);

      -------------------------------------------------

      // name = zhangsan & name = lisi & name = wangwu key may correspond to a plurality of values.

      Map<String, String[]> map = request.getParameterMap();

      Set<String> keySet = map.keySet();
      Iterator<String> iterator = keySet.iterator();
      while (iterator.hasNext()) {
        String key = (String) iterator.next();
        System.out.println("key="+key + "--的值总数有:"+map.get(key).length);
        String value = map.get(key)[0];
        String value1 = map.get(key)[1];
        String value2 = map.get(key)[2];

        System.out.println(key+" ======= "+ value + "=" + value1 + "="+ value2);
    }

    3. Get Chinese data

      Client submits the data to the server, if the data with the Chinese, then there may be garbled situation, you can refer to the following solutions.

      If GET method

      1. Code transcoding
        String = request.getParameter username ( "username");
        String password = request.getParameter ( "password");

        System.out.println ( "the userName =" + username + "password = == "+ password);

        // GET request over the data in the url address bar has been encoded, so we get to is garbled,
        // Tomcat received a batch of data, getParameter default to ISO-8859-1 decoding

        // Return an array of bytes let text corresponding to ISO-8859-1, utf-8 then press Assembling string
        username = new string (username.getBytes ( " ISO-8859-1"), "UTF- . 8 ");
        System.out.println (" the userName = "+ username +" == password = "+ password);

        done directly disposed inside tomcat, after the get request over the data always in UTF-8 encoding.

      2. do the setting process inside the tomcat conf / server.xml = add the URIEncoding "UTF-. 8"

        <Connector connectionTimeout = "20000" Port = "8080" = Protocol "the HTTP / 1.1" the redirectPort = "8443" = the URIEncoding " UTF-8 "/>


     If POST method

      The said body is provided inside the character code of the request. get way, with this line is useless
      request.setCharacterEncoding ( "UTF-8") ;
           this line must be written prior disposed getParameter.

四、HttpServletResponse

     1. responsible for returning data to the client.

     2. output data to the page


    // character stream so as to write data
    //response.getWriter().write("<h1>hello Response ... </ h1 of> ");

    // byte stream so as to write data
    response.getOutputStream () .write ( "hello response2222 ..." getBytes ().);


    3. The response data in Chinese, so there may be Chinese garbled

      Character stream output

        response.getWriter()


        1. Specify the output to the client when the text using UTF-8 encoding
        response.setCharacterEncoding ( "UTF-8");

        2. the direct provisions of the browser to see this data, the encoded using what look.
        response.setHeader ( "Content-Type", "text / HTML; charset = UTF-8");

        . response.getWriter () the Write ( "I do not hi garbled");

 

        Output byte stream

           response.getOutputStream()

          1. Specify browser to see this code table data used
          response.setHeader ( "Content-Type", "text / html; charset = UTF-8");

          Chinese designated with the code table 2. The output
          response.getOutputStream ( ) .write ( "I will not be garbled." getBytes ( "UTF-8 ".));


          --------------------------------------------

          Whether byte stream or character stream, a direct line of code on it.

            response.setContentType("text/html;charset=UTF-8");

            Then you can write data.

   

    4. Implement the Chinese file download

      For browser type, file name encoding process to make Firefox (Base64), IE, Chrome ... using URLEncoder

      If the name of the file with the Chinese, you need to file name encoding process
      if it is IE, or Chrome (Google Chrome), using the coding URLEncoding
      If Firefox, use Base64 encoding
      1. Get the visiting client type       

        response.setContentType("text/html;charset=UTF-8");
        String filename = request.getParameter("filename");
        System.out.println(filename);
        filename= new String(filename.getBytes("ISO-8859-1"),"Utf-8");
        System.out.println(filename);
        InputStream is= getServletContext().getResourceAsStream("dwlon/"+filename);

        Request.getHeader clientType = String ( "the User-- Agent");
        IF (clientType.contains ( "Firefox")) {
          fileName = DownLoadUtil.base64EncodeFileName (fileName);
        } {the else
          IEs, or the Chrome (Google Chrome),
          for Chinese encoding process name
          fileName = the URLEncoder.encode (fileName, "UTF-. 8");
      }

        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        OutputStream os= response.getOutputStream();
        int len=0;
        byte[] arr = new byte[1024];
        while((len=is.read(arr))!=-1) {
        os.write(arr, 0, len);
        }
          os.close();
          is.close();

Fifth, the request forwarding and redirection

  1. Redirect

     Writing a
      response.setStatus (302);
      response.setHeader ( "the Location", "login_success.html"); * /

      redirection wording: reorient i.e. in a jump parameter
     writing two

      response.sendRedirect("login_success.html");

      1. The address is displayed on the path to the last address of that resource

      2. The number of requests least twice, after the first request to the server, as well as a return address 302, according to this address in the browser, perform a second visit.

      3. can jump to any path. Not their project can also jump.

      4. slightly lower efficiency, execution requests.

      The subsequent requests, can not use the data stored in the last request, or can not use a request object on, because it is different requests.

   2. Request Forwarding

      Forwards the request wording: i.e. the parameters in a jump
      request.getRequestDispatcher ( "login_success.html") forward ( request, response);.

      1. The address is displayed on the servlet request address. Returned 200 ok

      2. The number of requests only once, because it is an internal server to help clients perform follow-up work.

      3. Jump resource path can only own projects.

      4. slightly higher efficiency, because the request only once.

      5 can use a request object.

    3. The above two methods, also known as client server-side jumps and jump

Guess you like

Origin www.cnblogs.com/zyyzy/p/12555331.html