[Servlet] In-depth study of HttpServlet

Source: Internet
Author: User

HttpServlet Overview

In most Web applications, the client accesses the server-side resources through the HTTP protocol, and the servlet we write is primarily used for HTTP protocol request and response processing. To quickly develop a servlet class that is applied to the HTTP protocol, Sun provides an abstract class HttpServlet in the Javax.servlet.http package that inherits from Genericservlet, which is used to create a web that is appropriate for HTTP protocol-based Servlet.

publicabstractclass HttpServlet extends GenericServlet {}

All the methods of HttpServlet are listed in the following table:

Method Summary
protected void DoDelete (httpservletrequest req, HttpServletResponse resp)
protected void Doget (httpservletrequest req, HttpServletResponse resp)
protected void Dohead (httpservletrequest req, HttpServletResponse resp)
protected void Dooptions (httpservletrequest req, HttpServletResponse resp)
protected void DoPost (httpservletrequest req, HttpServletResponse resp)
protected void DoPut (httpservletrequest req, HttpServletResponse resp)
protected void Dotrace (httpservletrequest req, HttpServletResponse resp)
Protected long Getlastmodified (HttpServletRequest req)
protected void Service (HttpServletRequest req, HttpServletResponse resp)
void Service (ServletRequest req, servletresponse Res)

Here we discuss the various methods provided in the HttpServlet abstract class.

The overridden service () method

Two overloaded service () methods are available in the HttpServlet class:

  Public Abstract  class httpservlet extends genericservlet {    @Override     Public void Service(ServletRequest req, servletresponse Res)throwsServletexception, IOException {httpservletrequest request; HttpServletResponse response;Try{request = (httpservletrequest) req;        Response = (httpservletresponse) res; }Catch(ClassCastException e) {Throw NewServletexception ("Non-http Request or response"); } service (request, response);}protected void Service(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {String method = Req.getmethod ();if(Method.equals (Method_get)) {LongLastModified = getlastmodified (req);            Maybesetlastmodified (resp, lastmodified);        Doget (req, resp); }Else if(Method.equals (Method_head)) {LongLastModified = getlastmodified (req);            Maybesetlastmodified (resp, lastmodified);        Dohead (req, resp); }Else if(Method.equals (Method_post))        {DoPost (req, resp); }Else if(Method.equals (Method_put))        {DoPut (req, resp); }Else if(Method.equals (Method_delete))        {DoDelete (req, resp); }Else if(Method.equals (method_options))       {dooptions (REQ,RESP); }Else if(Method.equals (Method_trace))        {dotrace (REQ,RESP); }Else{String errmsg = lstrings.getstring ("http.method_not_implemented"); object[] Errargs =Newobject[1]; errargs[0] = method;            ErrMsg = Messageformat.format (errmsg, Errargs);        Resp.senderror (httpservletresponse.sc_not_implemented, errmsg); }}

By looking at the source code of the HttpServlet we know that the first service () method is the implementation of the Service () method in the Genericservlet class. In the service () Method converts the ServletRequest and Servletresponse objects to HttpServletRequest (inherited from the ServletRequest interface) and HttpServletResponse (inherited from the Servletresponse interface) , and then calls the second service () method to process the client's request.

In the second service () method, 7 processing methods are provided for the 7 request-mode get, Post, Head, Put, Delete, Trace, and options defined in the HTTP 1.1 protocol. The parameter types and exception throw types of the 7 methods are consistent with the second service () method in the HttpServlet class. When the servlet container receives a request for an HttpServlet object, the order of the methods to invoke the object is as follows:

    • Call the public Service () method, convert the parameter types to HttpServletRequest and HttpServletResponse, and then call the protected Service () method.
    • In the protected service () method, get the name of the HTTP request method, and then, depending on the type of request method, call the Doxxx () method of the response.

Therefore, when we inherit the custom servlet from HttpServlet, we usually do not need to rewrite the service () method, just rewrite the doxxx () method of the response.

Seven methods of request processing

There are 7 processing methods available in the HttpServlet abstract class for the 7 request modes that are defined in the HTTP 1.1 protocol, GET, Post, Head, Put, Delete, Trace, and options:

    • protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, ioexception
    • protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, ioexception
    • protected void Dohead (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, ioexception
    • protected void DoPut (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException
    • protected void DoDelete (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException
    • protected void Dotrace (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException
    • protected void dooptions (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException

Of these 7 methods of handling requests, the HttpServlet class implements the trace and options methods appropriately, so we do not need to rewrite the Dotrace () and Dooptions () methods. For the other 5 request handling methods, the HttpServlet class provides an implementation that returns an HTTP error. For HTTP 1.0 client requests, these methods return a status code of 400, which indicates that the request sent by the client is syntactically incorrect. For HTTP 1.1 client requests, these methods return a status code of 405, indicating that the request method for the specified resource is not allowed.

For the actual application of the HTTP protocol, we most commonly use get and post, so when customizing the Servlet, Doget () and Dopost () Two request handling methods are often overridden. where the Doget () method is used to handle the request for Get mode, the DoPost () method is used to handle the request of the Post method, let's take a look at the following example:

    • Create an HTML page to send the client request.
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html>  <head>    <title>Index.html</title>    <meta http-equiv="Content-type" content="text/html; Charset=utf-8 ">  </head>  <body>    <H1>Get method Request</H1>    <form id="UserInfo" method="Get" action ="Threeservlet">User name:<input type="text" id="username" name="username" >        <input type="Submit" id="Submit" value= "Submit">    </form>    <H1>Post Mode request</H1>    <form id= "userinfo" method= "post" action=" Threeservlet ">User name:<input type="text" id="username" name= "username">        <input type=" submit" id= "Submit" value="Submit" >    </form>  </body></html>
    • Create a servlet to process the request.
public   Class  threeservlet  extends  httpservlet  { public  void< /span> doget  (httpservletrequest request, httpservletresponse response) throws  servletexception, IOException {System.out.println (" This is a get way to send Request, the servlet uses the Doget () method to handle the. ");} public  void  dopost  (HttpServletRequest request, httpservletresponse response) throws  Servletexception, IOException {System.out.println ( "This is a post-send request, Servlet uses Dopost () method to handle the. ");}} 
    • Configure the Web. xml file.
<?xml version= "1.0" encoding= "UTF-8"?><web-app version="2.5"xmlns="Http://java.sun.com/xml/ns/javaee"  xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">                 <servlet><servlet-name>Threeservlet</servlet-name>    <servlet-class>App.java.servlet.ThreeServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>Threeservlet</servlet-name>    <url-pattern>/threeservlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></Web-app>
    • Publish the Web project to the Tomcat server and start the Tomcat server.
    • Open the browser and enter http://localhost:8080/08_servlet/index.html in the Address bar.

Using the Get method to send the request, the console prints the contents of the Doget () method. Using post to send requests, the console prints the contents of the Dopost () method.

Reprint NOTE: Please indicate the author and the original link, thank you!

[Servlet] In-depth study of HttpServlet

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.