package cn.itcast.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class AServlet extends BaseServlet { private static final long serialVersionUID = 1L; /*@Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { * 1、获取参数,用来说明要调用的方法
* 2、然后判断是哪个方法执行 String methodName=req.getParameter("method"); if(methodName == null || methodName.trim().isEmpty()){
throw new RuntimeException("您没有传递method参数,无法确定要调用的方法");
}
// if(methodName.equals("addUser")){
// addUser(req,res);
// }else if(methodName.equals("eidtUser")){
// editUser(req,res);
// }else if(methodName.equals("deleteUser")){
// deleteUser(req,res);
// } * 我们发现这样的代码不好复用
* 1、我们可以通过方法名称,使用反射调用呢?
* 需要得到class,然后调用它的方法进行查询
* 我们查询的是当前类的方法 Class c=this.getClass();
Method method=null;
try{
method=c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
}catch(Exception e){
throw new RuntimeException("您要调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 不存在");
} * 调用method try {
method.invoke(this, req,res);
} catch (Exception e) {
System.out.println("您调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 内部抛出了异常");
throw new RuntimeException(e);
} }*/
public void addUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("addUser()...");
throw new IOException("测试一下");
} public void editUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("editUser()...");
} public void findAll(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("findAllUser()...");
} public void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("deleteUser()...");
} }
/**
* 我们发现这样复用性还是不够理想,我们可以抽象出一个弗雷给别人继承
*/
package cn.itcast.web.servlet;

import java.io.IOException;
import java.lang.reflect.Method; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @SuppressWarnings({"rawtypes","unchecked"})
public class BaseServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { String methodName=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+"(HttpServletRequest,HttpServletResponse) 不存在");
}
String text=null;//获取返回值
try {
text=(String) method.invoke(this, req,res);
/*
*获取请求处理方法后返回的字符串,它表示转发或者重定向的路径
*如果返回值中不包含“:”,表示使用默认方式:转发
*如果返回值中包含“:”,将字符串通过“:”截取为两部分,前一部分表示标识,f代表转发,r代表重定向
*如果返回的字符串是null或者"",我们什么也不干
*/
} catch (Exception e) {
System.out.println("您调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 内部抛出了异常");
throw new RuntimeException(e);
}
if(text==null || text.trim().isEmpty()) return;
if(!text.contains(":")){
req.getRequestDispatcher(text).forward(req, res);
}else{
int index=text.indexOf(":");
String bz=text.substring(0, index);
String path=text.substring(index+1);
if(bz.equalsIgnoreCase("r")){
res.sendRedirect(path);
}else if(bz.equalsIgnoreCase("f")){
req.getRequestDispatcher(path).forward(req, res);
}else{
throw new RuntimeException("您的指定:"+bz+"暂时没有开通此业务");
}
} }
/**
* 我们在Servlet中实现重定向和转发感觉有点麻烦,我们希望抽象出来再BaseServlet中处理
* request.getRequestDispatcher("xxx").forward(request,response)
* response.sendRedirect("xxx")
*/ }
package cn.itcast.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class BServlet extends BaseServlet { private static final long serialVersionUID = 1L; public String fun1(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
//return "forward:/index.jsp";
System.out.println("fun1()...");
return "f:/index.jsp";
}
public String fun2(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
//return "redirect:/index.jsp";
System.out.println("fun2()...");
return "r:"+req.getContextPath()+"/index.jsp";
}
public String fun3(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
System.out.println("fun3()...");
return "/index.jsp";
}
public String fun4(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
System.out.println("fun4()...");
return null;
}
public String fun5(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
System.out.println("fun3()...");
return "d:/index.jsp";
}
}

BaseServlet
1.我们希望在一个Servlet中可以有多个请求处理方法
2、客户端发送请求时,必须多给出一个参数,用来说明要调用的方法
3、参数名遵守约定
4、希望帮助简化重定向和转发,利用返回值
domain:User
dao:UserDao
service:UserService
servlet:UserServlet

void init(ServletConfig config)
void destory()
void service(ServletRequest,ServletResponse)throws IOException,ServletException{
在这里让它去调用其他方法!
要求:用户发出请求时,必须给出一个参数

BaseServlet优化Servlet,实现类似struts2的一些简单效果的更多相关文章

  1. 自己实现的简单MVC框架(类似Struts2+Spring)

    一.框架简介 本框架是一个类似于Struts2+Spring的框架,目的在于个人钻研和技术分享,将流行技术框架Struts2.Spring中使用到的主要技术以较为简化的方式实现出来,给大家一个更直观的 ...

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

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

  3. struts2和servlet同时用(访问servlet时被struts2过滤器拦截问题的解决)

    在同一个项目中间,如果既用到servlet有用了struts2的框架,运行项目时可能无法正常使用servlet,原因是在配置struts2的核心控制器时<url-pattern>/*< ...

  4. 【WEB小工具】BaseServlet—一个Servlet处理多个请求

    package cn.itcast.test.web.servlet; import java.io.IOException; import java.io.PrintWriter; import j ...

  5. Duilib实现类似电脑管家扫描目录效果

    实现原理: 1.后台开线程遍历目录,遍历出一个文件路径在界面上更新显示(通过发消息通知主界面) 2.需要扩展一下Duilib控件,在此我扩展了CLabelUI,重写了PaintText函数 扩展控件的 ...

  6. WPF如何实现类似iPhone界面切换的效果(转载)

    WPF如何实现类似iPhone界面切换的效果 (version .1) 转自:http://blog.csdn.net/fallincloud/article/details/6968764 在论坛上 ...

  7. Adobe Edge Animate –地球自转动画的实现,类似flash遮罩层的效果

    Adobe Edge Animate –地球自转动画的实现,类似flash遮罩层的效果 版权声明: 本文版权属于 北京联友天下科技发展有限公司. 转载的时候请注明版权和原文地址. 目前Edge的功能尚 ...

  8. PHP实现类似题库抽题效果

    PHP实现类似题库抽题效果 大家好,我顾某人又回来了,最近学了一点PHP,然后就想写个简单小例子试试,于是就写了一个类似于从题库抽题的东西,大概就是先输入需要抽题的数量,然后从数据库中随机抽取题目. ...

  9. 利用反射优化Servlet抽象出父类BaseServlet

    在编写servlet的时候发现每个servlet里面的doPost方法都如: protected void doPost(HttpServletRequest request, HttpServlet ...

随机推荐

  1. mybatis技术文章

    http://legend2011.blog.51cto.com/3018495/1600478

  2. JQuery EasyUI DataGrid动态合并单元格

    /**        * EasyUI DataGrid根据字段动态合并单元格        * @param fldList 要合并table的id        * @param fldList ...

  3. iPhone X

    iPhone X前置深度摄像头带来了Animoji和face ID,同时也将3D Face Tracking的接口开放给了开发者.有幸去Cupertino苹果总部参加了iPhone X的封闭开发,本文 ...

  4. Mode Standby

    Modern Standby 1.Connected Standby和 Connected Standby是Windows 8全新的电源管理系统,即当系统进入休眠状态时,应用程式虽处於暂停(suspe ...

  5. 如何在cmd中启动redis

    首先要指定redis安装的目录,然后输入: redis-server.exe redis.windows.conf 如果成功,则会出现redis的标志,失败的话 请转帖到: http://www.cn ...

  6. 一步一步实现一个简单的OS(简单的让boot载入setup)

    这次直接写用boot载入setup模块. 文件系统就先不弄了,以后再说, 咱先整个转简单的载入器. 我把软盘引导改成硬盘了,由于硬盘的读扇区函数简单一些. 这里没有做硬盘的mbr区,我认为在如今我的这 ...

  7. eclipse-jee版配置tomcat

    Eclipse作为一款优秀的java开发开源IDE,集成了许多优秀的开发控件.下来我就如何安装eclipse及插件进行说明: 一.JDK安装   JDK是作为整个java的核心,包括运行环境,编译工具 ...

  8. Delphi下如何使程序在Win7/Vista上用管理员权限运行(转)

    Delphi程序必须在资源里面嵌入MANIFEST信息 一 首先编辑一个文件,内容如下: <?xml version="1.0" encoding="UTF-8&q ...

  9. StringBuilder的append、StringBuffer的append和String str = "a"+"b"的区别?

    大家都知道String+String会开销额外的系统资源,粗略的原因是String是不可变类,每一步操作都会返回新的String变量,占用空间及时间. 其实我的理解不是这样的,我们来看看String+ ...

  10. 部署mongodb中需要注意的调参

    部署mongodb的生产服务器,给出如下相关建议: 使用虚拟化环境: 系统配置 1)推荐RAID配置 RAID(Redundant Array of Independent Disk,独立磁盘冗余阵列 ...