1. BaseServlet 的作用

  • 让一个Servlet可以处理多种不同的请求,不同的请求调用Servlet的不同方法.

2. 实现原理

  • 客户端发送请求时, 必须多给出一个参数, 用来说明要调用的方法!! 这样,BaseServlet 通过该参数来

    调用目标方法.
  • 请求处理方法的签名必须与 service 相同, 即方法的返回值和参数,以及声明的异常都相同.

// 代码示例
public class AServlet extends HttpServlet{ // service 方法
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ // 获取参数, 用来识别客户端想请求的方法
// 然后判断是哪一个方法, 是哪一个方法,就调用哪一个方法. // 我们这里给参数的名字为 method
String methodName = req.getParameter("method"); if(methodName.equals("addUser")){
addUser(req,resp);
}else if(methodName.equals("editUser")){
editUser(req,resp);
}else if(methodName.equals("deleteUser")){
deleteUser(req,resp);
}
} // 添加客户的方法
public void addUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
} // 编辑客户的方法
public void editUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
} // 删除客户的方法
public void deleteUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
}
} // 升级版
/*
* 思路:
* 得到方法名称, 是否可以通过反射来调用方法?
* 步骤:
* 1. 得到方法名, 通过方法名再得到 Method 类的对象
* 2. 需要得到 class, 然后调用它的方法进行查询! 得到 Method
* 3. 我们要查询的是当前类的方法, 所以我们需要得到当前类的 Class
*/ public abstact class BaseServlet extends HttpServlet{ public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ // 获取参数, 用来识别用户想请求的方法
String methodName = req.getParameter("method"); // 判断该参数是否存在, 不存在,抛出异常
if(methodName == null || methodName.trim().isEmpty()){
throw new RuntimeException("您没有传递 method 参数! 无法确定您想调用的方法");
} // 得到当前类的 class 对象
Class c = this.getClass(); // 查询方法, 参数需要: 方法名和该方法的参数类型
// 该方法的参数类型必须与 service 中的参数类型一致
Method method = null;
try{
method = c.getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch(Exception e){
throw new RuntimeException("您要调用的方法"+methodName+",它不存在!");
} // 调用 method 方法
// 反射调用, 第一参数表示当前类,
// 正常调用: this.method(req,resp)
try{
method.invoke(this,req,resp);
} catch(Exception e){
throw new RuntimeException(e);
}
} // AServlet 继承 BaseServlet
public void class AServlet extends BaseServlet{
// 添加客户的方法
public void addUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
} // 编辑客户的方法
public void editUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
} // 删除客户的方法
public void deleteUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()....");
}
} // 处理转发和重定向问题
public void class BServlet extends BaseServlet{ // 添加客户的方法
public String addUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()...."); // 返回表示转发的字符串, "f" 表示 forward
return "f:/index.jsp";
} // 编辑客户的方法
public String editUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()...."); // 返回表示重定向的字符串, "r" 表示 redirect
return "r:/index.jsp";
} // 删除客户的方法
public String deleteUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{ System.out.println("addUser()...."); return null;
}
} // BaseServlet 升级
public void abstract BaseServlet extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException{ String methdoName = req.getParameter("method"); if(methodName == null || methodName.trim().isEmpty()){
throw new RuntimeException("您没有传递method参数,无法确定要调用的方法!");
} Class c = this.getClass(); Method method=null;
try{
method = c.getMethod(methodName,
HttpServletRequest.class,HttpServletResponse.class);
}catch(Exception e){
throw new RuntimeException("您要调用的"+methodName+"方法,它不存在!");
} // 调用 method 方法 try{ String result = (String)method.invoke(this,req,resp); /*
* 获取请求处理方法执行后返回的字符串, 它表示转发或重定向的路径!
* 完成转发或重定向.
*
* 如果用户返回的字符串为 null, 或为 "", 那么我们什么也不做!
*
* 查看返回的字符串中是否包含冒号, 如果没有, 表示转发
* 如果有, 使用冒号分割字符串, 得到前缀和后缀!!
* 其中前缀如果是 f, 表示转发, 如果是 r, 表示重定向, 后缀就是要转发或重定向的路径了!
*/ if(result == null || result.trim().isEmpty()){
return;
} // 如果不为空
if(result.contains(":")){
// 使用冒号分割字符串, 得到前缀和后缀
int index = result.indexOf(":"); // 获取冒号的位置
String s = result.substring(0,index); // 获取前缀
String path = result.subString(index+1); // 获取后缀, 即路径 if(e.equalsIgnoreCase("r")){ // 如果前缀是 r, 重定向
resp.sendRedirect(req.getContextPath()+path);
}else if(e.equalsIgnoreCase("f")){
req.getRequestDispatcher(path).forward(req,resp);
} else {
throw new RuntimeException("您指定的操作:"+s+",当前版本不支持!");
} } else { // 没有冒号, 默认为转发
req.getRequestDispatcher(result).forward(req,resp);
} }catch(Exception e){
throw new RuntimeException(e);
}
}
}

参考资料:

BaseServlet 介绍的更多相关文章

  1. day18(JDBC事务&连接池介绍&DBUtils工具介绍&BaseServlet作用)

    day18总结 今日思维导图: 今日内容 事务 连接池 ThreadLocal BaseServlet自定义Servlet父类(只要求会用,不要求会写) DBUtils à commons-dbuti ...

  2. 十三、事务、连接池 、ThreadLocal 、BaseServlet自定义Servlet父类 、 DBUtils à commons-dbutils

    l 事务 l 连接池 l ThreadLocal l BaseServlet自定义Servlet父类(只要求会用,不要求会写) l DBUtils à commons-dbutils 事务 l 事务的 ...

  3. CSS3 background-image背景图片相关介绍

    这里将会介绍如何通过background-image设置背景图片,以及背景图片的平铺.拉伸.偏移.设置大小等操作. 1. 背景图片样式分类 CSS中设置元素背景图片及其背景图片样式的属性主要以下几个: ...

  4. MySQL高级知识- MySQL的架构介绍

    [TOC] 1.MySQL 简介 概述 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB公司开发,目前属于Oracle公司. MySQL是一种关联数据库管理系统,将数据保存在不同的表中,而 ...

  5. Windows Server 2012 NIC Teaming介绍及注意事项

    Windows Server 2012 NIC Teaming介绍及注意事项 转载自:http://www.it165.net/os/html/201303/4799.html Windows Ser ...

  6. Linux下服务器端开发流程及相关工具介绍(C++)

    去年刚毕业来公司后,做为新人,发现很多东西都没有文档,各种工具和地址都是口口相传的,而且很多时候都是不知道有哪些工具可以使用,所以当时就想把自己接触到的这些东西记录下来,为后来者提供参考,相当于一个路 ...

  7. JavaScript var关键字、变量的状态、异常处理、命名规范等介绍

    本篇主要介绍var关键字.变量的undefined和null状态.异常处理.命名规范. 目录 1. var 关键字:介绍var关键字的使用. 2. 变量的状态:介绍变量的未定义.已定义未赋值.已定义已 ...

  8. HTML DOM 介绍

    本篇主要介绍DOM内容.DOM 节点.节点属性以及获取HTML元素的方法. 目录 1. 介绍 DOM:介绍DOM,以及对DOM分类和功能的说明. 2. DOM 节点:介绍DOM节点分类和节点层次. 3 ...

  9. HTML 事件(一) 事件的介绍

    本篇主要介绍HTML中的事件知识:事件相关术语.DOM事件规范.事件对象. 其他事件文章 1. HTML 事件(一) 事件的介绍 2. HTML 事件(二) 事件的注册与注销 3. HTML 事件(三 ...

随机推荐

  1. 基于Jekyll的博客模板

    代码地址如下:http://www.demodashi.com/demo/13147.html 效果 环境配置 环境 Windows 10 Git Bash 安装ruby 下载rubyinstalle ...

  2. 基于python实现的DDoS

    目录 一个简单的网络僵尸程序 一个简单的DOS攻击程序 整合网络僵尸和DoS攻击--DDoS 代码地址如下:http://www.demodashi.com/demo/12002.html 本例子包含 ...

  3. 深入分析JavaWeb Item22 -- 国际化(i18n)

    一.国际化开发概述 软件的国际化:软件开发时,要使它能同一时候应对世界不同地区和国家的訪问,并针对不同地区和国家的訪问.提供对应的.符合来訪者阅读习惯的页面或数据. 国际化(international ...

  4. Linux管理员必须知道的sudo命令

    "Sudo"是Unix/Linux平台上的一个很实用的工具,它同意系统管理员分配给普通用户一些合理的"权利",让他们执行一些仅仅有超级用户或其它 特许用户才干完 ...

  5. Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net

    Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码, 1 1.1. 子模式 urlsafe Or  url  ...

  6. ModelSim6.2 설치에 관한(About the Installation problem of ModelSim 6.2)

    ModelSim 설치는 PC OS 따라서 호환성 문제가 발생한다. !!!!!! Vista OS에서는 ModelSim 설치가 안됨(호환성 문제) XP, Win7에서는 호환성 문제 없 ...

  7. Ionic学习笔记1_基本布局

    <body> <!-- 头部 -->                               bar里嵌入子元素:title,button,button-bar和 inpu ...

  8. nginx+python+fastcgi环境配置(flup版本)

    昨天花了一整天的时间研究搭建了nginx+python+fastcgi环境,并测试没问题,由于是第一次,并且参考了网上很多东西,网上也有很多,但还是把自己的过程记录下. 主要感谢这位兄弟的文章给了我很 ...

  9. FineReport实现java报表多级上报的效果图

    Java报表-上报流程管理 Java报表-上报任务管理 Java报表-我的上报任务 Java报表-系统说明

  10. Centos 7 启动错误:XFS_WANT_CORRUPTED_GOTO 修复

    参考源 如果出现以下报错 [sda] Assuming drive cache: write through Internal error xfs XFS_WANT_CORRUPTED_GOTO at ...