javaweb之创建一个baseservlet,让其他的servlet的继承它,然后在继承的servlet中只写方法就可以了,解决一个servlet写一个功能的问题

package mine.servlet;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 创建这个BaseServlet的目的:
 * 1.以前是一个功能就写一个servlet,这样的写法过于繁琐,现在想是否能有一种方法,可以只写一个servlet实现多个功能呢
 * 2.一般servlet处理完都会有一个转发的功能,所以,我把转发的功能也放在这里,以简化代码
 * 步骤:
 * 0.首先这段代码要写在service方法中,其他servlet继承这个方法以后,只写方法就可以了,不用再写doget和dopost了
 * 1.首先前端必须把要调用的方法作为参数发过来
 * 2.然后判断这个参数是否为空
 * 3.接下来,用反射的知识获取类,然后就可以根据发过来的方法名字来调用响应的方法
 * 4.最后执行方法invoke后还会返回一个参数,这个参数作为转发的目的地,然后我就可以在其他的servlet中,返回一个参数就可以实现转发
 * 5.如果我想要重定向的话,只需要写一个重定向的语句,然后返回一个null给这个baseservlet即可
 */
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
		//设置编码方式,防止中文乱码
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		//获取方法的名称
		String methodName = req.getParameter("method");
		//判断方法是否为空,或者去掉空格后为空
		if(methodName == null || methodName.trim().isEmpty()){
			throw new RuntimeException("传的方法为空了");
		}
		//获取继承baseservlet的类
		Class<? extends BaseServlet> clazz = this.getClass();
		Method method = null;
		try {
			//获取方法的对象
			method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("错误");
		} 
		
		try {
			//调用invoke方法执行方法,并返回一个值作为转发的目的地
			String result = (String) method.invoke(this, req,resp);
			if(result != null && !result.trim().isEmpty()){
				req.getRequestDispatcher(result).forward(req, resp);
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/86551525