Servlet中通用的service方法

来源:互联网 发布:java nanotime 编辑:程序博客网 时间:2024/05/18 23:56
package com.itliuwei.store.utils;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.lang.reflect.Method;/** * 以后创建Servlet的时候不需要继承HttpServlet了,而是继承这个类(BaseServlet) * 这样每个Servlet都不用写service方法了 * 只需要写那些真正用于处理业务的方法即可,默认调用父类的service方法 * 而父类service方法中获取请求要执行的方法名然后通过反射调用并执行方法 */public class BaseServlet extends HttpServlet {    @Override    protected void service(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {               try {            String runMethodName = req.getParameter("method");            Class clazz = this.getClass();            Method method = clazz.getMethod(runMethodName, HttpServletRequest.class,                    HttpServletResponse.class);                        if (method != null) {                String url = (String) method.invoke(this, req, resp);                if (url != null) {                    req.getRequestDispatcher(url).forward(req, resp);                }            }        } catch (Exception e) {            e.printStackTrace();        }    }}