抽取通用BaseServlet

之前编写的servlet的问题:
1.doget每次请求都会执行--- 重写service
2.用了大量 if else if 判断执行的是那个方法让方法执行
Method method = this.getClass().getMethod(mt, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
3.每个方法执行的结果无非就是请求转发或者重定向或者打印数据
让所有的方法都返回一个字符串
若最后的结果需要请求转发,就把转发的路径给返回
若最后的结果不需要请求转发,就返回一个null

String path=method.invoke(this, request,response);
if(path != null){
request.getx(path).forward(...)
}
4.所有servlet的service中的代码都一样
向上继续抽取
编写一个BaseServlet,将之前service方法中的代码复制过来即可,
然所有的servlet都继承baseservlet即可

5.统一的错误页面

/**
 * 通用的servlet
 */
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//1.获取方法名称
			String mName = request.getParameter("method");
			
			//1.1判断 参数是否为空  若为空,执行默认的方法
			if(mName == null || mName.trim().length()==0){
				mName = "index";
			}
			
			//2.获取方法对象
			Method method = this.getClass().getMethod(mName, HttpServletRequest.class,HttpServletResponse.class);
			
			//3.让方法执行,接受返回值
			String path=(String) method.invoke(this, request,response);
			
			//4.判断返回值是否为空 若不为空统一处理请求转发
			if(path != null){
				request.getRequestDispatcher(path).forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	
	public String index(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("亲,不要捣乱");
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/yujq1993/article/details/80321933