[Servlet] Summary, servlet Summary

Source: Internet
Author: User
Tags set cookie

[Servlet] Summary, servlet Summary
1 Servlet basics 1.0 inheritance relationships of common Servlet classes

1.1 common Servlet objects
  • ServletContext: describes the context of the current project.
  • ServletRequest: browser requests to the server
Request. getParameter ("username"); // obtain a single data request. getParameterValues ("love"); // obtain a set of data: used to check the request for multiple types of data. setCharacterEncoding ("UTF-8"); // process Chinese garbled characters, this method is only valid for POST requests, GET needs to process the request separately. setAttribute ("login", "true ");

Other request methods

SetAttribute (String name, Object) // set the parameter value of the request whose name is "name" to getAttributeNames () // return the name set of all attributes of the request Object, the result is an enumerated instance getCookies () // returns all Cookie objects of the client. The result is a Cookie array getCharacterEncoding () // returns the character encoding method getContentLength () in the request () // return the length of the request Body getHeader (String name) // get the Header information defined by the HTTP protocol getHeaders (String name) // return all values of the request Header with the specified name, the result is an enumerated instance getHeaderNames () // returns the name of the request Header. The result is an enumerated instance getInputStream () // returns the request input stream, getMethod () // getParameter (String name) // obtain the parameter value getParameterNames () that the client sends to the server with the name specified. // obtain the name of all parameters that the client sends to the server, the result is an enumerated instance getParametervalues (String name) // obtain all the values of the parameter with name specified getProtocol () // obtain the protocol name getQueryString () on which the client transmits data to the server // obtain the query string getRequestURI () // obtain the client address getRemoteAddr () of the request string () // obtain the Client IP address getRemoteHost () // obtain the client name getSession ([Boolean create]) // return the SessiongetServerName () associated with the request // obtain the server name getServletPath () // obtain the path of the script file requested by the client getServerPort () // obtain the server port number removeAttribute (String name) // delete an attribute in the request
  • ServletResponse: the server responds to the browser and stores all the data to be sent to the browser on this object. Store the required data in the specified stream. The data is displayed in the browser.
Response. getWriter (); // usually sends the data content response in the program. getOutputStream (); // byte stream is generally used in the program with the copy function response. setContentType ("text/html; charset = UTF-8"); // notify tomcat and the browser to send the data encoding response. setHeader ("Cache-Control", "no-cache"); // set the client header information response. sendRedirect ("new. jsp "); // redirect // implement redirection on the jsp page: <% response. sendRedirect ("new. jsp "); %> Object obj = request. getAttribute ("login"); getRequestDispatcher (String path); // server: the current program needs to obtain the request scheduler // forward: When the scheduler coordinates multiple Servlets, this method returns the output content of the last servlet page.
1.2 Servlet sample code
Public class FormServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter ();//★★Get the producer stream // send data out. println ("<form action = \" # \ "method = \" post \ ">"); out. println ("name: <input type = 'text' name = 'username' value = 'fengjie '> <br/>"); out. println ("password: <input type = 'Password' name = 'userpwd'> <br/>"); out. println ("<input type = 'submit 'value = 'Submit'/>"); out. println ("</form>");} // other Code omitted}
1.3 Cookie and Session
  • Cookie example
// 1. create a cookie and notify the browser of the cookie information [CookieServlet. java] Cookie cookie = new Cookie ("test", "itcast"); // create cookieresponse. addCookie; // notify the browser of the cookie information. // 2. obtain the cookie information [ReadCookieServlet. java] Cookie [] cookies = request. getCookies (); if (cookies! = Null ){//★No. When the browser is closed and then opened, a null pointer exception for (Cookie c: cookies) {System. out. println (c. getName () + ":" + c. getValue () ;}// 3. set the cookie validity period so that session-level cookies become persistent cookieCookie = new cookie ("gf", "fengjie"); // * Create cookiecookie. setMaxAge (60*60*24); // * sets the effective time response. addCookie (cookie); // * notify the browser // 3. modify the cookie Path,/cookie/addCookieServlet2 // set the cookie of the current servlet, which can only be obtained from all the servlets in the cookie directory and the subsequent servlet. // you want to get the cookie in/getCookieSer Access in vlet? Cookie cookie = new Cookie ("add222", "22222222222"); // * Create cookiecookie. setMaxAge (60*60); // * sets the effective time cookie. setPath ("/day07/"); // * modify the path response. addCookie (cookie); // * notify the browser // 4. store Chinese cookies in cookies [] cookies = request. getCookies (); if (cookies! = Null) {for (Cookie c: cookies) {System. out. println (c. getName () + ":" + c. getValue (); // obtain the value of cn, and then decode if ("cn ". equals (c. getName () {String value = URLDecoder. decode (c. getValue (), "UTF-8"); System. out. println (value) ;}}string data = ""; String returnData = URLEncoder. encode (data, "UTF-8"); // encode transmitted Chinese characters Cookie = new cookie ("cn", returnData); // create Cookie response. addCookie (cookie); // send data-} // 5. set the maximum character value of the Cookie public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); // piece together data, get a 4 kb string, cannot exceed 4 kb StringBuffer buf = new StringBuffer (); for (int I = 0; I <1024*4; I ++) {buf. append ("a");} String data = buf. toString (); Cookie cookie = new Cookie ("max", data); // create a cookie. setMaxAge (60*60); // set the effective time response. addCookie (cookie); // notify the browser to send data}
  • Session

The Session object is created by the server and obtained through the request. getSession () method.
The default value of the Session is 30 minutes. (set it to 30 in the web. xml file of the conf directory. Note that the unit is minute)

Sample Code

Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); // JSESSIONID = DFE75A1E9CCAA1591F900FA3B1AEE9F3: tomcat automatically adds cookies, session-level // get session HttpSession session = request. getSession (); // The default value of the parameter is true. Not created. A response is returned. System. out. println (session. isNew (); // The First Time is true, and then false // persistence operation Cookie = new cookie ("JSESSIONID", session. getId (); // create Cookie by yourself. setMaxAge (60*30); // set cookie attribute: Effective time response. addCookie (cookie); // specifies the Cookie behavior: notifies the browser}
2. Differences between post and get requests in other 2.1 http requests [1] 2.2 What are the differences between forward () and redirect () in SERVLET APIs?
  • The former is only the redirection of control in the container, and the address after the redirection is not displayed in the address bar of the client browser; the latter is a complete jump, and the browser will get the jump address, and resend the request link. In this way, the link address after the jump is displayed in the address bar of the browser. Therefore, the former is more efficient. When the former can meet the needs, try to use the forward () method, and this will also help to hide the actual link. In some cases, for example, to jump to a resource on another server, you must use the sendRedirect () method.
    [Forward]

    [Redirection]
2.3 difference between getAttribute () and getParameter 2.4 difference between filters, listeners, and interceptors 2.5 difference between Servlet, Filter, and listener execution sequence

The loading sequence for the entire project (without any framework) is:context-param -> listener -> filter -> servletWhere, the filter execution sequence is performed according to the sequence defined in web. xml (when multiple filters match). The execution sequence is shown as follows:
-

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.