在最开始的时候我们写一个servlet(LoginServlet)对应一个请求(Login.jsp),这样的话就会产生很多的servlet,使其以后维护变得麻烦,所以我们可以考虑将同一类型(Login.jsp,Regist.jsp等等都看作一个用户类)的请求用一个servlet(UserServlet)处理,然后将把关于User的请求封装为一个个的方法(login(),regist()),例如:
public class UserServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response){
String methodName = request.getParameter("method"); //jsp中获取的 <form action="client/UserServlet?method=login" method="post">
if ("login".equals(methodName )) { //被判断的数据放在后面,这样可以避免发生空指针异常
login(request, response);
}else if ("regist".equals(methodName )) {
regist(request, response); //调用regist方法
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response){
doGet(request, response);
}
protected void login(HttpServletRequest request, HttpServletResponse response) {...} //登录
protected void regist(HttpServletRequest request, HttpServletResponse response) {...} //注册
........
}
写完之后发现,如果有删除用户(delete)的操作,就还需要再增加else if 语句,这样的又有太多的if--else判断语句,因此可以采用反射的技术,动态的获取当前方法的对象调用要执行的方法,所以继续优化:
public class UserServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response){
String methodName = request.getParameter("method"); //jsp中获取的 <form action="client/UserServlet?method=login" method="post">
try {
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.setAccessible(true);
method.invoke(this, request, response); //因为login、regist方法的有两个参数,分别是request和response
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response){
doGet(request, response);
}
protected void login(HttpServletRequest request, HttpServletResponse response) {...} //登录
protected void regist(HttpServletRequest request, HttpServletResponse response) {...} //注册
........
}
完毕之后,发现如果有BookServlet,这样的其它一些servlet还需要进行此类的判断,所以可以考虑把上面的doGet(),doPost()提取出来封装成为一个公共的类(假如是BaseServlet),这样的话,有类似操作的servlet都可以继承这个类BaseServlet,因此上面的就可以写成:
PS:BaseServlet只是一个功能类,不会被访问,所以创建为一个普通的class就行,然后extends HttpServlet。
public class BaseServlet extends HttpServlet {
//上面的doGet()和doPost()方法
}
public class UserServlet extends BaseServlet{
protected void login(HttpServletRequest request, HttpServletResponse response) {...} //登录
protected void regist(HttpServletRequest request, HttpServletResponse response) {...} //注册
........
}
//如果有BookServlet 等等servlet直接继承BaseServlet即可
-------------------------------------------------------------------------------------------------------------------------------------------------------------