10th Chapter Web10-request&response

Source: Internet
Author: User

Today's mission
? Reading of files under Web engineering
? Complete file download after logging into the system
? Mall System Registration function.
Teaching navigation
Teaching objectives
Mastering response Setting the response header
Mastering the difference between response redirection and forwarding
Master request parameters for receiving requests
Mastering the scope of the request domain
Teaching methods
Case-driven approach
1.1 Previous lesson Content review:
HTTP:

  • HTTP request section:
    • Request Line: Request path protocol version.
      • Request Method:
        • There are a lot of requests. Get and post are commonly used.
        • Difference: Get has a size limit, post has no size limit, the get parameter is displayed to the address bar, post is not displayed to the address bar, into the request body.
    • Request Header: Key-value pair.
      • Referer: Web page source.
      • User-agent: Browser information.
      • If-modified-since:
    • Request Body
      • Post submission parameters.
  • HTTP Response section:
    • Response Line: Protocol version Status Code status code description
      • 200,302,304,404,500
    • Response Header: Key-value pairs.
      • Location: Redirect.
      • Refresh: Timed Jump
      • Content-disposition: File Download
      • Last-modified
    • Response body
      • Displays the content to the page.
        Servlet:
  • Overview of the servlet: Sun provides dynamic web development specifications, which is a small Java program running on the server side.
  • Getting Started with Servlets:
  • The life cycle of a servlet:
    • The first time the servlet is accessed, the server creates an instance of the servlet, and the Init method executes. Any request server sent from the client will create a new thread to execute the service method. The method of calling unused doxxx within the service method based on the request. When the project is removed from the server, or when the server is shut down, the Servlet,destroy method is executed.
  • Related configurations for Servlets:
    • Load at startup:
    • Url-pattern:
      • Full path matching
      • Catalog Matching
      • Name extension matches
  • The servlet inheritance relationship:
    • Servlet

      Genericservlet

      HttpServlet

  • ServletConfig object: Used to obtain configuration information for the servlet.
  • ServletContext object:

    • 1. Get Global Initialization parameters
    • 2. Get the MIME type of the file
    • 3. Access data as a domain object.
    • 4. Read the files in the Web project.
      1.2 Case One: Read the files under the Web project. 1.2.1 Requirements:
      Now there is a profile in Web project SRC, project to be published into Tomcat, need to write a program to read the file.
      1.2.2 Analysis: 1.2.2.1 Technical Analysis:
      "Demonstrate traditional way to read Web project files"
      /**

        • Traditional way to read files:
          • Use a relative path, relative to the path of the JVM.
          • But now is a Web project, relative to the path of the JVM. Now the JVM has been handed over to Tomcat management.
        • @throws FileNotFoundException
        • @throws IOException
          */
          private void Test1 () throws FileNotFoundException, IOException {
          InputStream is = new FileInputStream ("Src/db.properties");
          Properties Properties = new properties ();
          Properties.load (IS);

          String driverClass = properties.getProperty("driverClass");String url = properties.getProperty("url");String username = properties.getProperty("username");String password = properties.getProperty("password");System.out.println(driverClass);System.out.println(url);System.out.println(username);System.out.println(password);

          }
          "Use ServletContext object to read files under Web project"

  • InputStream getResourceAsStream (String path); ---to return a file's input stream based on the supplied path to the read file.
  • String Getrealpath (string path); ---Returns the absolute path of a path to the disk.
    1.2.3 Code implementation: 1.2.3.1 read with getResourceAsStream

/**

    The
    • reads using getResourceAsStream in ServletContext.
    • @throws FileNotFoundException
    • @throws IOException
      */
      private void Test2 () throws FileNotFoundException, IOException {
      // Get ServletContext:
      ServletContext context = This.getservletcontext ();
      InputStream is = Context.getresourceasstream ("/web-inf/classes/db.properties");
      Properties Properties = new properties ();
      Properties.load (IS);
      String driverclass = Properties.getproperty ("Driverclass");
      String url = properties.getproperty ("url");
      String username = properties.getproperty ("username");
      String password = properties.getproperty ("password");
      System.out.println (Driverclass);
      System.out.println (URL);
      System.out.println (username);
      System.out.println (password);
      }
        1.2.3.2 read files using getrealpath:  
/** * 使用ServletContext中的getRealPath读取. * @throws FileNotFoundException * @throws IOException */private void test3() throws FileNotFoundException, IOException {// 获得ServletContext:ServletContext context = this.getServletContext();String realPath = context.getRealPath("/WEB-INF/classes/db.properties");// 获得该文件的磁盘绝对路径.System.out.println(realPath);InputStream is = new FileInputStream(realPath);Properties properties = new Properties();properties.load(is);String driverClass = properties.getProperty("driverClass");String url = properties.getProperty("url");String username = properties.getProperty("username");String password = properties.getProperty("password");System.out.println(driverClass);System.out.println(url);System.out.println(username);System.out.println(password);}

1.2.4 Summary: Function of 1.2.4.1 ServletContext:
"Feature one: Read Global initialization parameters"

配置全局初始化参数:  <context-param>          <param-name>username</param-name>          <param-value>root</param-value>  </context-param>    <context-param>          <param-name>password</param-name>          <param-value>123</param-value>  </context-param>代码:protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username = this.getServletContext().getInitParameter("username");String password = this.getServletContext().getInitParameter("password");System.out.println(username+"    "+password);Enumeration<String> e = this.getServletContext().getInitParameterNames();while(e.hasMoreElements()){String name = e.nextElement();String value = this.getServletContext().getInitParameter(name);System.out.println(name+"    "+value);}}

"Function two: Get the MIME type of the file"

    • Gets the type of mime for the file.
      Code implementation:
       /** * Gets the MIME type of the file */private void Test2 () {String type = This.getservletcontext            (). GetMimeType ("1.html");    System.out.println (type);  

      Function Three: Access data as a domain object
      Scope: The entire Web project. and the global object.
      Create: When the server starts, the server creates a separate ServletContext object for each Web project.
      Destroy: Destroys ServletContext when the server shuts down.
      function Four: Read files under Web Project
      1.2. Class 4.2 Loader reads files: (Extended)

public static void readFile() throws IOException{// 使用类的加载器来读取文件.// 类的加载器用来加载class文件,将class文件加载到内存.InputStream is = ReadFileUtils.class.getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(is);String driverClass = properties.getProperty("driverClass");String url = properties.getProperty("url");String username = properties.getProperty("username");String password = properties.getProperty("password");System.out.println(driverClass);System.out.println(url);System.out.println(username);System.out.println(password);}

1.3 Case TWO: After successful login, complete the download of the file. 1.3.1 Requirements:
After the login is successful, the page jumps to the File download list page, click on some links in the list to download the file.
1.3.2 Analysis: 1.3.2.1 Technical Analysis:
"Overview of Response"
? Response: The object that represents the response. Outputs content from the server to the browser.
"Response's Common API"
? Response Line:

    • Sets the status code.
      ? Response header:
    • Header information for multiple value for a key.
    • header information corresponding to one value for a key.
      ? Response Body

      How do I download files
      ? One: Hyperlink download. Writes the path of the file directly to the href of the hyperlink.---premise: file type, browser does not support.
      ? Two kinds: Manual code to complete the file download.
    • set two headers and one stream:
      • content-type: The MIME type of the file.
      • content-disposition: Open the file as downloaded.
      • InputStream: The input stream for the file.
        1.3.3 Code implementation 1.3.3.1 Step One: Prepare the previous login function:
        1.3.3.2 Step Two: Add a link to the file download on the File download list page:
        1.3.3.3 Step Three: Complete the implementation of the code for the file download:
  public class Downloadservlet extends HttpServlet {private static final long Serialversionuid = 1l;protected Voi D doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//1. Receive Parameters string filename = request.getparameter ("filename");//2. Complete file Download://2.1 Set Content-type header String type = This.getservletcontext (). GetMimeType (filename); Response.setheader ("Content-type", Type);//2.2 Set Content-disposition header Response.setheader (" Content-disposition "," attachment;filename= "+filename);//2.3 settings file inputstream.string Realpath = This.getservletcontext (). Getrealpath ("/download/" +filename); InputStream is = new FileInputStream (realPath);// Get response output stream: OutputStream os = Response.getoutputstream (); int len = 0;byte[] B = new Byte[1024];while (len = Is.read (b)) ! =-1) {os.write (b, 0, Len);} Is.close ();} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}  

1.3.4 Summary: Download the 1.3.4.1 Chinese file:

? When Internet Explorer downloads the Chinese file, it uses the encoding of the URL. The Firefox browser uses BASE64 encoding when downloading Chinese files./** * File Download servlet */public class Downloadservlet extends HttpServlet {private static Final long serialversionuid = 1l;protected void doget (HttpServletRequest request, httpservletresponse response) throws Se Rvletexception, IOException {//1. receive parameter String filename = new string (Request.getparameter ("filename"). GetBytes (" Iso-8859-1 ")," UTF-8 "); SYSTEM.OUT.PRINTLN (filename);//2. Complete file Download://2.1 Set Content-type header String type = This.getservletcontext (). GetMimeType ( filename); Response.setheader ("Content-type", Type);//2.3 Setting file Inputstream.string Realpath = This.getservletcontext ( ). Getrealpath ("/download/" +filename);//handle garbled problems of Chinese files according to browser type: String Agent = Request.getheader ("user-agent"); SYSTEM.OUT.PRINTLN (Agent), if (Agent.contains ("Firefox")) {filename = base64encodefilename (filename);} Else{filename = Urlencoder.encode (filename, "UTF-8");} 2.2 Set Content-disposition head response.setheader ("Content-disposition", "attachment;filename=" +filename); NputstreaM is = new FileInputStream (realpath);//Get response output stream: OutputStream os = Response.getoutputstream (); int len = 0;byte[] B = New Byte[1024];while (len = Is.read (b))! =-1) {os.write (b, 0, Len);} Is.close ();} public static string Base64encodefilename (String fileName) {Base64encoder Base64encoder = new Base64encoder (); try { Return "=? UTF-8? B? " + New String (Base64encoder.encode (Filename.getbytes ("UTF-8")) + "? =";} catch (Unsupportedencodingexception e) {e.printstacktrace (); throw new RuntimeException (e);}} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

1.3.4.2 response how to output response content:
How to respond to a page:

  • Getoutputstream ();
  • Getwriter ();
  • These two methods are mutually exclusive.
    • Only one of these flow responses can be used when responding.
  • output Chinese garbled processing:
    • byte stream:
      • Set the encoding that the browser opens by default:
        • resposne.setheader ("Content-type", "text/ Html;charset=utf-8 ");
      • Sets the encoding when the Chinese byte is removed.
        • "Chinese". GetBytes ("UTF-8");
    • character stream:
      • set encoding for browser open
        • resposne.setheader ("Content-type", "t Ext/html;charset=utf-8 ");
      • Sets the encoding of the buffer for response
        • response.setcharacterencoding ("UTF-8");
          Simplified notation: response.setcontenttype ("Text/html;charset=utf-8");
          1.4 Case Three: Complete the user registration function: 1.4.1 Requirements:
          Site First click on the registered link, jump to the registration page, enter the information in the registration page. Complete registration: (saves data to the database).

          1.4.2 Analysis: 1.4.2.1 Technical Analysis:
          "Request Overview"
          ? Request on behalf of the user.
          Request API
          Function One: Obtain client-related information
          ? How to obtain a request:

          ? Get the requested path:

          ? Get client-related information:

          ? Get project name:

          Function two: Get parameters submitted from the page:

          Function Three: Access data as a domain object:


          "Show request information for client"
public class RequestServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 获得请求方式:String method = request.getMethod();System.out.println("请求方式:"+method);// 获得客户机的IP地址:String ip = request.getRemoteAddr();System.out.println("IP地址:"+ip);// 获得用户的请求的路径:String url = request.getRequestURL().toString();String uri = request.getRequestURI();System.out.println("获得请求的URL:"+url);System.out.println("获得请求的URI:"+uri);// 获得发布的工程名:String contextPath = request.getContextPath();System.out.println("工程名:"+contextPath);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

1.4.3 Code implementation: 1.4.3.1 Step one: Create databases and tables:

create database day10;use day10;create table user(id int primary key auto_increment,username varchar(20),password varchar(20),email varchar(20),name varchar(20),sex varchar(10),telephone varchar(20));

1.4.3.2 Step Two: Create packages and classes:
1.4.3.3 Step Three: Introduce the registration page:
1.4.3.4 Step Four: implementation of the registration code:
1.4.4 Summary: 1.4.4.1 deal with the request to receive the parameters of the Chinese garbled problem:
Now whether the get or post submitted in Chinese, there will be garbled problems.
Solve:
? Post solutions:

    • The parameters of the post are in the request body, directly to the servlet in the background. The data is encapsulated into the request in the servlet. The request also has a buffer. The buffer for the request is also iso-8859-1 encoded.
    • To set the encoding of the buffer for the request:
      • Request.setcharacterencoding ("UTF-8"); ---Be sure to set the encoding before receiving the parameters OK.
        ? Get Solutions for:
    • 1. Modify the encoding of the Tomcat character set. (Not recommended)
    • 2. Use Urlencoder and Urldecoder for encoding and decoding operations.
    • 3. Use string to construct the method:

      1.4.4.2 request to access data as a domain object:
      Accessing data using the Request object:
    • SetAttribute (String name,string value);
    • Object getattribute (String name);
      The scope of the request:
    • Scope is the scope of a request.
    • Create and Destroy:
      • Create: After a client sends a request to the server, the server creates an object for the requests.
      • Destroy: After the server responds to this request.
        1.4.4.3 Redirection and Forwarding differences: (difference between redirect and forward)
    • 1. The redirected address bar changes, and the forwarded address bar is unchanged.
    • 2. REDIRECT two requests two responses, forward a request once response.
    • 3. The redirect path requires an engineering name, and the forwarded path does not need to add the project name.
    • 4. Redirects can jump to any Web site, and forwarding can only be forwarded inside the server.

10th Chapter Web10-request&response

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.