1.希望在一个Servlet中可以有多个请求处理方法
domain:User
dao:UserDao
servlet:UserServlet
service:UserService
2.客户端发送请求时,必须多给出一个参数,用来说明要调用的方法。
请求处理方法的签名必须与service相同,即返回值和参数,以及申明异常都相同
3.客户端必须传递名为method的参数!
package cn.jxk.web.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class BaseServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1.获取参数,用来识别用户想请求的方法
* 2.然后判断是哪一个方法,是哪一个我们就调用哪一个
* */
String methodName=req.getParameter("method");
if(methodName==null||methodName.trim().isEmpty()){
throw new RuntimeException("您没有传递method参数,无法确定你想要调用的方法");
}
/*
* 得到方法名称,是否可以用反射来调用方法?
* 1.得到方法名,通过方法名再得到method类的一个对象
* *需要得到Class,然后调用它的方法进行查询!得到Method
* *我们要查询的是当前类的方法,所以我们需要得到当前类的Class
* */
Class c=this.getClass();//得到当前类的class对象
Method method=null;
try {
method=c.getMethod(methodName,
HttpServletRequest.class,HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法:"+methodName+",它不存在!");
}
/*
* 调用method表示的方法
* */
try {
method.invoke(this, req,resp);
} catch (Exception e) {
System.out.println("您调用的方法"+methodName+",它内部跑出了异常!");
throw new RuntimeException(e);
}
}
}
package cn.jxk.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 在这里给出多个请求处理方法
* 请求处理方法:除了名称以外,都与service方法相同
* */
public class AServlet extends BaseServlet {
public void addUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("addUser()....");
}
public void editUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("editUser()...");
}
public void deleteUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("deleteUser()...");
}
public void loadUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("deleteUser()...");
}
public void findAll(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("findAll()...");
}
}