Javaweb:servlet Technology

Source: Internet
Author: User
Tags html form locale session id tomcat server

Javaweb:servlet Technology Quick Start what servlet is

A Java Servlet is a program that runs on a Web server or Application server , as a middle tier between a request from a Web browser or other HTTP client and a database or application on an HTTP server . Using Servlets, you can collect user input from a Web page form, render records from a database or other source, and create Web pages dynamically.

Location of the servlet in the Web application:

  

task of the Servlet

The Servlet performs the following major tasks:

    • reads the explicit data sent by the client (browser) . This includes the HTML form on the Web page, or it can be a form from an applet or a custom HTTP client program.
    • Reads the implicit HTTP request data sent by the client (browser). This includes cookies, media types, and compression formats that the browser can understand.
    • process the data and generate the results . This process may require accessing the database, executing RMI or CORBA calls, invoking the Web service, or directly calculating the corresponding response.
    • sends explicit data (that is, documents) to the client (browser). The format of the document can be varied, including text files (HTML or XML), binary files (GIF images), Excel, and so on.
    • Sends an implicit HTTP response to the client (browser). This includes telling the browser or other clients which types of documents are returned (such as HTML), setting cookies and caching parameters, and other similar tasks.
Servlet Environment Configuration

Download Tomcat Server

website address:https://tomcat.apache.org/download-80.cgi

  

Adding Web development packages to environment variables

  

Create our first servlet

We inherited the httpservlet to implement our own servlet:

A special class:

The Servletcontext:servlet context object that the servlet accesses to provide various support for the current web app by accessing the object.

The declaration period of the servlet

  

    • The first HTTP request to reach the server is delegated to the Servlet container.
    • The servlet container loads the servlet before invoking the service () method.
    • The servlet container then processes multiple requests produced by multiple threads, each executing a single Servlet instance's service () method.
  • Init: is responsible for initializing the Servlet object, which is called after the container has created the Servlet object.
    • The init method is designed to be called only once . It is called the first time the Servlet is created, and is no longer invoked on subsequent user requests .
    • The servlet is created when the user first invokes the URL corresponding to the servlet, but you can also specify that the servlet is loaded the first time the server is started.
    • When a user invokes a servlet, a servlet instance is created, and each user request generates a new thread, which, when appropriate, is handed over to the Doget or DoPost method. The init () method simply creates or loads some data that will be used for the entire life cycle of the Servlet.
  • Destory: responsible for releasing the resources occupied by the Servlet object, which is called by the container when the Servlet object ends its life cycle.
    • The Destroy () method is called only once and is called at the end of the Servlet's life cycle. The Destroy () method allows your Servlet to shut down a database connection, stop a background thread, write a Cookie list or hit counter to disk, and perform other similar cleanup activities.
    • The Destroy method executes when the container removes the servlet, and it executes only once. This method executes after the service () method of all threads executes or times out, and after this method is called, the container no longer calls the servlet's method, which means that the container will not send the request to the servlet. This method frees the servlet of the resources it consumes, and is typically used to perform some cleanup tasks.
The relationship between Servlet and Tomcat

one of the biggest bugs in this question is that theservlet is a complex thing, in fact, theservlet is a Java interface, interface! Openidea, CTRL + SHIFT + N, search the servlet, and you'll see a interface! with only 5 methods

  

So, the Web protocol,HTTP, and so on in the question,theservlet doesn't care! No more!

What did the servlet do? Very simple, what is the function of the interface? Specification Bai!

The Servlet interface defines a set of specifications for handling network requests, and all classes that implement the servlet need to implement its five methods, the most important of which is the two life cycle method init () and Destroy (), and one that handles the request. Service (), that is, all classes that implement the Servlet interface, or all classes that want to handle network requests, need to answer these three questions:

    • What to do when you initialize
    • What to do when you destroy
    • What to do when you accept the request

This is a Java to give a specification! Like Asimov's robot Three Laws, the Walking Dead in Rick's three questions, the norm!

A servlet is a specification that implements a servlet class to handle a request?

The answer is, no.

You can casually Google a servlet's Hello World tutorial, which will let you write a servlet, believe me, you never write in the servlet listening 8080 Port Code, theservlet does not deal directly with the client!

How did the request come to the servlet? The answer is a servlet container, like the one we use most often, and Similarly, you can just Google a servlet's Hello World tutorial, which will certainly let you deploy the servlet to a container, Or your servlet won't work at all.

Tomcat is the guy that deals directly with the client, he listens to the port, requests it over, according to URL, determine which servlet to pass the request to , and then call the servlet's service method, The service method returns a response object, andtomcat Returns the response to the client .

Important header information to receive requests and make responses to HTTP requests
Header Information Description
Accept This header information specifies the MIME types that the browser or other client can handle. A value of image/png or image/jpeg is the two most common possible values.
Accept-charset This header information specifies the character set that the browser can use to display information. such as Iso-8859-1.
Accept-encoding This header information specifies the type of encoding that the browser knows how to handle. The value of gzip or compress is the two most common possible values.
Accept-language This header information specifies the preferred language for the client, in which case the Servlet produces results in multiple languages. For example, en, en-us, RU, etc.
Authorization This header information is used by clients to identify themselves when accessing password-protected Web pages.
Connection This header information indicates whether the client can handle persistent HTTP connections. Persistent connections allow clients or other browsers to retrieve multiple files through a single request. A value of keep-alive means that a persistent connection is used.
Content-length This header information applies only to the POST request and gives the size of the post data in bytes.
Cookies This header message returns the cookies that were previously sent to the browser to the server.
Host This header information specifies the host and port in the original URL.
If-modified-since This header information represents the page that the client wants only if the page has changed since the specified date. If no new results are available, the server sends a 304 code that represents the not Modified header information.
If-unmodified-since This header information is the antithesis of if-modified-since, which specifies that the operation succeeds only if the document is older than the specified date.
Referer This header indicates the URL of the Web page to which the message is pointing. For example, if you click a link to page 2 on page 1, when the browser requests page 2 o'clock, the URL of page 1 is included in the Referer header message.
User-agent This header information identifies the browser or other client that made the request and can return different content to different types of browsers.

Browser HTTP Requests

The following methods can be used to read HTTP headers in a Servlet program. These methods are available through the httpservletrequest object.

Serial Number Method & Description
1 Cookie[] GetCookies ()
Returns an array that contains all the Cookie objects that the client sends the request.
2 Enumeration Getattributenames ()
Returns an enumeration that contains the name of the property that is available for the request.
3 Enumeration Getheadernames ()
Returns an enumeration that contains all the header names that are contained in the request.
4 Enumeration Getparameternames ()
Returns an enumeration of a String object that contains the names of the parameters contained in the request.
5 HttpSession getsession ()
Returns the current session that is associated with the request, or creates one if the request has no session sessions.
6 HttpSession getsession (Boolean Create)
Returns the current HttpSession associated with the request, or returns a new session session if the current session is not present and the creation is true.
7 Locale GetLocale ()
Based on the Accept-language header, returns the preferred locale for the client to accept the content.
8 Object getattribute (String name)
Returns the value of the named property as an object, or null if no attribute with the given name exists.
9 ServletInputStream getInputStream ()
Use ServletInputStream to retrieve the principal of the request in binary data form.
10 String Getauthtype ()
Returns the name of the authentication scheme used to protect the Servlet, for example, "BASIC" or "SSL", or null if the JSP is not protected.
11 String getcharacterencoding ()
Returns the name of the character encoding used in the request body.
12 String getContentType ()
Returns the MIME type of the request principal and returns NULL if the type is not known.
13 String Getcontextpath ()
Returns the part of the request URI that indicates the request context.
14 String GetHeader (string name)
Returns the value of the specified request header as a string.
15 String GetMethod ()
Returns the name of the requested HTTP method, for example, GET, POST, or PUT.
16 String GetParameter (string name)
Returns the value of the request parameter as a string, or null if the argument does not exist.
17 String GetPathInfo ()
When the request is issued, returns any additional path information related to the URL sent by the client.
18 String Getprotocol ()
Returns the name and version of the request agreement.
19 String getquerystring ()
Returns the query string contained in the request URL after the path.
20 String getremoteaddr ()
Returns the Internet Protocol (IP) address of the client sending the request.
21st String Getremotehost ()
Returns the fully qualified name of the client that sent the request.
22 String Getremoteuser ()
If the user is authenticated, returns the logged on user who made the request, or null if the user is not authenticated.
23 String Getrequesturi ()
Returns part of the URL of the request from the protocol name until the first line of the HTTP request is returned in the query string.
24 String Getrequestedsessionid ()
Returns the session ID specified by the client.
25 String Getservletpath ()
Returns part of the URL of the request that called the JSP.
26 String[] Getparametervalues (String name)
Returns an array of String objects containing the values of all given request parameters and returns null if the argument does not exist.
27 Boolean issecure ()
Returns a Boolean value that indicates whether the request uses a secure channel, such as HTTPS.
28 int Getcontentlength ()
Returns the length of the request body in bytes, providing an input stream, or 1 if the length is unknown.
29 int Getintheader (String name)
Returns the value of the specified request header to an int value.
30 int Getserverport ()
Returns the port number to which this request was received.
31 int Getparametermap ()
Encapsulates a parameter into a MAP type.
Common HTTP Response Headers
Header Information Description
Allow This header specifies the requested method (GET, POST, and so on) that the server supports.
Cache-control This header information specifies the circumstances under which the response document can be safely cached. Possible values are: public, Private, or No-cache , and so on. Public means that documents are cacheable, private means that documents are private documents for individual users and can only be stored in private (non-shared) caches, no-cache means that documents should not be cached.
Connection This header information indicates whether the browser uses a persistent HTTP connection. A value of close indicates that the browser does not use persistent HTTP connections, and the value keep-alive means using persistent connections.
Content-disposition This header information allows you to request that the browser require the user to save the response to disk with a file of the given name.
Content-encoding This header information specifies how the page is encoded during the transfer process.
Content-language This header information represents the language in which the document was written. For example, en, en-us, RU, etc.
Content-length This header information indicates the number of bytes in the response. This information is only required if the browser is using a persistent (keep-alive) HTTP connection.
Content-type This header information provides the MIME (multipurpose Internet Mail Extension) Type of the response document.
Expires This header information specifies when the content expires, after which the content is no longer cached.
Last-modified This header information indicates the last modification time of the document. The client can then cache the file and provide a date through the if-modified-since request header information in a later request.
Location This header information should be included in all responses with a status code. Within 300s, this notifies the address of the browser document. The browser will automatically reconnect to this location and get a new document.
Refresh This header information specifies how the browser should request an updated page as soon as possible. You can specify the number of seconds to refresh the page.
Retry-after This header information can be used in conjunction with the 503 (Service Unavailable services unavailable) response, which tells the client how long it will be possible to repeat its request.
Set-cookie This header information specifies a cookie associated with the page.

Server HTTP response
Serial Number Method & Description
1 String encoderedirecturl (string url)
Encodes the specified URL used in the Sendredirect method, or if the encoding is not required, the return URL is unchanged.
2 String encodeurl (string url)
Encodes the specified URL that contains the session ID, or if the encoding is not required, the return URL does not change.
3 Boolean Containsheader (String name)
Returns a Boolean value that indicates whether the named response header has been set.
4 Boolean iscommitted ()
Returns a Boolean value indicating whether the response has been committed.
5 void Addcookie (Cookie cookie)
Adds the specified cookie to the response.
6 void Adddateheader (String name, long date)
Adds a response header with the given name and date value.
7 void AddHeader (string name, String value)
Adds a response header with the given name and value.
8 void Addintheader (String name, int value)
Adds a response header with the given name and integer value.
9 void Flushbuffer ()
Forces any content in the buffer to be written to the client.
10 void Reset ()
Clears any data that exists in the buffer, including the status code and header.
11 void Resetbuffer ()
Clears the contents of the underlying buffer in the response, without clearing the status code and headers.
12 void Senderror (int sc)
Sends an error response to the client using the specified status code, and clears the buffer.
13 void Senderror (int sc, String msg)
Sends an error response to the client using the specified state.
14 void Sendredirect (String location)
Sends a temporary REDIRECT response to the client using the specified redirect location URL.
15 void setbuffersize (int size)
Sets the preferred buffer size for the response body.
16 void Setcharacterencoding (String charset)
Sets the character encoding (MIME character set) of the response that is sent to the client, for example, UTF-8.
17 void setcontentlength (int len)
Sets the length of the content body in the HTTP Servlet response, which sets the HTTP Content-length header.
18 void setContentType (String type)
If the response has not yet been committed, set the content type of the response that is sent to the client.
19 void Setdateheader (String name, long date)
Sets a response header with the given name and date value.
20 void SetHeader (string name, String value)
Sets a response header with the given name and value.
21st void Setintheader (String name, int value)
Sets a response header with the given name and integer value.
22 void SetLocale (Locale Loc)
If the response has not yet been committed, set the region of the response.
23 void SetStatus (int sc)
Set the status code for the response.

HTTP status Code
See Rookie Tutorial:www.runoob.com/servlet/servlet-http-status-codes.html
Create a directory structure for Web Project Web Apps

– Application root directory

–|--Web-inf directory: Required Directory

–|--WEB.XML:WEB Application Deployment profile, required directory

–|--Classes directory: Storing byte-code files

–|--Lib directory: storing third-party class library files

–|--TLD File: Tag Library description file

–|--other static files: HTML, CSS, JavaScript, pictures, etc.

Web. xml file

The Web. xml file is a configuration file for the Javaweb application, stored in the Web-inf subdirectory. Written by the developer for access by the servlet container .

The servlet container reads its web. xml file when it loads and initializes the Javaweb application, and obtains the publishing information for the application.

Add a servlet map as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"         xsi:schemalocation= "HTTP://XMLNS.JCP.ORG/XML/NS/JAVAEE/HTTP// Xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd "         version=" 4.0 ">    <servlet>        <servlet-name >MoviesServlet</servlet-name>        <servlet-class>dao. moviesservlet</servlet-class>    </servlet>        <servlet-mapping>        <servlet-name >MoviesServlet</servlet-name>        <url-pattern></url-pattern>    </servlet-mapping ></web-app>

  

Javaweb:servlet Technology

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.