Servlet_体系结构
6. Servlet的体系结构
Servlet -- 接口
|
GenericServlet -- 抽象类
|
HttpServlet -- 抽象类
* GenericServlet:将Servlet接口中其他的方法做了默认空实现,只将service()方法作为抽象
* 将来定义Servlet类时,可以继承GenericServlet,实现service()方法即可
* HttpServlet:对http协议的一种封装,简化操作
1. 定义类继承HttpServlet
2. 复写doGet/doPost方法
package com.learn.web.servlet;import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;@WebServlet("/demo1")
public class ServletDemo1 implements Servlet {@Overridepublic void init(ServletConfig servletConfig) throws ServletException {}@Overridepublic ServletConfig getServletConfig() {return null;}@Overridepublic void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {System.out.println("demo1....");}@Overridepublic String getServletInfo() {return null;}@Overridepublic void destroy() {}}
package com.learn.web.servlet;import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/demo2")
public class ServletDemo2 extends GenericServlet {@Overridepublic void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {System.out.println("demo2.....");}}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package javax.servlet;import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {private static final long serialVersionUID = 1L;private transient ServletConfig config;public GenericServlet() {}public void destroy() {}public String getInitParameter(String name) {return this.getServletConfig().getInitParameter(name);}public Enumeration<String> getInitParameterNames() {return this.getServletConfig().getInitParameterNames();}public ServletConfig getServletConfig() {return this.config;}public ServletContext getServletContext() {return this.getServletConfig().getServletContext();}public String getServletInfo() {return "";}public void init(ServletConfig config) throws ServletException {this.config = config;this.init();}public void init() throws ServletException {}public void log(String msg) {this.getServletContext().log(this.getServletName() + ": " + msg);}public void log(String message, Throwable t) {this.getServletContext().log(this.getServletName() + ": " + message, t);}public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;public String getServletName() {return this.config.getServletName();}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package javax.servlet.http;import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.servlet.DispatcherType;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;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("javax.servlet.http.LocalStrings");public HttpServlet() {}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(405, msg);} else {resp.sendError(400, msg);}}protected long getLastModified(HttpServletRequest req) {return -1L;}protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {this.doGet(req, resp);} else {NoBodyResponse response = new NoBodyResponse(resp);this.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(405, msg);} else {resp.sendError(400, 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(405, msg);} else {resp.sendError(400, 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(405, msg);} else {resp.sendError(400, msg);}}private static Method[] getAllDeclaredMethods(Class<?> c) {if (c.equals(HttpServlet.class)) {return null;} else {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;Class clazz = null;try {clazz = Class.forName("org.apache.catalina.connector.RequestFacade");Method getAllowTrace = clazz.getMethod("getAllowTrace", (Class[])null);ALLOW_TRACE = (Boolean)getAllowTrace.invoke(req, (Object[])null);} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException var14) {;}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 = "GET";}if (ALLOW_HEAD) {if (allow == null) {allow = "HEAD";} else {allow = allow + ", HEAD";}}if (ALLOW_POST) {if (allow == null) {allow = "POST";} else {allow = allow + ", POST";}}if (ALLOW_PUT) {if (allow == null) {allow = "PUT";} else {allow = allow + ", PUT";}}if (ALLOW_DELETE) {if (allow == null) {allow = "DELETE";} else {allow = allow + ", DELETE";}}if (ALLOW_TRACE) {if (allow == null) {allow = "TRACE";} else {allow = allow + ", TRACE";}}if (ALLOW_OPTIONS) {if (allow == null) {allow = "OPTIONS";} else {allow = allow + ", OPTIONS";}}resp.setHeader("Allow", allow);}protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String CRLF = "\r\n";StringBuilder buffer = (new StringBuilder("TRACE ")).append(req.getRequestURI()).append(" ").append(req.getProtocol());Enumeration reqHeaderEnum = req.getHeaderNames();while(reqHeaderEnum.hasMoreElements()) {String headerName = (String)reqHeaderEnum.nextElement();buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));}buffer.append(CRLF);int responseLength = buffer.length();resp.setContentType("message/http");resp.setContentLength(responseLength);ServletOutputStream out = resp.getOutputStream();out.print(buffer.toString());out.close();}protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String method = req.getMethod();long lastModified;if (method.equals("GET")) {lastModified = this.getLastModified(req);if (lastModified == -1L) {this.doGet(req, resp);} else {long ifModifiedSince;try {ifModifiedSince = req.getDateHeader("If-Modified-Since");} catch (IllegalArgumentException var9) {ifModifiedSince = -1L;}if (ifModifiedSince < lastModified / 1000L * 1000L) {this.maybeSetLastModified(resp, lastModified);this.doGet(req, resp);} else {resp.setStatus(304);}}} else if (method.equals("HEAD")) {lastModified = this.getLastModified(req);this.maybeSetLastModified(resp, lastModified);this.doHead(req, resp);} else if (method.equals("POST")) {this.doPost(req, resp);} else if (method.equals("PUT")) {this.doPut(req, resp);} else if (method.equals("DELETE")) {this.doDelete(req, resp);} else if (method.equals("OPTIONS")) {this.doOptions(req, resp);} else if (method.equals("TRACE")) {this.doTrace(req, resp);} else {String errMsg = lStrings.getString("http.method_not_implemented");Object[] errArgs = new Object[]{method};errMsg = MessageFormat.format(errMsg, errArgs);resp.sendError(501, errMsg);}}private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {if (!resp.containsHeader("Last-Modified")) {if (lastModified >= 0L) {resp.setDateHeader("Last-Modified", lastModified);}}}public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {HttpServletRequest request;HttpServletResponse response;try {request = (HttpServletRequest)req;response = (HttpServletResponse)res;} catch (ClassCastException var6) {throw new ServletException("non-HTTP request or response");}this.service(request, response);}
}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><form action="/demo3" method="POST"><input name="username"><input type="submit" value="提交"></form>
<hr><a href="/day14/requestDemo4">demo4...</a></body>
</html>
package com.learn.web.servlet;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/demo3")
public class ServletDemo3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("doGet....");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("doPost...");}
}
Servlet_体系结构相关推荐
- Servlet和HTTP请求协议-学习笔记02【Servlet_体系结构与urlpartten配置、HTTP请求协议】
Java后端 学习路线 笔记汇总表[黑马程序员] Servlet和HTTP请求协议-学习笔记01[Servlet_快速入门-生命周期方法.Servlet_3.0注解配置.IDEA与tomcat相关配置 ...
- JAVAWEB入门之Servlet_体系结构
我们建的这个类要继承复写Servlet的所有方法,但是这会很麻烦,所有的写出来很繁琐当摆设,所以我们想,可不可以定义一个类,然后继承这些类和方法, Servlet的体系结构, Servlet----接 ...
- Servlet和HTTP请求协议-学习笔记01【Servlet_快速入门-生命周期方法、Servlet_3.0注解配置、IDEA与tomcat相关配置】
Java后端 学习路线 笔记汇总表[黑马程序员] Servlet和HTTP请求协议-学习笔记01[Servlet_快速入门-生命周期方法.Servlet_3.0注解配置.IDEA与tomcat相关配置 ...
- 新手学java 学哪方面_初学者学Java应从哪些方面学习?
原标题:初学者学Java应从哪些方面学习? Java作为应用于网络的最好语言,前景无限看好.然而,就算用Java建造一个不是很烦琐的web应用,也不是件轻松的事情.那么,初学者学Java应从哪些方面学 ...
- 黑马旅游网完整代码_JavaWeb+黑马旅游网
JavaWeb+黑马旅游网 |____资料 |____16.黑马旅游网 |____15.Maven基础 |____14.Redis |____13.Ajax和JSON |____12.Jquery | ...
- 黑马旅游网完整代码_JavaWeb黑马旅游网 视频 下载
课程目录: JavaWeb+黑马旅游网 |____资料 |____16.黑马旅游网 |____15.Maven基础 |____14.Redis |____13.Ajax和JSON |____12.Jq ...
- 自学java,学多久可以自己找到工作?
前言 回想几年前的自己,在学校里面左手稳着键盘,右手捏住鼠标,不停的动着右手的中指,一声Penta KIll把自己带入了一个虚幻的世界 日复一日,之前那个好学又勤奋的自己慢慢开始转变,从每天的外卖到内 ...
- 王道考研 计算机网络笔记 第一章:概述计算机网络体系结构
本文基于2019 王道考研 计算机网络: 2019 王道考研 计算机网络 个人笔记总结 后续章节将陆续更新- 目录 一.概念.功能.组成.分类 1. 计算机网络的概念 2. 计算机网络功能 3. 计算 ...
- 基于ARMv8的固件系统体系结构
基于ARMv8的固件系统体系结构 The architecture of ARMv8-based firmware systems 自2011年发布以来,ARMv8处理器架构在移动设备市场上已经相当普 ...
最新文章
- 四. python的time和datetime 模块
- Windows下MySql安装【图文】
- WebRTC 的传输协议
- oracle rac启动关闭,Oracle RAC启动及关闭步骤
- makefile 基础(转)
- 十大经典排序算法3(Python版本)
- One Web MKey
- 2017界面UI设计风格流行什么?(一)
- cin.get()的用法
- Python告诉你NBA球星都喜欢在哪个位置出手?
- 关于“长尾理论”(The Long Tail)
- asan c/c++内存检测
- 仙剑奇侠传亿仙java_《仙剑奇侠传-忆仙》图文攻略之三
- 在Ubuntu下安装netspeed查看网络速度
- Python 新手入门引导。
- 牛津5000词汇表(The Oxford 5000™)
- Python连载(0013): 字典(dict)
- C语言:计算同一年内两个日期的相隔天数
- Glide加载动态图片
- unity|加载AB包|有依赖关系的AB包
热门文章
- 利用线性链表基本操作完成两个有序线性表的合并
- Activiti+oracle 启动项目时不能自动建表或更新表的问题分析及解决办法
- POSIX 线程编程(二)线程建立与终止
- 测试Live Writer
- 【存储过程】Merge Into语句实现Insert/Update在Oracle中的应用
- JSP学习总结:2006
- [转:作者: 出处:javaresearch ]选择JSF不选Struts的十大理由
- 在同一基准下对前端框架进行比较(2019年更新)
- 安装NodeJs运行环境
- Fedora 24的用户,千万不要在桌面里运行 `dnf update`