9th Chapter Web09-servlet

Source: Internet
Author: User
Tags tomcat server

Today's mission
? The ability to complete the login of the system
? After completing the login system, the page timed jump
? How many times the system has been accessed after logging the system login success
Teaching navigation
Teaching objectives
Understanding the HTTP protocol
Mastering the writing of Servlets
Understand the use of ServletConfig
Mastering the use of ServletContext objects
Teaching methods
Case-driven approach
1.1 Previous lesson Content review:
Xml:

  • An Overview of XML:
    • What is XML: Extensible Markup Language.
    • The role of XML: As a software configuration file, transfer and access data.
    • Use of XML:
      • Basic syntax FOR XML:
        • The label must have a start and end.
        • Must have a tag with
        • is case sensitive.
        • Nested correctly.
      • Document declaration FOR XML: <?xml version= "1.0" encoding= "UTF-8"?>
      • XML comment:<!--Comment--
      • Elements of XML:
        • Naming conventions: Cannot start with a number, the label contains a letter or a number, cannot begin with XML, cannot appear a space colon.
      • Attributes of XML:
        • Naming conventions: Consistent with elements. Attributes must be quoted.
      • Special characters and CDATA areas of XML.
  • Parsing of XML:
    • What are the parsing methods of XML:
      • Dom and sax:
        • The DOM loads the document into memory at once, forming a tree structure. If the document is too large, it can cause memory overflow. Easy to add and modify the operation.
        • The way sax reads Edge parsing, if the document is large, does not cause memory overflow, but cannot be increased.
    • Common XML-parsing APIs:
      • Jaxp,jdom,dom4j ...
    • Parsing XML using dom4j:
  • Constraints of XML: (understanding)
    • What are the differences between XML constraints?
      • DTD and Schame:
        • The syntax of a DTD is self-contained, which is the syntax used by the schema XML.
        • Schema has more powerful semantics and syntax constraints than DTDs.
        • The schema supports namespaces.
          Tomcat
  • Web-related content:
    • Software Architecture:
    • Server: is a computer, this computer has installed the software of the server.
    • Common Web servers: Websphere,weblogic,tomcat,jboss,iis,apache ...
    • Using Tomcat:
  • Download and install Tomcat:
  • The structure of the Tomcat directory:
    • Tomcat/conf:
    • Tomcat/webapps:
    • Tomcat/logs:
    • Tomcat/bin:
  • How to publish a Web project to the server:
    • First, copy the project to WebApps.
    • Second, modify the Server.xml, configure <context path= "" docbase= ""/>
    • Third, in Conf/catalina/localhost/xxx.xml configuration <context docbase= ""/>
  • To configure Tomcat with an STS:
    1.2 Case One: Use a servlet to complete a user logon case. 1.2.1 Requirements:
    On the homepage of the website, login link, click the login link, you can jump to the login page. Enter the user name and password in the login page click the log in case. Complete the login function.

    1.2.2 Analysis: 1.2.2.1 Technical Analysis:
    "Overview of the HTTP protocol"
    ? Agreement:
  • What is an agreement: rules that require both parties to abide by.
    ? HTTP protocol:
  • What is the HTTP protocol: rules that are used to specify the browser and server to follow.

    ? The purpose of the HTTP protocol is to standardize the data transfer between the browser and the server.
    ? Features of the HTTP protocol:
  • A model based on requests and responses.
    • Must have a response before the request.
    • The request and response must appear in pairs.
  • The default port number is 80.
    ? Version of the HTTP protocol:
  • 1.0: The connection is closed immediately after each response.
  • 1.1: Use now. Do not hang up after each response and wait for a long time without a request to hang up.
    "Demo of HTTP Protocol"
    Packet Capture Analysis: Get mode:
  • Request section:
    get/day09/demo1-http/demo2.html?name=aaa&age=23 http/1.1
    accept:text/html, application/xhtml +xml, /
    x-httpwatch-rid:59176-10011
    referer:http://localhost:8080/day09/demo1-http/demo1.html
    ACCEPT-LANGUAGE:ZH-CN
    user-agent:mozilla/5.0 (Windows NT 6.3; WOW64; trident/7.0; rv:11.0) like Gecko
    Accept-encoding:gzip, deflate
    host:localhost:8080
    dnt:1
    connection:keep-alive
    Packet Capture Analysis: POST mode:
    post/day09/demo1-http/demo2.html http/1.1
    accept:text/html, Application/xhtml+xml, /
    x-httpwatch-rid:59176-10031
    referer:http://localhost:8080/day09/demo1-http/demo1.html
    ACCEPT-LANGUAGE:ZH-CN
    user-agent:mozilla/5.0 (Windows NT 6.3; WOW64; trident/7.0; rv:11.0) like Gecko
    content-type:application/x-www-form-urlencoded
    Accept-encoding:gzip, deflate
    Host: localhost:8080
    content-length:15
    dnt:1
    connection:keep-alive
    Cache-control:no-cache
    name=bbb &age=38
  • Response section:
    http/1.1 OK
    server:apache-coyote/1.1
    Accept-ranges:bytes
    etag:w/"145-1461807615933"
    Last-modified:thu, APR 01:40:15 GMT
    Content-type:text/html
    content-length:145
    Date:thu, APR 01:43:52 GMT
    <! DOCTYPE html>
    <meta charset= "UTF-8" >
    <title>insert title here</title>
    <body>
    </body>
    "An explanation of the HTTP protocol"
    ? Request section
  • Request Line
    • How to submit:
      • There are many ways to submit, commonly used get and post:
      • The difference between get and post:
        • The parameters for the get's submission are displayed on the address bar, and the post is not displayed.
        • Get is often limited by size, while post has no size limit.
        • Get has no request body, and Post has a request body.
    • Commit path:
    • Protocol version:
  • Request Header
    • are displayed in the form of key-value pairs. Typically a key corresponds to a value, and there is an individual key that corresponds to more than one value.
    • User-agent: Represents the type of browser. ---file download: Download the Chinese file: IE uses Urlencodor to encode, while Firefox uses BASE64 encoding.
    • Referer: Represents the source of the Web page. ---anti-theft chain.
    • If-modified-since: Typically used with header last-modified in the response to find the local cache.
  • Request Body
    • is the submit parameter of the Post submission method.
      ? Response section
  • Response Line:
    • Protocol version
    • Status code:
      • 200: Success
      • 302: Redirect
      • 304: Find local cache
      • 404: Resource does not exist
      • 500: Server Internal Error
    • Status Code Description
  • Response header: A key value pair, typically a key corresponds to a value, and a key corresponds to more than one value.
    • Last-modified: Use Find local cache with if-modified-since in request.
    • Content-dispostion: A header information used by the use of file downloads.
    • Location: The path of the redirected jump.
    • Refresh: Timed flush/timed jump.
  • Response Body: Displays the contents of the browser's page.
    "Overview of the Servlet"
    ? What is a servlet:
  • is a small Java program running on a Web server that receives and responds to requests sent from the client, usually using the HTTP protocol.
  • The servlet is a dynamic web development technology provided by Sun.
    ? The role of the servlet:
  • Used to process requests sent from the client browser, and can respond to requests
    ? Using Servlets:
  • Write a class to implement a servlet interface.
  • Configure this class to be written to the server.
    ? Getting Started with Servlets:
  • To write a class:
    public class ServletDemo1 implements Servlet{br/> @Override
    • The method that handles requests and responses for the user.
      */
      public void Service (ServletRequest req, servletresponse Res) throws Servletexception, IOException {
      Res.getwriter (). println ("Hello Servlet ...");
      }
      ...
      }
  • Configuration:

    test1 Com.itheima.a_servlet. ServletDemo1 test1 /servletdemo1
  • Access:
    Http://localhost:8080/day09/ServletDemo1
    "Receive parameters using ServletRequest"
  • String GetParameter (string name); ---is used to receive data with a name that corresponds to a value.
  • String[] Getparametervalues (String name),---is used to receive data with a name that corresponds to multiple values.
  • Map Getparametermap (); ---is used to receive all the data in the form, the map key is the parameter name submitted by the form, and the value of map is the values of the commit parameter.
  • The enumeration Getparameternames ()---is used to get the names of all the arguments that are submitted in the form.
    "Servlet's access Process"
    "The implementation of the servlet relationship"
    Servlet: interface

    Genericservlet: A common servlet

    Httpservlet:httpservlet

  • Write a class that inherits HttpServlet, overriding the Doget and Dopost methods.
  • Configuration
    1.2.3 Code implementation 1.2.3.1 Step One: Create databases and tables:
  • create database day09;use day09;create table user(id int primary key auto_increment,username varchar(20),password varchar(20),nickname varchar(20));insert into user values (null,‘aaa‘,‘111‘,‘小凤‘);insert into user values (null,‘bbb‘,‘111‘,‘小童童‘);

    1.2.3.2 Step Two: Create packages and classes:
    1.2.3.3 Step Three: Introducing the JAR Package

    • MySQL Database driver package
    • C3P0 jar Package for connection pool
    • Dbutils's Bag
      1.2.3.4 Introduction to login page
      1.2.3.5 Writing Servlet-->service-->dao
      1.2.4 Summary: The life cycle of the 1.2.4.1 servlet: (* * * *)
      ? Life cycle: Is the process from creation to destruction of an object.
      ? Servlet life cycle: The servlet's process from creation to destruction.
    • When to create: the first time a user accesses a servlet to create an instance of a servlet
    • When to destroy: When the project is removed from the server, or when the server is shut down.
      ? When a user accesses the servlet for the first time, the server creates an instance of the servlet, Then the Init method in the servlet executes. Any one request server creates a new thread to access the service in the servlet. The method of doxxx is called within the service method, depending on how the request is made. (GET request calls Doget,post request call Dopost). If the servlet is removed from the server, or the server is shut down, the instance of the servlet is destroyed, and the Destroy method executes.
      Related configurations of the 1.2.4.2 servlet:
      "Create servlet at startup"
      The servlet is created by default at the time of the first visit. Now let the servlet be created when the server is started. To configure the servlet:
      Configure in the <servlet></servlet> tab in Web. xml:
    • <load-on-startup>2</load-on-startup>---Pass in a positive integer, the smaller the integer, the higher the priority is created.
      "Configuration of Url-pattern"
      There are three ways to configure Url-pattern:
      1. Full path match: with/start for example:/servletdemo4,/aaa/servletdemo5,/aaa/bbb/servletdemo6
      2. Directory matching: to/From the beginning of the need toend. For example:/,/aaa/,/aaa/bbb/
      3. Extension matches: Cannot start with/to begin with. For example:. Do, *.action
      *The wrong wording:/. Do
      Like the following configuration:
      <servlet>
      <servlet-name>ServletDemo4</servlet-name>
      <servlet-class>com.itheima.a_servlet. Servletdemo4</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>ServletDemo4</servlet-name>
      <url-pattern>/ServletDemo4</url-pattern>
      </servlet-mapping>
      <servlet>
      <servlet-name>ServletDemo5</servlet-name>
      <servlet-class>com.itheima.a_servlet. Servletdemo5</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>ServletDemo5</servlet-name>
      <url-pattern>/
      </url-pattern>
      </servlet-mapping>
      <servlet>
      <servlet-name>ServletDemo6</servlet-name>
      <servlet-class>com.itheima.a_servlet. Servletdemo6</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>ServletDemo6</servlet-name>
      <url-pattern>.do</url-pattern>
      </servlet-mapping>
      If Access address:
      Http://localhost:8080/day09/ServletDemo4: The first one
      Http://localhost:8080/day09/aaa.do: The second One
      Full path matching > directory matching > Extension matching
      1.2.4.3 the path in the development of the program:
      ? Relative paths: All are required to find a positional relative relationship. Cannot start with.
    • ./Current Path: /Top level Directory
    • Access using relative paths:
      • Http://localhost:8080/day09/demo4-url/demo1.html
      • Http://localhost:8080/day09/ServletDemo6
        ? Absolute path: Does not need to find a positional relative relationship. To begin with.
    • The absolute path is divided into the client path and the server-side path:

      • The client path must add the project name. /day09/servletdemo6
      • The server-side path does not need to add engineering names. /servletdemo6
        1.3 Case two: 5 seconds after successful login jump to another page. 1.3.1 Requirements:
        After the login is successful, the page jumps to another page for 5 seconds.
        1.3.2 Analysis: 1.3.2.1 Technical Analysis:
        "Use the Refresh header information in the HTTP protocol"
        Refresh has been introduced before can be timed page jump. You need to use the program to set the header information.
        "Setting the response header in response"
    • AddHeader (String name,string value); ---a response header that corresponds to more than one value for a key.
      • Adddateheader (String name,long date);
      • Addintheader (String name,int value);
    • SetHeader (String name,string value); ---a response header that corresponds to a value for a key.
      • Setdateheader (String name,long date);
      • Setintheader (String name,int value);
        For example: header information: xxx:aaa
      • AddHeader ("xxx", "BBB"); -->xxx:aaa,bbb
      • SetHeader ("xxx", "BBB"); -->xxx:bbb
        1.3.3 Code implementation:
    On the code after successful login, timed jump. Public class Userrefreshservlet extends HttpServlet {private static final long Serialversionuid = 1l;pro tected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {try {/ /solve garbled problem of output Chinese to page!!! Response.setcontenttype ("Text/html;charset=utf-8");//1. Receive the parameters of the form submission. String username = request.getparameter ("username"); String Password = request.getparameter ("password");//2. Encapsulated into the entity object. User user = new user (); User.setusername (username); User.setpassword (password);//3. Call the business layer to process the data. UserService userservice = new UserService (); User Existuser = Userservice.login (user);//4. Display information based on processing results (page jump). if (Existuser = = null) {//Login failed Response.getwriter (). println ("

    1.3.4 Summary: 1.3.4.1 use JS to control the effect of reading seconds.

    <script type="text/javascript">var time = 5;window.onload = function(){setInterval(‘changeTime()‘,1000);}function changeTime(){time--;document.getElementById("s1").innerHTML = time;}</script>

    1.4 Case THREE: Record the number of successful login sites. 1.4.1 Requirements:
    After the successful login, 5 seconds after the jump to a page, the page shows that you are the X-login successful users.
    1.4.2 Analysis: 1.4.2.1 Technical Analysis:
    "ServletContext Object"
    ServletContext object Access data, the data stored in a certain range of functions. This object is called a domain object.

      • To access data:
      • Used to deposit data into the ServletContext.
      • Used to fetch data from the ServletContext.
      • Used to remove data from the ServletContext.
        1.4.3 Code implementation:
    /** * Login Code servlet */public class Usercountservlet extends HttpServlet {private static final long Serialversionuid = 1l;@o verridepublic void Init () throws Servletexception {//Initialize a variable count value to 0.int count = 0;// This value is stored in ServletContext. This.getservletcontext (). SetAttribute ("Count", count);} protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { try {response.setcontenttype ("text/html;charset=utf-8");//1. Receive parameters for form submission. String username = request.getparameter ("username"); String Password = request.getparameter ("password");//2. Encapsulated into the entity object. User user = new user (); User.setusername (username); User.setpassword (password);//3. Call the business layer to process the data. UserService userservice = new UserService (); User Existuser = Userservice.login (user);//4. Display information based on processing results (page jump). if (Existuser = = null) {//Login failed Response.getwriter (). println ("

    1.4.4 Summary: 1.4.4.1 servletconfig: Understanding. Get configuration information for the servlet.

      • String Getservletname (); ---Get the value of the name that the servlet configures in Web. Xml.
      • String Getinitparameter (string name); ---Get the initialization parameters of the servlet.
      • Enumeration Getinitparameternames (); ---Gets the name of the initialization parameter for all servlets.
        1.4.4.2 ServletContext: Important
        The role of ServletContext:
      • 1. Used to obtain global initialization parameters.
      • 2. The type of mime used to obtain the file.
      • 3. Access data as a domain object.
        ServletContext is a domain object.
        • Scope of action: the entire Web project.
        • Create: When the server starts, the Tomcat server creates a separate ServletContext object for each Web project.
        • Destroy: When the server shuts down, or when the project is removed from the server.
      • 4. Used to read files under the Web project.

    9th Chapter Web09-servlet

    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.