BaseServlet类反射调用Servlet的方法实现

Servlet里doGet过多的判断method语句,会让代码略显冗余,此时可以用一个BaseServlet类反射调用Servlet里的方法,从而可以省略去Servlet里doGet和doPost语句;
代码实现如下:

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;
//编写BaseServlet继承HttpServlet
//重写其doGet和doPost方法
public class BaseServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数中的method
        String method = req.getParameter("method");
        if(method!=null){
            try {
                //通过反射调用对应的方法
                //通过“this”获取class对象
                Class clazz = this.getClass();
                //通过class对象和方法名获取方法对象
                Method m = clazz.getMethod(method, HttpServletRequest.class,HttpServletResponse.class);
                //通过反射机制调用方法
                m.invoke(this, req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}   

注意:
1.那么Servlet继承Baseservlet类即可:如
public class UserServlet extends BaseServlet{

}
2.继承Baseservlet的Servlet里的doGet和doPost注释掉或者删除即可。

猜你喜欢

转载自blog.csdn.net/sinat_43094886/article/details/82696836
今日推荐