1.1. Servlet Source Code
Public abstract Interface Servlet {public abstract void init (ServletConfig paramservletconfig) throws servletexception; Public abstract ServletConfig Getservletconfig (); public abstract void Service (ServletRequest paramservletrequest, Servletresponse paramservletresponse) throws Servletexception, IOException; Public abstract String Getservletinfo (); public abstract void Destroy ();
Second, Genericservlet analysis
2.1. Genericservlet Source Code
1 package javax.servlet; 2 3 Import java.io.IOException; 4 Import java.io.Serializable; 5 Import java.util.Enumeration; 6 7 Public abstract class Genericservlet implements Servlet, servletconfig,serializable {9 private transient servlet Config config;10-public void Destroy () {}13-public string Getinitparameter (string name) {R Eturn getservletconfig (). Getinitparameter (name);}17 Public Enumeration Getinitparameternames () {R Eturn getservletconfig (). Getinitparameternames ();}21 public ServletConfig getservletconfig () {% RET Urn this.config;24}25-public ServletContext getservletcontext () {getservletconfig (). GETSERVL Etcontext ();}29-Public String getservletinfo () {return "", "}33" public void init (Serv Letconfig config) throws servletexception {this.config = config;36 init (); PNs}38 All public void Init () throws Servletexception {}41) public void log (String msg) {getservletcontext (). log (Getservletname () + ":" + msg); }45 (String message, Throwable t) {getservletcontext (). log (Getservletname () + ":" + message, t);}49 public abstract void Service (ServletRequest paramservletrequest,51 servletres Ponse paramservletresponse) throws servletexception,52 ioexception;53-public String getservletname () {5 5 return This.config.getServletName (); 56}57}
points to note:
- Genericservlet is an abstract class that cannot be instantiated directly and must be given a subclass to instantiate. i.e.: Genericservlet GS = new Genericservlet (); Compile will error. Genericservlet GS = new Myservlet (); This is correct (where Myservlet is its subclass)
- Its service () method is an abstract method, that is, it gives the task of processing the request to a subclass. Subclasses must implement this method.
- In the end, it gives the skeleton of the design servlet, defines the servlet life cycle, and some methods of getting the name, configuration, and initialization parameters, which are designed to be independent of the application layer protocol, which means that you might implement it with a non-HTTP protocol (in fact, the current Java Servlet is still only one HTTP).
Three, HttpServlet analysis
3.1. HttpServlet Source code
1 package javax.servlet.http; 2 3 Import java.io.IOException; 4 Import java.io.Serializable; 5 Import Java.lang.reflect.Method; 6 Import Java.text.MessageFormat; 7 Import java.util.Enumeration; 8 Import Java.util.ResourceBundle; 9 Import Javax.servlet.GenericServlet; Ten import javax.servlet.ServletException; Import Javax.servlet.ServletOutputStream; Import Javax.servlet.ServletRequest; Import Javax.servlet.ServletResponse; Public abstract class HttpServlet extends Genericservlet implements Serializable {$ private static final long Serialversionuid = 1L; private static final String Method_delete = "DELETE"; private static final String Method_head = "HEAD"; private static final String Method_get = "GET"; private static final String method_options = "OPTIONS"; private static final String Method_post = "POST"; Method_put static Final String = "PUT"; The private static final String Method_trace = "TRACE";private static final String header_ifmodsince = "If-modified-since"; $ private static final String Header_lastmod = "last-modified"; The private static final String Lstring_file = "Javax.servlet.http.LocalStrings"; ResourceBundle private static lstrings = ResourceBundle Getbundle ("Javax.servlet.http.LocalStrings" ); Protected long getlastmodified (HttpServletRequest req) {return-1l; + protected V OID Dohead (httpservletrequest req, HttpServletResponse resp), throws Servletexception, IOException {37 Nobodyresponse response = new Nobodyresponse (RESP); Doget (req, response); Response.setcontentlength (); protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servlete Xception, IOException {protocol string = Req.getprotocol (), String msg = Lstrings.getstring ("http.m Ethod_post_not_supported ");if (Protocol.endswith ("1.1")) Resp.senderror (405, MSG); -Else Resp.senderror (n, msg); protected void Doget (HttpServletRequest req, HttpServletResponse resp), throws Servletex Ception, IOException {protocol string = Req.getprotocol (), String msg = Lstrings.getstring ("http.me Thod_get_not_supported "); if (Protocol.endswith ("1.1")) Resp.senderror (405, MSG); Resp.senderror (n, msg); protected void DoPut (HttpServletRequest req, HttpServletResponse resp) throws Servletex Ception, IOException {A string protocol = Req.getprotocol (), and a string msg = Lstrings.getstring ("http.me Thod_put_not_supported "); if (Protocol.endswith ("1.1")) Resp.senderror (405, MSG); Resp.senderror (n, msg); protected void DoDelete(HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {. protocol = Req.getprotocol (); The String msg = lstrings.getstring ("http.method_delete_not_supported"); if (Protocol.endswith ("1.1")) Resp.senderror (405, MSG); + Else Resp.senderror (n, msg); Method[] Getalldeclaredmethods (Class c) {if (C.equals (Httpservlet.class)) { return null; method[] Parentmethods = Getalldeclaredmethods (C.getsuperclass ()); method[] Thismethods = C.getdeclaredmethods (); if (parentmethods! = null) && (parentmethods.length > 0)) {method[] Allmethods = new Method[parentmethods.length + thismethods.length]; System.arraycopy (parentmethods, 0, allmethods, 0, 94 parentmethods.length); 95 96 System.arraycopy (thismethods, 0, Allmethods, Parentmethods.length, thismethods.length); 98 Thismethods = allmethods;100}101 return thismethods;102}103 104 protected Voi D dooptions (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {106 Method[] methods = Getalldeclaredmethods (GetClass ()); 107 108 Boolean allow_get = false;109 Boolean AL Low_head = false;110 Boolean allow_post = false;111 Boolean allow_put = false;112 Boolean allow_de Lete = false;113 Boolean allow_trace = true;114 Boolean allow_options = true;115 for (int i = 0; i < methods.length; i++) {117 Method m = methods[i];118 119 if (M.getname (). Equals ("Doget")) {ALLO W_get = true;121 Allow_head = true;122}123 if (M.getname (). Equals ("DoPost")) 124 Allow_post = true;125 if (M.getname (). Equals ("DoPut")) 126 Allow_put = true;127 if (M.getname (). Equals ("DoDelete")) {Allow_delete = true;129}130}131 String allow = null;132 if ((allow_get) && (allow = = null)) 133 allow = "GET"; 134 if (Allow_head) 135 if (allow = = nulls) 136 allow = "HEAD"; 137 else138 Allow = Allow + ", HEAD"; 139 if (allow_post) if (allow = = null) 141 allow = "PO ST "; 142 else143 allow = Allow +", POST "; 144 if (allow_put) 145 if (allow = = null) 146 allow = ' put '; 147 else148 allow = Allow + ", PUT"; 149 if (A Llow_delete) (allow = = null) 151 = "DELETE"; else153 Allow = Allow + ", DELETE "; 154 if (allow_trace) 155 if (allow = = nulls) 156 allow =" TRACE "; 157 Else 158 Allow + ", TRACE"; 159 if (allow_options) {box if (allow = = null) 161 Allow = "Options"; 162 else163 allow = Allow + ", OPTIONS"; 164}165 R Esp.setheader ("Allow"), 166}167 168 protected void Dotrace (HttpServletRequest req, HttpServletResponse resp ) 169 throws Servletexception, IOException {string CRLF = "\ r \ n"; 171 string responsestring = "TRACE" + req.getrequesturi () + "" 172 + req.getprotocol (); 173 174 Enumeration Reqheaderenum = Req.getheadernames (); 175 176 while (Reqheaderenum.hasmoreelements ()) {177 String Headername = (string) Reqheaderenum.nextelement (); 178 responsestring = responsestring + CRLF + headername + ":" 179 + Req.getheader (heaDername);}181 182 responsestring = responsestring + crlf;183 184 int responselength = response String.Length (); 185 186 Resp.setcontenttype ("Message/http"); 187 resp.setcontentlength (responselength); 188 Servletoutputstream out = Resp.getoutputstream (); 189 out.print (responsestring); Out.close (); 191 }192 193 protected void Service (HttpServletRequest req, HttpServletResponse resp) 194 throws Servletex Ception, IOException {195 String method = Req.getmethod (), 196 197 if (Method.equals ("GET")) {198 Long lastmodified = getlastmodified (req), 199 if (lastmodified = = -1l) {doget, req (resp) ; 201} else {202 long ifmodifiedsince = Req.getdateheader ("if-modified-since"); 203 if (Ifmodifiedsince < lastmodified/1000l * 1000L) {204 maybesetlastmodified (resp, Lastmodifi ED); 205 Doget (req, resp); 206} else {207 resp.setstatus (304); 208}209 }210} else if (Method.equals ("HEAD")) {211 Long lastmodified = getlastmodified (req); 212 Maybesetlastmodified (resp, lastmodified); 213 Dohead (req, resp); 214} else if (Method.equals ("PO ST ")) {215 DoPost (req, resp); 216} else if (Method.equals (" PUT ")) {217 DoPut (req, resp); 21 8} else if (Method.equals ("DELETE")) {219 DoDelete (req, resp); Ptions ")) {221 dooptions (req, resp); 222} else if (Method.equals (" TRACE ")) {223 Dotrace (re Q, RESP); 224} else {225 String errmsg = lstrings.getstring ("http.method_not_implemented"); 226 object[] Errargs = new object[1];227 errargs[0] = method;228 errmsg = Messageformat.format (er RMSG, Errargs); 229 230 Resp.senderror (501, errmsg); 231}232}233 234 private void maybesetlastmodified (HTTPSERVLETRESP Onse resp,235 long lastmodified) {236 if (Resp.containsheader ("last-modified")) 237 return; 238 if (lastmodified >= 0L) 239 resp.setdateheader ("last-modified", lastmodified); 240}241 242 public void Service (ServletRequest req, servletresponse Res) 243 throws Servletexception, IOException {244 HttpServletRequest request;245 HttpServletResponse response;246 try {247 request = (Htt pservletrequest) req;248 response = (httpservletresponse) res;249} catch (ClassCastException e) {250 throw new Servletexception ("Non-http Request or response"); 251}252 Service (request, response) ; 253}254}
Points to note:
- HttpServlet is also an abstract class that cannot be instantiated directly, and must be given a subclass to instantiate (that is, it cannot be used directly and can only be inherited).
- HttpServlet is used for communication with the HTTP protocol, so it also implements several methods in the HTTP protocol, each of which can handle the corresponding type of request
|
http protocol method |
httpservlet Implementation method /td> |
|
OPTIONS |
Dooptio N () |
|
GET |
&NBSP;&NBSP;&NB Sp Doget () |
|
POST |
&nbs p; doPost () |
|
TRACE |
dotrace () |
|
PUT |
doPut ()
|
|
DELETE |
DoDelete () |
- The service () method of HttpServlet is quite special, and the Service () method with the Public keyword is obviously inherited from the parent class, which only receives HTTP requests, where the corresponding request and response are converted to the corresponding object based on the HTTP protocol. The request is eventually forwarded to the service () method with the protected keyword. The protected service () method forwards the request to the appropriate dodelete (), Doget (), Dooptions (), DoPost (), DoPut (), and so on, depending on the type of request. So when developing your own servlet, there is no need to overwrite the HttpServlet service () method, because the method eventually forwards the request to the corresponding Doxxx method, only needs to overwrite the corresponding Doxxx method for request processing. If this method is overridden, no other specific method is invoked based on the method name.
- In the same way, dooptions and Dotrace methods do not need to be overwritten.
- Looking at the Doget, DoPost, DoPut, Dodelete Four method code, found that these methods only determine the protocol type, and then throw the corresponding exception, nothing else to do, so when implementing their own servlet, you need to override these methods to meet their own needs for request processing.
Iv. Comparison of the three
4.1 The relationship between the main classes of the servlet
Genericservlet is the ancestor class of all servlet classes, implements the interface: Servlet, ServletConfig, Genericservlet is an abstract parent class that must be given subclasses to instantiate
The HttpServlet class inherits the Genericservlet
The servlet has two very important objects, which can be said to be two objects at the very core of the Java Web, HttpServletRequest and HttpServletResponse
4.2 HttpServletRequest and HttpServletResponse objects
Servlet HttpServlet genericservlet Relationship between three