简单介绍

Servlet接口实现类

1、Servlet接口SUN公司定义了两个默认实现类,分别为:GenericServlet、HttpServlet。

2、HttpServlet指能够处理HTTP请求的servlet,它在原有Servlet接口上添加了一些与HTTP协议处理方法,它比Servlet接口的功能更为强大。因此开发人员在编写Servlet时,通常应继承这个类,而避免直接去实现Servlet接口。

3、HttpServlet在实现Servlet接口时,覆写了service方法,该方法体内的代码会自动判断用户的请求方式,如为GET请求,则调用HttpServlet的doGet方法,如为Post请求,则调用doPost方法。因此,开发人员在编写Servlet时,通常只需要覆写doGet或doPost方法,而不要去覆写service方法。

接口分离原则:

将一个包含多功能的单一接口根据函数功能分离称多个独立的接口,同时每个接口都有自己特有的、有意义的、具有实际哦那功能的修饰器。
    多重接口修饰:
         每个修饰器设计时都需要首先实现他要修饰的接口,可以配合应用 适配器和修饰器这两个模式来构建多重修饰器,同时也能保证代码量最少。
客户端构建:
    为客户端提供接口实例的方式一定程度上取决于接口实现的数目。如果每个接口都有自己特有的实现,那就需要构造所有实现的实例并提供给客户端。或者如果所有的接口的实现都包含在单个类中,那么只需要构建该类的实例就能够满足客户端的所有依赖。
    1、多接口、多实例:
        控制器类:将所有方法整合到控制器类中(构造函数传入参数为各个接口)。控制器类中的每个方法都需要一个不同的接口来执行他的功能。
    2、单接口、单实例:
        在单个类中继承并实现所有接口。这样将每个接口的实现方法都整合到一个类中。(一般用于叶子实现类)

Servlet的作用:

1.接收请求数据

2.处理请求

3.完成响应

Servlet接口中的五大方法:

其中有三个是生命周期方法:

1.void init(ServletConfig).当Servlet对象被服务器创建时调用,仅调用一次。

2.void service(ServletRequest, ServletResponse).可被服务器调用多次。

3.void destroy().服务器关闭连接之前调用,仅一次。

另外的两个:

4.ServletConfig getServletConfig()

5.String getServletInfo()

Servlet代码源

  1. package javax.servlet;
  2.  
  3. import java.io.IOException;
  4.  
  5. public interface Servlet {
  6. void init(ServletConfig var1) throws ServletException;
  7.  
  8. ServletConfig getServletConfig();
  9.  
  10. void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
  11.  
  12. String getServletInfo();
  13.  
  14. void destroy();
  15. }

HttpServlet代码源

  1. package javax.servlet.http;
  2.  
  3. import java.io.IOException;
  4. import java.lang.reflect.InvocationTargetException;
  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.DispatcherType;
  10. import javax.servlet.GenericServlet;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.ServletOutputStream;
  13. import javax.servlet.ServletRequest;
  14. import javax.servlet.ServletResponse;
  15.  
  16. public abstract class HttpServlet extends GenericServlet {
  17. private static final long serialVersionUID = 1L;
  18. private static final String METHOD_DELETE = "DELETE";
  19. private static final String METHOD_HEAD = "HEAD";
  20. private static final String METHOD_GET = "GET";
  21. private static final String METHOD_OPTIONS = "OPTIONS";
  22. private static final String METHOD_POST = "POST";
  23. private static final String METHOD_PUT = "PUT";
  24. private static final String METHOD_TRACE = "TRACE";
  25. private static final String HEADER_IFMODSINCE = "If-Modified-Since";
  26. private static final String HEADER_LASTMOD = "Last-Modified";
  27. private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
  28. private static final ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");
  29.  
  30. public HttpServlet() {
  31. }
  32.  
  33. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  34. String protocol = req.getProtocol();
  35. String msg = lStrings.getString("http.method_get_not_supported");
  36. if (protocol.endsWith("1.1")) {
  37. resp.sendError(405, msg);
  38. } else {
  39. resp.sendError(400, msg);
  40. }
  41.  
  42. }
  43.  
  44. protected long getLastModified(HttpServletRequest req) {
  45. return -1L;
  46. }
  47.  
  48. protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  49. if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {
  50. this.doGet(req, resp);
  51. } else {
  52. NoBodyResponse response = new NoBodyResponse(resp);
  53. this.doGet(req, response);
  54. response.setContentLength();
  55. }
  56.  
  57. }
  58.  
  59. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  60. String protocol = req.getProtocol();
  61. String msg = lStrings.getString("http.method_post_not_supported");
  62. if (protocol.endsWith("1.1")) {
  63. resp.sendError(405, msg);
  64. } else {
  65. resp.sendError(400, msg);
  66. }
  67.  
  68. }
  69.  
  70. protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  71. String protocol = req.getProtocol();
  72. String msg = lStrings.getString("http.method_put_not_supported");
  73. if (protocol.endsWith("1.1")) {
  74. resp.sendError(405, msg);
  75. } else {
  76. resp.sendError(400, msg);
  77. }
  78.  
  79. }
  80.  
  81. protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  82. String protocol = req.getProtocol();
  83. String msg = lStrings.getString("http.method_delete_not_supported");
  84. if (protocol.endsWith("1.1")) {
  85. resp.sendError(405, msg);
  86. } else {
  87. resp.sendError(400, msg);
  88. }
  89.  
  90. }
  91.  
  92. private static Method[] getAllDeclaredMethods(Class<?> c) {
  93. if (c.equals(HttpServlet.class)) {
  94. return null;
  95. } else {
  96. Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
  97. Method[] thisMethods = c.getDeclaredMethods();
  98. if (parentMethods != null && parentMethods.length > 0) {
  99. Method[] allMethods = new Method[parentMethods.length + thisMethods.length];
  100. System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);
  101. System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);
  102. thisMethods = allMethods;
  103. }
  104.  
  105. return thisMethods;
  106. }
  107. }
  108.  
  109. protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  110. Method[] methods = getAllDeclaredMethods(this.getClass());
  111. boolean ALLOW_GET = false;
  112. boolean ALLOW_HEAD = false;
  113. boolean ALLOW_POST = false;
  114. boolean ALLOW_PUT = false;
  115. boolean ALLOW_DELETE = false;
  116. boolean ALLOW_TRACE = true;
  117. boolean ALLOW_OPTIONS = true;
  118. Class clazz = null;
  119.  
  120. try {
  121. clazz = Class.forName("org.apache.catalina.connector.RequestFacade");
  122. Method getAllowTrace = clazz.getMethod("getAllowTrace", (Class[])null);
  123. ALLOW_TRACE = (Boolean)getAllowTrace.invoke(req, (Object[])null);
  124. } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException var14) {
  125. ;
  126. }
  127.  
  128. for(int i = 0; i < methods.length; ++i) {
  129. Method m = methods[i];
  130. if (m.getName().equals("doGet")) {
  131. ALLOW_GET = true;
  132. ALLOW_HEAD = true;
  133. }
  134.  
  135. if (m.getName().equals("doPost")) {
  136. ALLOW_POST = true;
  137. }
  138.  
  139. if (m.getName().equals("doPut")) {
  140. ALLOW_PUT = true;
  141. }
  142.  
  143. if (m.getName().equals("doDelete")) {
  144. ALLOW_DELETE = true;
  145. }
  146. }
  147.  
  148. String allow = null;
  149. if (ALLOW_GET) {
  150. allow = "GET";
  151. }
  152.  
  153. if (ALLOW_HEAD) {
  154. if (allow == null) {
  155. allow = "HEAD";
  156. } else {
  157. allow = allow + ", HEAD";
  158. }
  159. }
  160.  
  161. if (ALLOW_POST) {
  162. if (allow == null) {
  163. allow = "POST";
  164. } else {
  165. allow = allow + ", POST";
  166. }
  167. }
  168.  
  169. if (ALLOW_PUT) {
  170. if (allow == null) {
  171. allow = "PUT";
  172. } else {
  173. allow = allow + ", PUT";
  174. }
  175. }
  176.  
  177. if (ALLOW_DELETE) {
  178. if (allow == null) {
  179. allow = "DELETE";
  180. } else {
  181. allow = allow + ", DELETE";
  182. }
  183. }
  184.  
  185. if (ALLOW_TRACE) {
  186. if (allow == null) {
  187. allow = "TRACE";
  188. } else {
  189. allow = allow + ", TRACE";
  190. }
  191. }
  192.  
  193. if (ALLOW_OPTIONS) {
  194. if (allow == null) {
  195. allow = "OPTIONS";
  196. } else {
  197. allow = allow + ", OPTIONS";
  198. }
  199. }
  200.  
  201. resp.setHeader("Allow", allow);
  202. }
  203.  
  204. protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  205. String CRLF = "\r\n";
  206. StringBuilder buffer = (new StringBuilder("TRACE ")).append(req.getRequestURI()).append(" ").append(req.getProtocol());
  207. Enumeration reqHeaderEnum = req.getHeaderNames();
  208.  
  209. while(reqHeaderEnum.hasMoreElements()) {
  210. String headerName = (String)reqHeaderEnum.nextElement();
  211. buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
  212. }
  213.  
  214. buffer.append(CRLF);
  215. int responseLength = buffer.length();
  216. resp.setContentType("message/http");
  217. resp.setContentLength(responseLength);
  218. ServletOutputStream out = resp.getOutputStream();
  219. out.print(buffer.toString());
  220. out.close();
  221. }
  222.  
  223. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  224. String method = req.getMethod();
  225. long lastModified;
  226. if (method.equals("GET")) {
  227. lastModified = this.getLastModified(req);
  228. if (lastModified == -1L) {
  229. this.doGet(req, resp);
  230. } else {
  231. long ifModifiedSince;
  232. try {
  233. ifModifiedSince = req.getDateHeader("If-Modified-Since");
  234. } catch (IllegalArgumentException var9) {
  235. ifModifiedSince = -1L;
  236. }
  237.  
  238. if (ifModifiedSince < lastModified / 1000L * 1000L) {
  239. this.maybeSetLastModified(resp, lastModified);
  240. this.doGet(req, resp);
  241. } else {
  242. resp.setStatus(304);
  243. }
  244. }
  245. } else if (method.equals("HEAD")) {
  246. lastModified = this.getLastModified(req);
  247. this.maybeSetLastModified(resp, lastModified);
  248. this.doHead(req, resp);
  249. } else if (method.equals("POST")) {
  250. this.doPost(req, resp);
  251. } else if (method.equals("PUT")) {
  252. this.doPut(req, resp);
  253. } else if (method.equals("DELETE")) {
  254. this.doDelete(req, resp);
  255. } else if (method.equals("OPTIONS")) {
  256. this.doOptions(req, resp);
  257. } else if (method.equals("TRACE")) {
  258. this.doTrace(req, resp);
  259. } else {
  260. String errMsg = lStrings.getString("http.method_not_implemented");
  261. Object[] errArgs = new Object[]{method};
  262. errMsg = MessageFormat.format(errMsg, errArgs);
  263. resp.sendError(501, errMsg);
  264. }
  265.  
  266. }
  267.  
  268. private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
  269. if (!resp.containsHeader("Last-Modified")) {
  270. if (lastModified >= 0L) {
  271. resp.setDateHeader("Last-Modified", lastModified);
  272. }
  273.  
  274. }
  275. }
  276.  
  277. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
  278. HttpServletRequest request;
  279. HttpServletResponse response;
  280. try {
  281. request = (HttpServletRequest)req;
  282. response = (HttpServletResponse)res;
  283. } catch (ClassCastException var6) {
  284. throw new ServletException("non-HTTP request or response");
  285. }
  286.  
  287. this.service(request, response);
  288. }
  289. }

GenericServlet代码源

  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 {
  8. private static final long serialVersionUID = 1L;
  9. private transient ServletConfig config;
  10.  
  11. public GenericServlet() {
  12. }
  13.  
  14. public void destroy() {
  15. }
  16.  
  17. public String getInitParameter(String name) {
  18. return this.getServletConfig().getInitParameter(name);
  19. }
  20.  
  21. public Enumeration<String> getInitParameterNames() {
  22. return this.getServletConfig().getInitParameterNames();
  23. }
  24.  
  25. public ServletConfig getServletConfig() {
  26. return this.config;
  27. }
  28.  
  29. public ServletContext getServletContext() {
  30. return this.getServletConfig().getServletContext();
  31. }
  32.  
  33. public String getServletInfo() {
  34. return "";
  35. }
  36.  
  37. public void init(ServletConfig config) throws ServletException {
  38. this.config = config;
  39. this.init();
  40. }
  41.  
  42. public void init() throws ServletException {
  43. }
  44.  
  45. public void log(String msg) {
  46. this.getServletContext().log(this.getServletName() + ": " + msg);
  47. }
  48.  
  49. public void log(String message, Throwable t) {
  50. this.getServletContext().log(this.getServletName() + ": " + message, t);
  51. }
  52.  
  53. public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
  54.  
  55. public String getServletName() {
  56. return this.config.getServletName();
  57. }
  58. }

实现接口代码:

  1. package com.wbg;
  2.  
  3. import javax.servlet.*;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9.  
  10. @WebServlet("/MyServlet")
  11. public class MyServlet implements Servlet {
  12.  
  13. @Override
  14. public void init(ServletConfig servletConfig) throws ServletException {
  15. System.out.println("初始化servlet");
  16. }
  17.  
  18. @Override
  19. public ServletConfig getServletConfig() {
  20. System.out.println("getServletConfig()");
  21. return null;
  22. }
  23.  
  24. @Override
  25. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  26. System.out.println("正在销毁");
  27. }
  28.  
  29. @Override
  30. public String getServletInfo() {
  31. System.out.println("getServletInfo()");
  32. return null;
  33. }
  34.  
  35. @Override
  36. public void destroy() {
  37. System.out.println("正在销毁");
  38. }
  39. }

浏览器访问servlet时,需要将servlet与路径绑定,需要在web.xml中对servlet进行配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <servlet>
  7.  
  8. <servlet-name>testservlet</servlet-name>
  1. <servlet-class>com.wbg.testservlet</servlet-class>
  2. </servlet>
  3. </web-app>

实现接口的意义:

1、接口和实现分离给软件系统提供了无限的想像空间,才使得软件世界如此丰富多彩。

2、接口和实现分离使得多态变为可能

3、接口和实现分离使得解耦变为可能

4、接口和实现分离使得组合更有意义

5、接口和实现分离使得设计模式变为可能,才能衍生出23种设计模式。

简单的说接口和实现分离给软件系统提供了无限的想象空间、多态变为可能、解耦变为可能、组合更有意义、设计模式变为可能,才能衍生出23钟设计模式(创建型、结构型、行为型)

servlet三种方式实现servlet接口的更多相关文章

  1. Servlet接口应用(开发servlet三种方式)

    参见 文库/java/javaEE全新学习教程2.2节 1.通过URL调用 2通过提交表单 3超链接 4 javascript写一个函数,调用这个函数 1,首先在工程的WebRoot文件夹下建立一个j ...

  2. 开发servlet三种方式

    第一种:实现Servlet接口 ServletDemo类 实现Servlet接口 public class ServletDemo implements Servlet { //初始化该servlet ...

  3. 创建线程的第三种方式——使用Callable接口

    Callable是类似于Runnable的接口,实现Callable的类和实现Runnable的类都是可被其他线程执行的任务. 优点:有返回值 缺点:实现繁琐 简单实现: CallableAndFut ...

  4. Servlet实现的三种方式

    实现Servlet的三种方式:一个实现,两个继承 /*========================================== * servlet的执行过程: * 1.创建servlet对 ...

  5. 创建servlet的三种方式

    第一种方式,实现Servlet接口 package com.example.servlet; import java.io.IOException; import javax.servlet.Serv ...

  6. 详细理解servlet实现的三种方式和生命周期

    阅读目录 开发servlet的三种方式 理解实现servlet接口的方式,理解servlet生命周期 Servlet接口有五个方法 继承GenericServlet 继承HttpServlet 现在很 ...

  7. SpringBoot学习笔记(6)----SpringBoot中使用Servlet,Filter,Listener的三种方式

    在一般的运用开发中Controller已经大部分都能够实现了,但是也不排除需要自己实现Servlet,Filter,Listener的方式,SpringBoot提供了三种实现方式. 1. 使用Bean ...

  8. Servlet三种创建方式

    直接实现 Servlet 接口不太方便,所以 Servlet 又内置了两个 Servlet 接口的实现类(抽象类),分别为 GenericServlet 和 HttpServlet,因此,创建 Ser ...

  9. java:struts框架2(方法的动态和静态调用,获取Servlet API三种方式(推荐IOC(控制反转)),拦截器,静态代理和动态代理(Spring AOP))

    1.方法的静态和动态调用: struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCT ...

随机推荐

  1. Best HTTP

    http://blog.csdn.net/u012322710/article/details/52860747 Best HTTP (Pro)  这是一款很多公司都在用的网页插件,感觉确实不错,分P ...

  2. C# 面试题二

    1.        请编程实现一个冒泡排序算法? int [] array = new int [*] ; ; ; i < array.Length - ; i++) { ; j < ar ...

  3. bzoj 5291: [Bjoi2018]链上二次求和

    Description 有一条长度为n的链(1≤i<n,点i与点i+1之间有一条边的无向图),每个点有一个整数权值,第i个点的权值是 a_i.现在有m个操作,每个操作如下: 操作1(修改):给定 ...

  4. ICONIX方法(用例分析方法实例教程)

  5. 冒泡排序——Java实现

    一.排序思想 比较相邻的元素.如果第一个比第二个大,就交换他们两个. 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对.在这一点,最后的元素应该会是最大的数. 针对所有的元素重复以上的步骤, ...

  6. Redis的Publish/Subscribe

    Publish/Subscribe 从字面上理解就是发布(Publish)与订阅(Subscribe),在Redis中,你可以设定对某一个key值进行消息发布及消息订阅,当一个key值上进行了消息发布 ...

  7. sublime开启vi编辑器功能,与vi常用快捷键

    sublime开启vi编辑器 install package -> vintageES 设置里面 ignored_packages 里面的vintage去掉 VI命令 游标控制 h 游标向左移 ...

  8. PAT 1076 Forwards on Weibo

    #include <cstdio> #include <cstdlib> #include <vector> #include <queue> #inc ...

  9. The eighteen day

    27th Nov 2018 Setting goals is the first step in turning the invisible into the visiable   ---Tony R ...

  10. 【Linux】小应用 大智慧

    小应用 大智慧--重视 以工程师的标准要求自己