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. Android Serialization序列化

    Android Serialization 目的: 为了方便測试传感器数据处理算法,Android程序的採集数据.序列化保存为文件.pc程序再通过反序列化读入对象,在PC上測试算法. Java 序列化 ...

  2. jQuery框架源码解读

    1.jQuery 1.9.1 parseJSON: function( data ) { // Attempt to parse using the native JSON parser first ...

  3. Bootstrap组件之导航

    .nav--指定列表元素为导航组件. .nav-tabs--指定导航组件的样式为标签页: .nav-pills--指定导航组件的样式为胶囊式标签页: .nav-stacked--指定标签页的样式为垂直 ...

  4. Linux的Samba服务器

    1.samba服务器概述 Samba最先在Linux和windows两平台之间架起一座桥梁,正是由于samba的出现,我们可以在Linux系统和Windows系统之间相互通信,比如拷贝文件,实现不同操 ...

  5. C++程序设计(第4版)读书笔记_指针、数组与引用

    void * 函数指针和指向类成员的指针不能被赋给void * 字符串字面值常量 #include <iostream> using namespace std; void f() { c ...

  6. python-扫描某一网段下的ip

    #!/usr/bin/env python #-*- coding:utf-8 -*- ############################ #File Name: ipscaner.py #Au ...

  7. std::vector

    Vector Vectors are sequence containers representing arrays that can change in size. Just like arrays ...

  8. python模块学习之six模块

    Six:Python 2和3兼容性库 Six提供了简单的实用程序,用于覆盖Python 2和Python 3之间的差异.它旨在支持在Python 2和3中都可以进行修改的代码库. 六个只包含一个Pyt ...

  9. UIView 实例方法 Instance Methods(转)

    好了,我接着上篇,开始我们的对UIView 实例方法的探索 UIView 实例方法 Instance Methods 初始化一个视图 - (id)initWithFrame:(CGRect)aRect ...

  10. ORACLE函数之日期时间转换函数

     1.          TO_CHAR 语法:TO_CHAR(X [,format]) 说明:将X按format格式转换成字符串.X是一个日期或者数字.format是一个规定了X採用何种格式转换 ...