重写httpservlet,增强功能

package cn.book.utils;
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;
/**
 * 使用反射动态的调用子类的方法
 */
public abstract class BaseServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method==null || method.trim().equals("")){
            method="execute";
        }
        try{
            Method m = this.getClass().getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            m.invoke(this,req,resp);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    public abstract void execute(HttpServletRequest req,HttpServletResponse resp) throws Exception;
}



你可能感兴趣的:(重写httpservlet,增强功能)