package javax.servlet.http;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.*;
/**
* 抽象类HttpServlet的子类创建HTTP servlet,必须覆写以下其中之一的方法:
* a. doGet(),GET请求
* b. doPost(),POST请求
* ...等请求方式
* c. init和destroy管理servlet持有的资源
* d. getServletInfo(),获取servlet本身信息
*
* <p>一般情况下,不覆写service(),该方法控制HTTP请求调度到对应的请求方法中,
* 同样,doOptions()和doTrace()一般也不覆写。
*
* <p>servlet通常运行在多线程服务器上,因此servlet必须处理并发请求,并且要
* 注意同步访问共享资源。共享资源包括内存数据,如:实例、类变量、文件对象、数据
* 库连接和网络连接。
*
* <p>注意:HttpServlet extends GenericServlet implements
* Servlet, ServletConfig, java.io.Serializable。
* @author TCM
* @create 2017年10月26日上午9:00:08
*/
public abstract class HttpServlet extends GenericServlet
{
//HTTP请求方式...
//请求方式对应的处理方法...doGet(),doPost()等
/**
* 反射机制获取请求方式
* @param c
* @return
*/
private Method[] getAllDeclaredMethods(Class<? extends HttpServlet> c) {
Class<?> clazz = c;
Method[] allMethods = null;
while (!clazz.equals(HttpServlet.class)) {
Method[] thisMethods = clazz.getDeclaredMethods();
if (allMethods != null && allMethods.length > 0) {
Method[] subClassMethods = allMethods;
allMethods =
new Method[thisMethods.length + subClassMethods.length];
System.arraycopy(thisMethods, 0, allMethods, 0,
thisMethods.length);
System.arraycopy(subClassMethods, 0, allMethods, thisMethods.length,
subClassMethods.length);
} else {
allMethods = thisMethods;
}
clazz = clazz.getSuperclass();
}
return ((allMethods != null) ? allMethods : new Method[0]);
}
/**
* 处理请求并调度到doXXX()方法内
* @exception IOException
* @exception ServletException
* @see javax.servlet.Servlet#service
*/
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
//根据请求方法进入对应的处理方法中
}
/**
* 判定请求协议是不是HTTP
*/
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
//判定是不是HTTP协议
if (!(req instanceof HttpServletRequest &&
res instanceof HttpServletResponse)) {
throw new ServletException("non-HTTP request or response");
}
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
//进入HTTP请求处理
service(request, response);
}
}
/*
* 响应没有响应体,支持HEAD请求...NoBodyResponse和NoBodyOutputStream类
*/
HttpServlet源码翻译
最新推荐文章于 2021-03-19 11:39:48 发布