一个请求就要编写一个 Servlet 类,这样代码太臃肿。下面通过反射的技术将其改进,可以做到一个请求对应一个方法。
<br/>
步骤如下:
**1. 继承HttpServlet**
```java
public class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String methodName = request.getParameter("method");
Method method;
try {
method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.setAccessible(true);
String url = (String) method.invoke(this, request, response);
if (StringUtils.isEmpty(url)) {
return;
}
if (url.startsWith("redirect:")) {
int index = url.indexOf(":");
url = url.substring(index + 1);
response.sendRedirect("WEB-INF/views/" + url + ".jsp");
} else {
request.getRequestDispatcher("WEB-INF/views/" + url + ".jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
**2. 所有的Servlet继承BaseServlet**
```java
@WebServlet("/login")
public class LoginServlet extends BaseServlet {
public String login(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("zhangsan".equals(username) && "123456".equals(password)) {
return "loginSuccess";
} else {
return "loginFail";
}
}
}
```
**3. 访问login方法:http://localhost:8080/web/login?method=login&username=zhangsan&password=123456**
`method`指定的就是 LoginServlet 类的`login`方法名。