Research on all the Request and Response member methods in JSP Servlet, servletrequest

Source: Internet
Author: User
Tags error status code url decode

Research on all the Request and Response member methods in JSP Servlet, servletrequest

HttpServletRequest and HttpServletResponse are parameters passed in methods such as doGet and doPost in Servlet. They undertake most of the functions in Http requests and responses, both the Request Parsing and response responses depend on these two objects. All of their methods and functions are summarized below, hoping to be helpful for learning Java Web development.

1. HttpServletRequest:

/** Record each request. get value * request. getAsyncContext (); AsyncContext * get the text content of asynchronous transmission * request. getAttribute (String); Object * Attribute is different from Parameter. Attr is set in the program with SetA, while Par is the Parameter for receiving web pages * mostly used for session setting, session. setA, which can be set to its own type. getP can only receive strings, while getA can be object * request. getAttributeNames (); Enumeration <String> * gets an Enumeration type, hasmoreelement, nextelement * request. getAuthType (); String * returns the name of the authentication method, which is basic, SSL, form, and client_cert. And digest. If there is no authentication, the value is null * AuthType can be found on the web. for configuration in xml, use <login-config> <auth-method> xx <real-name> xxx to configure * for remote webpage links, that is, enter the webpage address, A logon interface is displayed, where the * Authorization information in the file header * request is read. getCharacterEncoding (); String * returns the encoding used by the webpage. the value in the charset of the webpage * request. getContentLength (); int * is only used for POST requests, indicating the number of bytes of data sent * request. getContentLengthLong (); long * same as above, used for large data volumes, long eight bytes * request. getContentType (); String * gets the content-type, including encoding. <Meta content = "text/html; charset = gb2312" http-equiv = "Content-Type"/> * Content-Type: defines the network file Type and webpage encoding, determines the form and encoding in which the browser will read the file * request. getContextPath (); String * gets the root directory name of the project, such as/MyTestWeb. Returns the prefix of the URL of the specified servlet context (web application. * When using an absolute path, you can use getRealPath () (not recommended) and request. getSession (). getServletContext (). getRealPath ("/") * request. getCookies (); Cookie [] * obviously, the cookies returned from the web page. In the array form, cookies are saved in the form of name + value * request. getDateHeader ("String"); long * is used to convert the part of the specified header information to a long integer that is easy to convert to a time type, simplifying getHeaders * request. getDispatcherType (); DispatcherType * unknown... * request. getHeader ("headname"); String * Get specified header information * request. getHeaderNames (); Enumeration <String> * Get the name Word enumeration, used to traverse * request. getHeaders ("headersname"); Enumeration <String> * obtains multiple value sequences of one name and returns the enumerated values of all HTTP header names of the specified type in the request, it is very useful for header labels with multiple values. * Request. getInputStream (); ServletInputStream inherits from io. inputStream * obtains the request content. It can obtain the content transmitted by the post method in the webpage through send, but it must be instantiated through InputStreamReader * And InputStreamReader cannot be directly read as a string, to use BufferedReader to instantiate InputStreamReader *, you can use the readline of BufferedReader to obtain intermediate data. * You can also directly use the InputStream's read method to write to the read parameter. byte array * This method can only be read once. Because it is a stream, no request is returned after reading it. getIntHeader ("head"); int * obtains the value from the beginning * request. getLocalAddr (); String * gets the local address, which varies according to the access method. It is 127.0.0.1 or public ip * request. getLocale (); Locale (in util) * obtains local location information, if ZHCN and so on * request. getLocales (); Enumeration <Locale> * obtains Enumeration when multiple locations exist * request. getLocalName (); String * obtains the name of the local IP address. For example, 127.0.0.1 indicates localhost * request. getLocalPort (); int * Get the port number, This application is 8081 * request. getMethod (); String * gets the Http method, including get, head, put, delete, post, options * request. getParameter ("code"); String * Get the submit parameter, that is, the URL? The following content corresponds to one-to-one relationship. Even POST, this can only be obtained? The following parameter * the difference between POST and GET is that content can be written in send, and the parameters passed in the URL are still the same * request. getParameterMap (); Map <String, String []> * The returned type is String [] Because the parameter names may be the same, if you use getPara to return multiple values with the same name, the values will be combined. * PS: the Map Traversal method. Set <Entry <String, String []> set = map. entrySet (); first obtain EntrySet * and then obtain the Iterator of EntrySet <Entry <String, String []> it = set. iterator (); * use the iterative getNext method to obtain the Entry <String, String []> entry = it. next (); * use Entry. getvalue: Get the string array * r Equest. getParameterNames (); Enumeration <String> * obtains the Enumeration of parameter names * request. getParameterValues ("code"); String [] * obtain multiple values of parameters with the same name * request. getPart ("file"); Part * is used to upload a file. A Part is a file and the mime type is multipart/form-data *. The @ MultipartConfig annotation * request must be added to the program. getParts (); Collection <Part> * obtains a Collection of parts for uploading multiple files * request. getPathInfo (); String * returns any additional path information specified in the URL. Without parameters, it is generally relative to the Servlet Path * pathinfo. The returned string has passed through the Servlet server URL Decode. * Output: the part of the URL following the Servlet Path and before the query string. * Request. getPathTranslated (); String * path information mapped to the actual server path. * Request. getProtocol (); String * gets the protocol information and version number, that is, HTTP/1.1 * request. getQueryString (); String * is the query String appended to the URL. The data is still URL encoded. * Undecoded data is rarely used in servlets. Generally, getParameter is used to access various parameters. * Request. getReader (); BufferedReader * gets BufferedReader, which is the same as that of inputStream... * Request. getRealPath ("/"); String * gets the absolute path and is deprecated. Use request. getSession (). getServletContext (). getRealPath ("/") * request. getRemoteAddr (); String * Client IP * request. getRemoteHost (); String * client host name * request. getRemotePort (); int * client port number * request. getRemoteUser (); String * client user name * request. getRequestDispatcher (""); RequestDispatcher * forwards the Request, obtains the requested address, and shares a request * Request with the address. getRequestedSessionId (); Str Ing * returns the corresponding session id * request for this request. getRequestURI (); String * gets the request URL, does not contain the request content, does not contain the domain name * request. getRequestURL (); StringBuffer * obtains the URL, contains the domain name, does not contain the request content * has not been Decode by the Servlet server URL. * Request. getScheme (); String * return protocol name, http * request. getServerName (); String * Get the server name, local IP * request. getServerPort (); int * Get server port number * request. getServletContext (); ServletContext * obtains information about the Servlet, getServletConfig (). getServletContext (). getServerInfo () * request. getServletPath (); String * The part of the URL that calls Servlet. It does not contain additional path information and query strings. * Request. getSession (); HttpSession * is used to obtain the Session dialogue, which is used to communicate with webpages. * equest. getSession (boolean); HttpSession * request. getSession (true): If a session exists, it is returned. Otherwise, a new session is created. * Request. getSession (false): If a session exists, it is returned. Otherwise, NULL * request is returned. getUserPrincipal (); Principal * returns a java. security. principal object, which contains the name of the currently authorized user * use request. getUserPrincipal (). getName () obtains the username *. If the user does not pass the authentication, no return value is returned. The value is obtained only after the user logs on. After passing the JAAS authentication, the user logs on to the ** request. authenticate (HttpServletResponse response); boolean * proves to be true, reliable, or valid; authentication to make it take effect * request. changeSessionId (); String * Change the session id of the current session associa Ted with this request and return the new session id. * request. isAsyncStarted (); boolean * Indicates whether asynchronous transmission starts * request. isAsyncSupported (); boolean * Whether asynchronous transmission * isRequestedSessionIdFromCookie (); boolean * Whether SessionId is obtained from cookies * request. isRequestedSessionIdFromUrl (); boolean * Whether the SessionId is obtained from the URL. * request has been discarded. isRequestedSessionIdFromURL (); boolean * same as above, this does not discard * request. isRequestedSessionIdValid (); boolean * Check Check whether SessionId is valid * request. isSecure (); boolean * indicates whether the security protocol is used, such as https * request. isUserInRole ("role"); boolean * determines whether a user is a role of a certain type. The type can be in the web. xml configuration (tomcat-users.xml) * request. login ("user", "password"); void * use the user name and password to log on * request. logout (); void * User logout * request. Y (); request. policyall (); void * is used for thread operations. For details, see * request. removeAttribute ("at"); void * deletes a property value, corresponding to set * request. setAttribute ("at", request ); Void * set a property value * request. setCharacterEncoding ("UTF-8"); void * sets the encoding method used to obtain each character, it should be the same as the webpage encoding method * Only applicable to setting the encoding of the request body submitted by post instead of the queryString submitted by the get method. * This method tells the application server what encoding should be used to parse the post-uploaded content. * Request. startAsync (request, response); void * starts asynchronous transmission without the * request. upgrade () parameter; void * starts update? * Request. wait (12); * all classes that implement the thread have this method, used to wait */

2. HttpServletResponse

/** Response object * response. addCookie (new Cookie ("a", "aa"); void * adds cookie * response. addDateHeader ("date", 23456789l); void * adds the date * response to the header. addHeader ("asf", "sff"); void * adds the header information * response. addIntHeader ("fsf", 12); void * adds the value type * response to the header. encodeRedirectUrl ("UTF-8"); discard * response. encodeRedirectURL ("UTF-8"); String * uses the specified encoding to encode the URL entry and carries the sessionid, cross-application * response. encodeUrl ("UTF-8"); discard * response. e NcodeURL ("UTF-8"); String * uses the specified encoding to encode the URL entry and carries the sessionid. This application * If sessionId exists and is not obtained from the cookie, put it at the end of the url. Otherwise, the original url is directly returned. * Response. flushBuffer (); vodi * immediately sends the buffer character to the client as the browser * response. getBufferSize (); int * Get the buffer size * response. getCharacterEncoding (); String * Get encoding type * response. getContentType (); String * obtains the MIME type and encoding of Content * response. getHeaderNames (); Collection <String> * Get the name list of all headers * response. getHeaders ("aa"); Collection <String> * obtains the Value List of all aa headers * response. getLocale (); Locale * Get local information, such as zhcn * response. getOutputStream (); ServletOutputStream inherits from OutputStream * to get the output stream, which corresponds to inputStream and * response to bufferedReader and printWriter. getStatus (); int * gets the status code of response, which has 200,301,404,500 * response. getWriter (); PrintWriter * obtains a PrintWriter, which is used to return data to response and return data to the client. This is more convenient than Stream * response. isCommitted (); boolean * calls the close () method of the PrintWriter object to close the underlying output stream. The method submits the data in the buffer to the client before closing the output stream. * Therefore, before calling the close () method of the PrintWriter object, response. the isCommitted () method returns false; * after calling the close () method of the PrintWriter object, response. the isCommitted () method returns true. * Response. reset (); void * clears the buffer, sets the page not to be cached, and clears the status code and header at the same time. If data has been sent, an exception occurs * response. resetBuffer (); void * only clears buffer * response. sendError (1, "123"); void * response. sendError (123); * response. sendError (1, "123"); * The setStatus method is used to set the status code returned by the Servlet to the client. It is used to set the status without errors. * If the Servlet fails to run, the Servlet can use the sendError method to set the status code. * For example, The sendError (int SC) method sets the error status code. The sendError (int SC, String msg) method sends an error message to the customer in addition to setting the status code. * Response. sendRedirect ("xx.html"); * returns a redirection and submits the new request and response to the redirected page for processing. * The sendRedirect method sends a temporary redirection response to the customer. It generates a 302 response status code. * The response gives the customer a new URL partition. If the buffer has been cleared, this method will bring up an IllegalStateException. * Response. setBufferSize (123); * set the buffer size * response. setCharacterEncoding ("UTF-8"); * sets the character encoding * response. setContentLength (123); * sets the length of the returned content. The header also contains * response. setContentLengthLong (1345l); * The length is very long. * response. setContentType ("dfd"); * Set ContentType, including encoding and type information * The role of ContentType ("text/html; charset = GBK") in the Http header of the webpage: * Tell the browser what encoding the data in the webpage \ * When the form is submitted, the browser will usually encode the data in the form according to the charset specified by ContentType, and then send it to the server. * Note that ContentType refers to the ContentType of the http header, rather than the ContentType in meta on the webpage. * Response. setDateHeader ("asd", 123l); * modify the date header * response. setHeader ("sfds", "sdfsdf"); * modify the header * response. setIntHeader ("sf", 3123); * set the value header * response. setLocale (locale); * set the local environment * response. setStatus (1); * sets the Http status code. * response is used for errors. setStatus (12, "dasd"); * set the status code with a message ****/

3. Code used for testing

AsyncContext async = request. getAsyncContext (); String attribute = (String) request. getAttribute ("code"); Enumeration <String> enumer = request. getAttributeNames (); String authtype = request. getAuthType (); String character = request. getCharacterEncoding (); int len = request. getContentLength (); long lenl = request. getContentLengthLong (); String contenttype = request. getContentType (); String contextpath = request. getContextPath (); Cookie [] cook = request. getCookies (); long dataHeader = request. getDateHeader (""); DispatcherType dispatcher = request. getDispatcherType (); String header = request. getHeader ("headname"); Enumeration <String> headernames = request. getHeaderNames (); Enumeration <String> headersname = request. getHeaders ("headersname"); ServletInputStream ins = request. getInputStream (); int I = request. getIntHeader ("head"); String add = request. getLocalAddr (); Locale locale = request. getLocale (); Enumeration <Locale> locales = request. getLocales (); String localname = request. getLocalName (); int port = request. getLocalPort (); String method = request. getMethod (); String codep = request. getParameter ("code"); Map <String, String []> map = request. getParameterMap (); Enumeration <String> Pnames = request. getParameterNames (); String [] values = request. getParameterValues ("code"); Part pa = request. getPart ("file"); Collection <Part> pas = request. getParts (); String pathin = request. getPathInfo (); String trans = request. getPathTranslated (); String protoc = request. getProtocol (); String query = request. getQueryString (); BufferedReader br = request. getReader (); String rp = request. getRealPath ("/"); String ra = request. getRemoteAddr (); String rh = request. getRemoteHost (); int rport = request. getRemotePort (); String ru = request. getRemoteUser (); RequestDispatcher rd = request. getRequestDispatcher (""); String rsi = request. getRequestedSessionId (); String uri = request. getRequestURI (); String scheme = request. getScheme (); String servern = request. getServerName (); int sport = request. getServerPort (); ServletContext scon = request. getServletContext (); String spath = request. getServletPath (); HttpSession session1 = request. getSession (); HttpSession session2 = request. getSession (true); Principal prc = request. getUserPrincipal (); boolean authe = request. authenticate (response); // it proves to be true, reliable, or valid. The authentication takes effect. String cs = request. changeSessionId (); boolean iss = request. isAsyncStarted (); boolean isss = request. isAsyncSupported (); boolean MIP = request. isRequestedSessionIdFromCookie (); boolean irsi = request. isRequestedSessionIdFromUrl (); boolean irss = request. isRequestedSessionIdFromURL (); boolean isiv = request. isRequestedSessionIdValid (); boolean isivs = request. isSecure (); boolean isr = request. isUserInRole ("role"); request. login ("user", "password"); request. logout (); request. Y (); request. policyall (); request. removeAttribute ("at"); request. setAttribute ("at", request); request. setCharacterEncoding ("UTF-8"); request. startAsync (); request. startAsync (request, response); // request. upgrade (); response. addCookie (new Cookie ("a", "aa"); response. addDateHeader ("date", 23456789l); response. addHeader ("asf", "sff"); response. addIntHeader ("fsf", 12); boolean ch = response. containsHeader ("asf"); String eru = response. encodeRedirectUrl ("UTF-8"); String eru1 = response. encodeRedirectURL ("UTF-8"); String eu = response. encodeUrl ("UTF-8"); String eu1 = response. encodeURL ("UTF-8"); response. flushBuffer (); int bs = response. getBufferSize (); String ge = response. getCharacterEncoding (); String cont = response. getContentType (); String se = response. getHeader ("aa"); Collection <String> ghn = response. getHeaderNames (); Collection <String> ghn1 = response. getHeaders ("aa"); Locale sss = response. getLocale (); ServletOutputStream ost = response. getOutputStream (); int rs = response. getStatus (); PrintWriter writer1 = response. getWriter (); boolean isc = response. isCommitted (); response. reset (); response. resetBuffer (); response. sendError (1, "123"); response. sendError (123); response. sendRedirect ("xx.html"); response. setBufferSize (123); response. setCharacterEncoding ("UTF-8"); response. setContentLength (1, 123); response. setContentLengthLong (1345l); response. setContentType ("dfd"); response. setDateHeader ("asd", 123l); response. setHeader ("sfds", "sdfsdf"); response. setIntHeader ("sf", 3123); response. setLocale (locale); response. setStatus (1); response. setStatus (12, "dasd ");

The above content is just a summary, and does not explain the role of each method and the role of the retrieved object. For example, Session is a very useful object. You need to know its usage, please refer to the blog below.

For details about the Http client, that is, the content of each part of the browser's request sending and response receiving, refer to the post.

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.