Servlet入门
略,参考讲义
Servlet深入
生命周期
创建过程: Servlet第一次被访问时,由Tomcat创建
销毁过程: 项目被卸载时,由Tomcat销毁
启动时加载
配置
load-on-startup
项
默认值为-1,负数代表着,第一次被访问时创建。非负数意味着,项目启动时,就创建。数字越小,优先级越高
建议配置成2或以上
HTTP & Request
HTTP组成
由请求与响应组成
特点:
- 一问一答
- 先问后答
- 问和答一一对应
请求组成
请求行
请求头
请求体
请求行API
request.getContextPath()
request.getServletPath()
@WebServlet("/request_line")
public class RequestLineServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 请求方式
System.out.println("Method: " + request.getMethod());
// URL
System.out.println("URL: " + request.getRequestURL());
System.out.println("URI: " + request.getRequestURI());
System.out.println("资源路径: " + request.getServletPath());
System.out.println("项目路径: " + request.getContextPath());
// 协议/版本号
System.out.println("Protocol: " + request.getProtocol());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
请求头API
request.getHeader()
@WebServlet("/request_header")
public class RequestHeaderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// String userAgent = request.getHeader("User-Agent");
// System.out.println(userAgent);
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + request.getHeader(headerName));
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}