《Oracle Java EE编程自学和面试指南》08-04:使用Cookie实现简化登录
程序开发
2023-09-18 23:06:37

深入了解IT/互联网行业及岗位,请参阅通用IT/互联网岗位招聘计划(最新全岗版)。
深入了解职业晋升及学习路线,请参阅最优职业晋升路线和课程学习指南(最新全栈版)。
内容导航:
前言
–
简化登录的思路
用户登录时,可以选择长时间内不需要登录
访问登录页面index.jsp时,获取所有Cookie对象,检查是否存在已经保存的用户名和密码,如果存在,则直接提交到Servlet进行登录处理。如果不存在,则显示index.jsp页面
Servlet中获取用户选择不需要登录的时间,把登录信息保存到cookie中,设置有效时间,写到客户端
简化登录步骤1:修改index.jsp
在上一章例子基础上进行修改。
修改index.jsp文件,加入脚本,获取cookie,判断是否存在已经保存的用户名和密码,如果存在,则直接到LoginServlet登录验证,否则就显示index.jsp
<% String username=null;
String password=null;
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if(cookie.getName().equals("username")){
username=cookie.getValue();
}
if(cookie.getName().equals("password")){
password=cookie.getValue();
}
}
}
if(username!=null&&password!=null){
request.getRequestDispatcher("LoginServlet?username="+username+"&pwd="+password).forward(request, response);
}%>
简化登录步骤2:修改LoginServlet
修改LoginServlet,把登录成功的信息作为Cookie保存到客户端,并设置有效时间。
//获得JSP页面的时间信息
String timelength=request.getParameter("timelength");
int days=0;
if(timelength!=null){
days=Integer.parseInt(timelength);
}
if(days!=0){
Cookie usernamecookie=new Cookie("username",username);
Cookie passwordcookie=new Cookie("password",pwd);
usernamecookie.setMaxAge(days*24*3600);
passwordcookie.setMaxAge(days*24*3600);
response.addCookie(usernamecookie);
response.addCookie(passwordcookie);
}
运行测试
再次访问index.jsp,可以直接登录成功;
修改时间,为当前时间的十天以后,再次访问index.jsp,可见cookie失效,需要重新登录。
运行效果
好好学习,天天向上!继续下一章…👏👏👏👏👏👏

感谢您阅读,如果对作者其它文章也很感兴趣,请扫码关注!🚀🚀🚀🚀🚀🚀
标签:
上一篇:
css中两列布局,三列布局实现方法
下一篇:
相关文章
-
无相关信息
