import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public abstract class BaseServlet extends HttpServlet {//基类
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {//service完成方法的分发
//通过基类对所用请求进行格式化
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//处理前端代码乱码
String mark = req.getParameter("mark");//规定之后所有请求的参数的参数名,?mark=doselect(方法名)
if (mark==null||mark==""){
throw new RuntimeException("此方法名不存在");//为什么使用运行时异常,使用运行时异常不需要抛出异常
}
Class cla=this.getClass(); //谁调用我?我代表谁
//第一个参数是方法名,第二个参数是方法所需要参数的值的class文件
try {
Method method = cla.getMethod(mark, HttpServletRequest.class, HttpServletResponse.class);//动态获取参数,和请求对象和响应对象
method.invoke(this,req,resp);//子类继承这个基类,里面的方法必须是public修饰的方法,如果私有则必须暴力反射解决
//子类的方法都必须有两个参数,循序分别是HttpServletRequest,HttpServletResponse
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
BaseServlet的编写使用反射完成servlet后端方法的分发
最新推荐文章于 2021-02-15 14:36:09 发布