您的位置:首页 > 其它

用cookie实现自动登录

2017-07-13 18:23 676 查看
今天学习了cookie小功能,这个主要应用在登录时,在你第一次登陆后,下次就可以自动登录等;

首先是登录页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%//获取用户名和密码cookie,判断cookie是否为空,为空的情况就是第一次登录,跳到登录页面,不为空就直接跳转到登陆后的页面。
String name=null;
String password=null;
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if(cookie.getName().equals("username")){
name=cookie.getValue();
}
if(cookie.getName().equals("pwd")){
password=cookie.getValue();
}
}
if(name!=null&&password!=null){
response.sendRedirect("LoginServlet?username="+name+"&pwd="+password);
}
}

%>
<h1>欢迎来到动物园</h1>
<form action="<%=request.getContextPath()%>/LoginServlet" method="get">
<p>请输入口令:<input type="text" name="username"></p>
<p>请输入密码:<input type="password" name="pwd"></p>
<p><input type="checkbox" name="box" value="ck">自动登录</p>
<p><input type="submit" value="欢迎进入"></p>
</form>
</body>
</html>


下面是servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
接收请求参数的值
String username=request.getParameter("username");
String password=request.getParameter("pwd");
if(username.equals("yyy")&&password.equals("123")) {
//如果没有选中自动登录,则要输入账号登录,否则就会执行cookie,实现自动登录
if(request.getParameter("box")==null) {
request.getRequestDispatcher("SearchAllServlet").forward(request, response);
}else {

Cookie name=new Cookie("username", username);
Cookie pwd=new Cookie("pwd", password);
response.addCookie(name);
response.addCookie(pwd);
name.setMaxAge(60*60);
pwd.setMaxAge(60*60);
request.getRequestDispatcher("SearchAllServlet").forward(request, response);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: