1.创建BaseServlet (重写父类的service方法)
package com.learning.web.servlet; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class BaseServlet extends HttpServlet { @Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//利用反射得到要执行的方法
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) res; String method=request.getParameter("method");
try {
//得到名称为method的方法
Method m = this.getClass().getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
m.invoke(this, request,response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} } }
2.总控制的Servlet继承BaseServlet
package com.learning.web.servlet; import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.learning.domain.User;
import com.learning.exception.UserException;
import com.learning.service.UserService; @WebServlet("/user")
public class UserServlet extends BaseServlet {
private static final long serialVersionUID = 1L; //登录
protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService userService=new UserService(); try {
User user=userService.findUserByUsernameAndPassword(username,password);
if (user!=null) { request.getSession().setAttribute("user", user);
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
request.setAttribute("login_msg", "用户名或密码错误"); } catch (UserException e) {
e.printStackTrace();
request.setAttribute("login_msg", e.getMessage());
}
request.getRequestDispatcher("/login.jsp").forward(request, response); } //注销
protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate();
response.sendRedirect(request.getContextPath()+"/index.jsp");
} }