Servlet详解
越学到后面,越觉得基础重要,慢慢开始补充基础,因此这篇博客主要备忘一下扎实servlet的相关知识。
1.首先如何查看servlet的源码。
servlet的源码在tomcat服务器的源代码中([点击下载][Link 1]) **[apache-tomcat-8.0.53-src.zip][Link 1]**
非源码的名字叫 **apache-tomcat-8.0.53.zip** 注意一下 没有src,去官网下载的时候请注意。
如何导源码包进eclipse 请看这篇博客:
https://blog.csdn.net/qq_29519041/article/details/82468100
结构图:
2.查看servlet源码的HttpServlet**类**
随便写一个类继承HttpServlet,按住ctrl点击HttpServlet
点击Declaration为查看这个类的代码,点击Implementation为查看所有继承这个类的子类。
来看一下HttpServlet这个类的源码
public abstract class HttpServlet extends GenericServlet {
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";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_TRACE = "TRACE";
private static final String HEADER_IFMODSINCE = "If-Modified-Since";
private static final String HEADER_LASTMOD = "Last-Modified";
private static final String LSTRING_FILE =
"javax.servlet.http.LocalStrings";
private static final ResourceBundle lStrings =
ResourceBundle.getBundle(LSTRING_FILE);
public HttpServlet() {
// NOOP
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected long getLastModified(HttpServletRequest req) {
return -1;
}
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {
doGet(req, resp);
} else {
NoBodyResponse response = new NoBodyResponse(resp);
doGet(req, response);
response.setContentLength();
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_put_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doDelete(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_delete_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
private static Method[] getAllDeclaredMethods(Class<?> c) {
if (c.equals(javax.servlet.http.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,
parentMethods.length);
System.arraycopy(thisMethods, 0, allMethods, parentMethods.length,
thisMethods.length);
thisMethods = allMethods;
}
return thisMethods;
}
protected void doOptions(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
Method[] methods = getAllDeclaredMethods(this.getClass());
boolean ALLOW_GET = false;
boolean ALLOW_HEAD = false;
boolean ALLOW_POST = false;
boolean ALLOW_PUT = false;
boolean ALLOW_DELETE = false;
boolean ALLOW_TRACE = true;
boolean ALLOW_OPTIONS = true;
for (int i=0; i<methods.length; i++) {
Method m = methods[i];
if (m.getName().equals("doGet")) {
ALLOW_GET = true;
ALLOW_HEAD = true;
}
if (m.getName().equals("doPost"))
ALLOW_POST = true;
if (m.getName().equals("doPut"))
ALLOW_PUT = true;
if (m.getName().equals("doDelete"))
ALLOW_DELETE = true;
}
String allow = null;
if (ALLOW_GET)
allow=METHOD_GET;
if (ALLOW_HEAD)
if (allow==null) allow=METHOD_HEAD;
else allow += ", " + METHOD_HEAD;
if (ALLOW_POST)
if (allow==null) allow=METHOD_POST;
else allow += ", " + METHOD_POST;
if (ALLOW_PUT)
if (allow==null) allow=METHOD_PUT;
else allow += ", " + METHOD_PUT;
if (ALLOW_DELETE)
if (allow==null) allow=METHOD_DELETE;
else allow += ", " + METHOD_DELETE;
if (ALLOW_TRACE)
if (allow==null) allow=METHOD_TRACE;
else allow += ", " + METHOD_TRACE;
if (ALLOW_OPTIONS)
if (allow==null) allow=METHOD_OPTIONS;
else allow += ", " + METHOD_OPTIONS;
resp.setHeader("Allow", allow);
}
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
int responseLength;
String CRLF = "\r\n";
StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI())
.append(" ").append(req.getProtocol());
Enumeration<String> reqHeaderEnum = req.getHeaderNames();
while( reqHeaderEnum.hasMoreElements() ) {
String headerName = reqHeaderEnum.nextElement();
buffer.append(CRLF).append(headerName).append(": ")
.append(req.getHeader(headerName));
}
buffer.append(CRLF);
responseLength = buffer.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(buffer.toString());
out.close();
return;
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = 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 {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
private void maybeSetLastModified(HttpServletResponse resp,
long lastModified) {
if (resp.containsHeader(HEADER_LASTMOD))
return;
if (lastModified >= 0)
resp.setDateHeader(HEADER_LASTMOD, lastModified);
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
}
去掉了注释部分(注释超多)
它有13个方法分别为
方法 | 解释或相关博客 |
public HttpServlet() | 空参构造 |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) | 处理get方式的请求 |
protected long getLastModified(HttpServletRequest req) | 获取最后的修改时间 (所请求的资源最后的修改时间) 比较优秀的解释博客: |
protected void doHead(HttpServletRequest req, HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85329453 |
protected void doPost(HttpServletRequest req, HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85331058 |
protected void doPut(HttpServletRequest req, HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85331472 |
protected void doDelete(HttpServletRequest req,HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85331647 |
private static Method[] getAllDeclaredMethods(Class<?> c) | 该方法是获取本类中的所有方法,包括私有的(private、protected、默认以及public)的方法。 |
protected void doOptions(HttpServletRequest req,HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85332183 |
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) | https://blog.csdn.net/qq_29519041/article/details/85332272 |
protected void service(HttpServletRequest req, HttpServletResponse resp) | 主要作用是对针对不同的请求调用不同的方法来处理,service方法会被自动调用,因此覆盖service方法的时候,需要在service方法里调用其他doXXX方法,不然其他方法将不会被调用,一般我们不用重写service方法,只需要重写get和post方法即可。 |
private void maybeSetLastModified(HttpServletResponse resp,long lastModified) | 如果尚未设置Last-Modified实体标头字段,如果它还没有被设置并且这个值是有用的,则设置该字段。在doGet之前调用,以确保在写入响应数据之前设置头。子类可能已经设置了这个标头,需要进行检查。 |
public void service(ServletRequest req, ServletResponse res) | 它的主要作用是把请求和响应的类型(做强转强转不了报错) ServletRequest req => HttpServletRequest request; ServletResponse res => HttpServletResponse response; |
3.GenericServlet类
他的作用如注释所说:
定义通用的、独立于协议的servlet。要编写用于Web的HTTP servlet,请改为{@link javax.servlet.http.HttpServlet}。
package javax.servlet;
import java.io.IOException;
import java.util.Enumeration;
/**
* Defines a generic, protocol-independent servlet. To write an HTTP servlet for
* use on the Web, extend {@link javax.servlet.http.HttpServlet} instead.
* <p>
* <code>GenericServlet</code> implements the <code>Servlet</code> and
* <code>ServletConfig</code> interfaces. <code>GenericServlet</code> may be
* directly extended by a servlet, although it's more common to extend a
* protocol-specific subclass such as <code>HttpServlet</code>.
* <p>
* <code>GenericServlet</code> makes writing servlets easier. It provides simple
* versions of the lifecycle methods <code>init</code> and <code>destroy</code>
* and of the methods in the <code>ServletConfig</code> interface.
* <code>GenericServlet</code> also implements the <code>log</code> method,
* declared in the <code>ServletContext</code> interface.
* <p>
* To write a generic servlet, you need only override the abstract
* <code>service</code> method.
*/
public abstract class GenericServlet implements Servlet, ServletConfig,
java.io.Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
/**
* Does nothing. All of the servlet initialization is done by one of the
* <code>init</code> methods.
*/
public GenericServlet() {
// NOOP
}
/**
* Called by the servlet container to indicate to a servlet that the servlet
* is being taken out of service. See {@link Servlet#destroy}.
*/
@Override
public void destroy() {
// NOOP by default
}
/**
* Returns a <code>String</code> containing the value of the named
* initialization parameter, or <code>null</code> if the parameter does not
* exist. See {@link ServletConfig#getInitParameter}.
* <p>
* This method is supplied for convenience. It gets the value of the named
* parameter from the servlet's <code>ServletConfig</code> object.
*
* @param name
* a <code>String</code> specifying the name of the
* initialization parameter
* @return String a <code>String</code> containing the value of the
* initialization parameter
*/
@Override
public String getInitParameter(String name) {
return getServletConfig().getInitParameter(name);
}
/**
* Returns the names of the servlet's initialization parameters as an
* <code>Enumeration</code> of <code>String</code> objects, or an empty
* <code>Enumeration</code> if the servlet has no initialization parameters.
* See {@link ServletConfig#getInitParameterNames}.
* <p>
* This method is supplied for convenience. It gets the parameter names from
* the servlet's <code>ServletConfig</code> object.
*
* @return Enumeration an enumeration of <code>String</code> objects
* containing the names of the servlet's initialization parameters
*/
@Override
public Enumeration<String> getInitParameterNames() {
return getServletConfig().getInitParameterNames();
}
/**
* Returns this servlet's {@link ServletConfig} object.
*
* @return ServletConfig the <code>ServletConfig</code> object that
* initialized this servlet
*/
@Override
public ServletConfig getServletConfig() {
return config;
}
/**
* Returns a reference to the {@link ServletContext} in which this servlet
* is running. See {@link ServletConfig#getServletContext}.
* <p>
* This method is supplied for convenience. It gets the context from the
* servlet's <code>ServletConfig</code> object.
*
* @return ServletContext the <code>ServletContext</code> object passed to
* this servlet by the <code>init</code> method
*/
@Override
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
/**
* Returns information about the servlet, such as author, version, and
* copyright. By default, this method returns an empty string. Override this
* method to have it return a meaningful value. See
* {@link Servlet#getServletInfo}.
*
* @return String information about this servlet, by default an empty string
*/
@Override
public String getServletInfo() {
return "";
}
/**
* Called by the servlet container to indicate to a servlet that the servlet
* is being placed into service. See {@link Servlet#init}.
* <p>
* This implementation stores the {@link ServletConfig} object it receives
* from the servlet container for later use. When overriding this form of
* the method, call <code>super.init(config)</code>.
*
* @param config
* the <code>ServletConfig</code> object that contains
* configuration information for this servlet
* @exception ServletException
* if an exception occurs that interrupts the servlet's
* normal operation
* @see UnavailableException
*/
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
/**
* A convenience method which can be overridden so that there's no need to
* call <code>super.init(config)</code>.
* <p>
* Instead of overriding {@link #init(ServletConfig)}, simply override this
* method and it will be called by
* <code>GenericServlet.init(ServletConfig config)</code>. The
* <code>ServletConfig</code> object can still be retrieved via
* {@link #getServletConfig}.
*
* @exception ServletException
* if an exception occurs that interrupts the servlet's
* normal operation
*/
public void init() throws ServletException {
// NOOP by default
}
/**
* Writes the specified message to a servlet log file, prepended by the
* servlet's name. See {@link ServletContext#log(String)}.
*
* @param msg
* a <code>String</code> specifying the message to be written to
* the log file
*/
public void log(String msg) {
getServletContext().log(getServletName() + ": " + msg);
}
/**
* Writes an explanatory message and a stack trace for a given
* <code>Throwable</code> exception to the servlet log file, prepended by
* the servlet's name. See {@link ServletContext#log(String, Throwable)}.
*
* @param message
* a <code>String</code> that describes the error or exception
* @param t
* the <code>java.lang.Throwable</code> error or exception
*/
public void log(String message, Throwable t) {
getServletContext().log(getServletName() + ": " + message, t);
}
/**
* Called by the servlet container to allow the servlet to respond to a
* request. See {@link Servlet#service}.
* <p>
* This method is declared abstract so subclasses, such as
* <code>HttpServlet</code>, must override it.
*
* @param req
* the <code>ServletRequest</code> object that contains the
* client's request
* @param res
* the <code>ServletResponse</code> object that will contain the
* servlet's response
* @exception ServletException
* if an exception occurs that interferes with the servlet's
* normal operation occurred
* @exception IOException
* if an input or output exception occurs
*/
@Override
public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
/**
* Returns the name of this servlet instance. See
* {@link ServletConfig#getServletName}.
*
* @return the name of this servlet instance
*/
@Override
public String getServletName() {
return config.getServletName();
}
}
他有13个方法
方法 | 解析 |
public GenericServlet() | 空参构造 |
public void destroy() | 用于销毁一个servlet时 |
public String getInitParameter(String name) | https://blog.csdn.net/qq_35873847/article/details/77988619 用来获取在web.xml中配置的初始化参数 <init-param> <param-name>XXXXX</param-name> <param-value>XXXXXX</param-value> </init-param> 有错误欢迎留言指正 |
public Enumeration<String> getInitParameterNames() | 老夫掐指一算 获得的应该是 所有web.xml中param-name标签包含的玩意,返回的是一个枚举字符串数组。 |
public ServletConfig getServletConfig() | |
public ServletContext getServletContext() | |
public String getServletInfo() | |
public void init(ServletConfig config) throws ServletException | |
public void init() throws ServletException | |
public void log(String msg) | |
public void log(String message, Throwable t) | |
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; | |
public String getServletName() |
|
———— 最后更新于2018年12月31日 22:46 待续…————
还没有评论,来说两句吧...