Java Web之BaseServlet的抽取

BaseServlet的抽取其实就是将每个Servelt封装成为每一个模块功能到到一个类中.此类继承BaseServlet类,BaseServlet继承HttpServlet,再根据Servlet的生命周期,会执行service方法,所以在BaseServlet中重写service方法,再在service方法中通过反射去执行到每个具体的Servlet类中的每个模块功能,简化代码。

//这个抽象类,BaseServlet类不需要在web.xml中进行配置
public abstract class BaseServlet extends HttpServlet {

    

   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成方法分发
        //1.获取请求路径
        String uri = req.getRequestURI();
        //2.获取方法名称
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
            //1.1判断 参数是否为空  若为空,执行默认的方法
			    if(methodName == null || methodName .trim().length()==0){
				methodName = "execute";
			    }

        try {
            // 2、通过反射获得当前运行类中指定方法,形式参数
            Method executeMethod = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 3、反射执行方法
            executeMethod.invoke(this, request, response);
           
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("请求的方法[" + methodName + "]不存在");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("服务器异常", e);
        }
    }

    /**
     * 此方法用于复写,方便子类编程,默认执行方法
     */
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值