public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求 String username = request.getParameter("username"); String password = request.getParameter("password"); boolean rememberMe = "on".equals(request.getParameter("remember-me")); try { if (username != null && !username.trim().isEmpty() && password != null && !password.trim().isEmpty()) { String hashedPasswd = hashPassword(password); if (authenticate(username, hashedPasswd)) { HttpSession session = request.getSession(); session.setAttribute("username", username); response.sendRedirect("mean1"); } else { response.sendRedirect("/login.html?error=1"); } } else { response.sendRedirect("/login.html?error=2"); } } catch (SQLException e) { throw new ServletException("Cannot connect to DB", e); } catch (NoSuchAlgorithmException e) { throw new ServletException("Cannot encrypt password", e); }如何修改代码,将其变为根据两个不同用户进入两个不同的页面代码
时间: 2024-01-16 16:03:10 浏览: 135
可以在 `authenticate()` 方法中增加根据用户名判断跳转到不同页面的逻辑,具体代码如下:
```java
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理POST请求
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean rememberMe = "on".equals(request.getParameter("remember-me"));
try {
if (username != null && !username.trim().isEmpty() &&
password != null && !password.trim().isEmpty()) {
String hashedPasswd = hashPassword(password);
if (authenticate(username, hashedPasswd)) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
if (username.equals("user1")) {
response.sendRedirect("page1.jsp");
} else if (username.equals("user2")) {
response.sendRedirect("page2.jsp");
} else {
response.sendRedirect("default.jsp");
}
} else {
response.sendRedirect("/login.html?error=1");
}
} else {
response.sendRedirect("/login.html?error=2");
}
} catch (SQLException e) {
throw new ServletException("Cannot connect to DB", e);
} catch (NoSuchAlgorithmException e) {
throw new ServletException("Cannot encrypt password", e);
}
}
}
```
在上述代码中,我们增加了根据用户名判断跳转到不同页面的逻辑。当用户名为 `user1` 时,跳转到 `page1.jsp` 页面;当用户名为 `user2` 时,跳转到 `page2.jsp` 页面;否则跳转到 `default.jsp` 页面。您需要根据实际需求修改页面名称和判断逻辑。
阅读全文