Request and response

Source: Internet
Author: User
Tags error status code

Request and response

 

 

The process for the server to process the request:

    • Each time the server receives a request, it will open up a new thread for the request.
    • The server encapsulates the request data of the client into the request object. The request is the carrier of the request data!
    • The server also creates an object that is connected to the client and can be used to send a response to the client.

1. HttpServletResponse object

1. Sending status code-related methods

ServletResponse: Protocol-independent type.

HttpServletResponse: protocol-related type

Status Code: 200 indicates successful, 302 indicates redirection, 404 indicates client error (resource access does not exist), and 500 indicates Server Error
  • SendError (int SC): Send an error status code, such as 404,500
  • SendError (int SC, String msg): sends an error status code and can contain an error message.
  • SetStatus (int SC): Status Code of successful sending, which can be used to send 302
Case:
@ WebServlet (name = "AServlet", urlPatterns = "/Aservlet") public class AServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {response. sendError (404, "resource exists, but you are still sending 404 ");}}
2. Response Headers: Content-Type, Refresh, and Location
  • SetHeader (String name, String value): applicable to single-value response headers, such
Response. setHeader ("aaa", "AAA ");
  • AddHeader (String name, String value): Applicable to multi-value response headers, for example:
Response. addHeader ("aaa", "ddd"); response. addHeader ("aaa", "ccc"); response. addHeader ("aaa", "fff ");
  • SetIntHeader (String name, int value): applicable to single-value int-type response headers, for example:
Response. setIntHeader ("Content-size", 888 );
  • AddIntHeader (String name, int value): Applicable to multi-value int type Response Headers
  • SetDateHeader (String name, long value): applicable to a single response header of the millisecond type, for example:
Response. setDateHeader ("expires", 1000*60*60*24); // The page expiration time is 24 hours.
  • AddDateHeader (String name, long value): Applicable to Multiple Response Headers worth milliseconds
Common setHeader (String name, String value). case:
    • Send 302 and set the Location header to complete temporary redirection!
/** Demonstrate redirection * the user requests BServlet, and then the BServlet responds to 302, and provides the Location header **/@ WebServlet (name = "BServlet", urlPatterns = "/BServlet ") public class BServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println ("BServlet");/** redirection: * 1. Set Location * 2. Send status code 302 **/response. setHeader ("Location", "/CServlet"); response. sendError (302 );}}
/*
* The browser redirects to this address.
**/
@ WebServlet (name = "CServlet", urlPatterns = "/CServlet ")
Public class CServlet extends HttpServlet {
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System. out. println ("CServlet ");
}
}
// BServlet Response Header

HTTP/1.1 302
Location:/CServlet
Content-Length: 0
Date: Wed, 30 Aug 2017 01:57:17 GMT

// BServlet Request Header

GET/BServlet HTTP/1.1
Host: localhost: 8080
User-Agent :*****
Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, */*; q = 0.8
Accept-Language: zh-CN, zh; q = 0.8, en-US; q = 0.5, en; q = 0.3
Accept-Encoding: gzip, deflate
Cookie: Idea-e96526d7 = db12919d-58f1-479a-b0f7-3104911c767b; Webstorm-2933ea9e = 87a0f860-7465-47bb-8d57-4358bd45ea39; JSESSIONID = AD5DC7F501C87B36FF2186A0A1596564
Connection: keep-alive
Upgrade-Insecure-Requests: 1

// CServlet Response Header

HTTP/1.1 200
Content-Length: 0
Date: Wed, 30 Aug 2017 01:57:17 GMT

// CServlet Request Header

GET/CServlet HTTP/1.1
Host: localhost: 8080
User-Agent :*****
Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, */*; q = 0.8
Accept-Language: zh-CN, zh; q = 0.8, en-US; q = 0.5, en; q = 0.3
Accept-Encoding: gzip, deflate
Cookie: Idea-e96526d7 = db12919d-58f1-479a-b0f7-3104911c767b; Webstorm-2933ea9e = 87a0f860-7465-47bb-8d57-4358bd45ea39; JSESSIONID = AD5DC7F501C87B36FF2186A0A1596564
Connection: keep-alive
Upgrade-Insecure-Requests: 1

    • Regularly Refresh and set the Refresh header, which can be understood as timed redirection.
/** Demonstrate timed Refresh * set a Refresh, indicating timed Refresh **/@ WebServlet (name = "DServlet", urlPatterns = "/DServlet ") public class DServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException {/** is used to send the response body **/PrintWriter writer = response. getWriter (); writer. print ("Welcome to xxx! The page is automatically displayed in 5 seconds! "); // Set the response Header response. setHeader (" Refresh "," 5; URL =/EServlet ");}}
    • Disable browser Cache: Cache-Control, pragma, expires
/** Disable browser cache **/@ WebServlet (name = "FServlet", urlPatterns = "/FServlet") public class FServlet extends HttpServlet {protected void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setHeader ("Cache-Control", "no-cache"); response. setHeader ("Pragma", "no-cache"); response. setDateHeader ("Expires",-1 );}}
    • <Meta> the tag can replace the response header: <meta http-equiv = "Content-Type" content = "text/html"; charset = UTF-8>
3. response body: it is usually html or two streams of the image response:
    • ServletOutputStream is used to send byte data to the client. ServletOutputStream out = response. getOutputStream ();
    • PrintWriter, used to send character data to the client and requires encoding. PrintWriter writer = respones. getWriter ();
    • Two streams cannot be used at the same time.
Case: Use PrintWriter to send character data use ServletOutputStream to send byte data (image) redirection: Set 302, set Location, where only Location is changed, so Java provides a shortcut to complete redirection. SendRedirect (String location) method response. sendRedirect ("http://www.baidu.com"); 2. Data in the HttpServletRequest Object request protocol can be obtained through the request object. The request encapsulates all the request data of the client, and GET has no request body.

1. obtain common information

    • Obtain the Client IP address. Case: IP address blocking, request. getRemoteAddr ();
    • Request Method, request. getMethod (), POST or GET

2. Get the Request Header

    • String getHeader (String name): applicable to single-value Headers
    • Int getIntHeader (String name): applicable to single-value int type request headers
    • Long getDateHeader (String name): applicable to single-value millisecond-type request headers
    • Enumeration <String> getHeaders (String name): Applicable to multi-value request headers

Case:

    • Use User-Agent to identify User browser types
1 @ WebServlet (name = "AServlet", urlPatterns = "/AServlet") 2 public class AServlet extends HttpServlet {3 protected void doGet (HttpServletRequest request, response) 4 throws ServletException, IOException {5 String addr = request. getRemoteAddr (); 6 System. out. println ("IP:" + addr); 7 System. out. println ("METHOD:" + request. getMethod (); 8 String userAgent = request. getHeader ("User-Agent"); 9 // System. out. println (userAgent); 10 // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) chrome/60.0.3112.113 Safari/537.3611 // indicates whether Chrome is included. if so, the user uses the google browser 12 if (userAgent. toLowerCase (). contains ("chrome") {13 System. out. println ("Hello:" + addr + ", you are using Google"); 14} else if (userAgent. toLowerCase (). contains ("firefox") {15 System. out. println ("hello," + addr + ", you are using Firefox"); 16} 17}
    • Anti-leech: if a request is not sent through a hyperlink on this site, an error code 404 is sent. Referer: The request header indicates the request source.
@ WebServlet (name = "BServlet", urlPatterns = "/BServlet") public class BServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/** use the Referer request Header for anti-leech protection * directly input in the address bar, then the Referer header value is null **/String referer = request. getHeader ("Referer"); System. out. println (referer); if (referer = null |! Referer. contains ("localhost") {response. sendRedirect ("http://www.baidu.com");} else {System. out. println ("hello ");}}}

3. Obtain the request URL

Http: // localhost: 8080/day10_2/AServlet? Username = xx & password = yyy

  • String getScheme (): Get protocol, http
  • String getServerName (): Get the server name, localhost
  • String getServerPost (): Get the server port, 8080
  • String getContextPath (): Get the project name,/day10_2
  • String getServletPath (): Get the Servlet Path,/AServlet
  • String getQueryString (): Get the parameter part, that is, the part after the question mark, username = xx & password = yyy
  • String getRequestURI (): Get the request URI, which is equal to the project name + Servlet Path,/day10_2/AServlet
  • String getRequestURL (): Get the request URL, which is equal to the entire request path without parameters, http: // localhost: 8080/day10_2/AServlet

4. GET request parameters: the request parameters are sent to the service by the client, which may be in the Request body (POST ), it may also be after the URL (GET ).

  • String getParameter (String name): obtains the request parameter value of the specified name. It is applicable to single-value request parameters.
  • String [] getParamerValues (String name): Get the request parameter value of the specified name, applicable to multi-value Request Parameters
  • Enumeration <String> getParameterName (): obtains the names of all request parameters.
  • Map <String, String []> getParameterMap (): obtains all request parameters, where key is the parameter name and value is the parameter value.
  • Case: hyperlink Parameters
  • Case: form data
1 <! DOCTYPE html> 2 
1/* 2 * demonstrate request Parameters! 3 **/4 @ WebServlet (name = "AServlet", urlPatterns = "/AServlet") 5 public class AServlet extends HttpServlet {6 protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {7 String username = request. getParameter ("username"); 8 String password = request. getParameter ("password"); 9 String [] Hober = request. getParameterValues ("holobby"); 10 System. out. println (username + "," + password + "," + Arrays. toString (holobby); 11/* 12 * test to obtain the names of all request Parameters 13 **/14 Enumeration names = request. getParameterNames (); 15 while (names. hasMoreElements () {16 System. out. println (names. nextElement (); 17} 18/* 19 * Get all request parameters and encapsulate them into Map 20 **/21 Map <String, String []> map = request. getParameterMap (); 22 for (String name: map. keySet () {23 String [] values = map. get (name); System. out. println (name + "=" + Arrays. toString (values); 24} 25 System. out. println ("hello"); 26} 27 protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {28 System. out. println ("GET:" + request. getParameter ("xxx"); 29 System. out. println ("GET:" + request. getParameter ("yyy"); 30} 31}

5. Request forwarding and request include:

RequestDispatcher rd = request. getRequestDispatchet ("/MyServlet"); use request to obtain the RequestDisapatcher object. The parameter of the method is the Servlet Path of the forwarded or contained Servlet.

  • Request forwarding:Rd. forward (request, response );
  • Request includes: rd. include (request, response );

Sometimes one request can be completed only after multiple servlets are collaborated. Therefore, you need to jump to another Servlet in one Servlet!

    • A request must be forwarded and included across multiple servlets.
    • Request forwarding: The response body is completed by the next Servlet. The current Servlet can set the Response Header (leave the header blank );
    • Request inclusion: the response body is jointly completed by two servlets (both are left ).
    • Both request forwarding and request inclusion are within the same request range, and the same request and response are used.

6. request domain

Servlet's three domain objects: request, session, and application all have the following methods:

    • Void setAttribute (String name, Object value)
    • Object getAttribute (String name)
    • Void removeAttribute (String name)
    • In the same request range, request. setAttribute () and request. getAttribute () are used to transmit values. The previous Servlet calls setAttribute () to save the values, and the other Servlet calls getAttribute () to obtain the values.

    

 

7. Differences between request forwarding and redirection

    • Request Forwarding is a request and a response, and redirection is a response of two requests.
    • The address bar of request forwarding does not change, but redirection displays the address of the next request.
    • Request forwarding can only be forwarded to other servlets in this project. Redirection not only redirects to other servlets in this project, but also to other projects.
    • Request Forwarding is a server-side action. You only need to provide the forwarded Servlet Path, And the redirection must provide requestURI, that is, containing the project name.
    • The efficiency of request forwarding and redirection is high because it is a request.
      • To change the address bar, you must redirect
      • To obtain data in the request field in the next Servlet, you must use forwarding.
/** Demonstrate request forwarding and inclusion * Note that a Tomcat cannot contain the same name and urlPatterns; otherwise, an exception is thrown. **/@ WebServlet (name = "OneServlet ", urlPatterns = "/OneServlet") public class OneServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println ("OneServlet"); response. setHeader ("aaa", "AAA"); // set the Response Header/** add an attribute to the request domain **/request. setAttribute ("username", "zhangsan") response. getWriter (). print ("hello OneServlet"); // you can specify the response body. The response body is displayed when it is included, and the request is not displayed when it is forwarded. getRequestDispatcher ("/TwoServlet "). include (request, response); // The request contains // equivalent to calling the TwoServlet service () method // request. getRequestDispatcher ("/TwoServlet "). forward (request, response); // request forwarding }}@ WebServlet (name = "IncludeTwoServlet", urlPatterns = "/include/TwoServlet ") public class TwoServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println (request. getAttribute ("username"); System. out. println ("TwoServlet... "); response. getWriter (). print ("hello TwoServlet"); // set the response body }}

Iii. Encoding

Common character encoding: ISO-8889-1 (Chinese characters not supported), gbk (system default encoding, China's country code), UTF-8 (universal code, supports the World's encoding)

1. Response Encoding

  • When response. getWriter () is used to send character data to the client, if no encoding is set before, iso is used by default, because iso does not support Chinese characters and must be garbled;
  • When using response. response. setCharacterEncoding () is used to set the encoding stream encoding to gbk or UTF-8. Of course, we usually select UTF-8, so that all sent characters use the configured encoding method.
  • When using response. response. setHeader ("Content-type", "text/html; charset = UTF-8") to set the response header and notify the browser that UTF-8 is used. The browser knows this through the Content-Type header, the browser also uses UTF-8.
  • SetHeader ("Content-type", "text/html; charset = UTF-8") shortcut: setContentType ("text/html; charset = UTF-8 ").

2. Request Encoding

  • What is the encoding of the request parameters sent from the client to the server? The client first opens a page and then submits a form or clicks a hyperlink. What is the encoding of the server response when requesting this page, what is the encoding used by the client to send a request?
  • What encoding is used by default on the server side to decode the parameters: the default ISO-8859-1 on the server side to decode, there must be garbled.
  • Request Encoding is divided into two types: GET and POST. GET request parameters are not in the Request body, while POST request parameters are in the Request body. Their processing methods are different!
  • GET Request Encoding:
    • String username = new String (request. getParameter ("iso-8859-1", "UTF-8 "));
    • Configure URIEncoding = UTF-8 in server. xml
  • POST Request Encoding:
    • String username = new String (request. getParameter ("iso-8859-1", "UTF-8 "));
    • Call request. setCharacterEncoding ("UTF-8") before obtaining parameters ");

3. URL Encoding

Form Type: Content-Type: application/x-www-form-urlencoded, which is to convert the form into hexadecimal format followed by two digits.

When the client and the server transmit Chinese characters, it must be converted into a suitable network method.

  • It is not character encoding
  • It is used to transmit parameters between the client and the server.
  • URL encoding requires the first character encoding. After decoding the string, you can get byte []. Then, convert the byte less than 0 to 256, convert it to hexadecimal notation, and add a %.
  • By default, POST requests use URL encoding. Tomcat uses URL Decoding automatically.
  • URL encoding: String username = URLEncoder. encode (username, "UTF-8 ");
  • URL Decoding: String username = URLEncoder. decode (username, "UTF-8 ");

 

We need to encode the Chinese parameters in the Link Using url and jsp, because HTML cannot provide Java code.

4. Path

  • <Url-pattern> path (Servlet Path) in web. xml)
    • Either start with "*" or start "/"
  • Forwarding and inclusion path
    • Start with "/": relative to the current project path, for example, http: // localhost: 8080/project name/
    • Not starting with "*": relative to the current Servlet Path.
  • Redirection path (client path)
    • Starting with "/": relative to the current host, for example, http: // localhost: 8080/, You need to manually add the project name
  • Superlinks and form paths on the page
    • The client path is the same as redirection. You need to add a project name.
  • ServletContext
    • Relative to the current project directory, that is, the directory where the current index. jsp is located
  • ClassLoader
    • Relative classes directory
  • Class obtains the resource path
    • Relative classes directory starting "/"
    • The Directory of the current. class file does not start.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.