自制BaseServlet
2016-04-08 16:13
309 查看
一个Servlet中可以有多个请求处理方法,可以利用反射实现
package cn.day19.web.servlet; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BaseServlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response){ String methodName = request.getParameter("method"); if(methodName ==null || methodName.trim().isEmpty()){ throw new RuntimeException("无method参数!"); } //通过反射调用名称 Class c = this.getClass();//得到当前的class对象 Method method = null; try { method =c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); } catch (Exception e) { // TODO Auto-generated catch block throw new RuntimeException("方法不存在"); } //调用method try { String result = (String)method.invoke(this, request,response); 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(s.equalsIgnoreCase("r")){ //如果前缀是r,那么重定向 response.sendRedirect(request.getContextPath()+path); }else if(s.equalsIgnoreCase("f")){//f:转发 request.getRequestDispatcher(path).forward(request, response); }else { throw new RuntimeException("没有指定的"+s+"操作"); } }else{//没有冒号,默认为转发 request.getRequestDispatcher(result).forward(request, response); } } catch (Exception e) { // TODO Auto-generated catch block throw new RuntimeException(); } } }
相关文章推荐
- 你想建设一个能承受500万PV/每天的网站吗?
- UVA_104_Arbitrage
- 欧拉环、欧拉路径的判定和求法
- 面试问题,将字符串、字符串单词倒叙输出
- 泛型依赖注入
- WKNavigationDelegate调用的顺序
- Hadoop和spark通信机制
- 在竞赛ACM Java处理输入输出
- linux下安装mongodb3.2.4
- 数组分段查找
- css 相对电脑窗口定位
- Service详解(五):使用Messager进行通信
- 【笔记】 《js权威指南》- 第17章 事件处理 - 17.2 - 17.3
- C语言之数组冒泡排序方法(学习之路)
- C++之运算符重载
- MySql远程不能登录问题解决办法
- 两个一维数组合并为对应的二维数组(array_merge_recursive)
- Netty1——概况
- Tomcat eclipse 启动时一个工程影响另一个工程
- 如何选择加密芯片?