这个问题的解决比较简单,只需要两步即可;


在失败的情况下直接返回登录页面

实现免登录的思想是:
保存信息:在登录成功时,并且查看前端做的标记–>复选框中是否有数据,在有数据的情况下:创建两个cookie对象,一个存储用户名,一个存储密码;并且设置存储时长和设置cookie的path属性(发送cookie的路径条件),之后就将cookie响应给浏览器;
欢迎页设置:这里有两种情况,一种是保存有cookie信息,直接免登录,另一种就是需要进行登录,因此需要对欢迎页从新设置


@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取cookie
// 这个Cookie[]数组可能是null,如果不是null,数组的长度一定是大于0的。
Cookie[] cookies = request.getCookies();
String username = null;
String password = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if("username".equals(name)){
username = cookie.getValue();
}else if("password".equals(name)){
password = cookie.getValue();
}
}
}
// 要在这里使用username和password变量
if(username != null && password != null){
// 验证用户名和密码是否正确
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean success = false;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user where username = ? and password = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
rs = ps.executeQuery();
if (rs.next()) {
// 登录成功
success = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
if (success) {
// 获取session
HttpSession session = request.getSession();
session.setAttribute("username", username);
// 正确,表示登录成功
response.sendRedirect(request.getContextPath() + "/dept/list");
}else{
// 错误,表示登录失败
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}else{
// 跳转到登录页面
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
}