一个Servlet中可以有多个请求处理方法,可以利用反射实现
package cn.day19.web.servlet;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet {
public void service(HttpServletRequest request,HttpServletResponse response){
String methodName = request.getParameter("method");
if(methodName ==null || methodName.trim().isEmpty()){
throw new RuntimeException("无method参数!");
}
//通过反射调用名称
Class c = this.getClass();//得到当前的class对象
Method method = null;
try {
method =c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException("方法不存在");
}
//调用method
try {
String result = (String)method.invoke(this, request,response);
if(result == null || result.trim().isEmpty()) return;
if(result.contains(":")){
int index = result.indexOf(":");//获取冒号的位置
String s = result.substring(0,index);//截取出前缀,表示操作
String path = result.substring(index+1);//截取后缀,表示路径
if(s.equalsIgnoreCase("r")){ //如果前缀是r,那么重定向
response.sendRedirect(request.getContextPath()+path);
}else if(s.equalsIgnoreCase("f")){//f:转发
request.getRequestDispatcher(path).forward(request, response);
}else {
throw new RuntimeException("没有指定的"+s+"操作");
}
}else{//没有冒号,默认为转发
request.getRequestDispatcher(result).forward(request, response);
}
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
}