javaweb中使⽤cookie记住⽤户的账号和密码毕业设计中需要⽤到记住账号密码的功能,⽹上搜到了⼀个解决⽅案,⾃⼰稍加改造就是下⾯的⽅法。
⾸先是登录的页⾯,当⽤户勾选记住密码,传递给controller(我⽤的SSM框架),后台设置cookie的值,然后下次登录的时候就不⽤再次输⼊账号和密码了。login.jsp的代码:
<%@page import="org.apachemons.lang.StringUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="public/nocache.jsp" %>
<%@include file="public/header.jsp" %>
<!-- 引⼊相关的js -->
<script type="text/javascript" src="${tPath}/js/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<style>
body{
margin:0px;
padding:0px;
}
.wrapper{
width:100%;height:100%;position:fixed;
}
.content{
width:100%;
height:100%;
position:relative;
text-align:center;
}
.login{
width:1050px;
height:450px;
position:absolute;
top:50%;
left:50%;
margin-top:-225px;
margin-left:-525px;
}
</style>
<script type="text/javascript">
window.history.forward();
}
</script>
<%@include file="public/headertop.jsp" %>
<!-- 进⼊资源⽂件 -->
<body>
<%-- 读取cookie --%>
<%
String name = "";
String password = "";
try{
Cookie[] cookies = Cookies();
if(cookies!=null){
for(int i = 0;i<cookies.length;i++){
if(cookies[i].getName().equals("cookie_user")){
String values = cookies[i].getValue();
// 如果value字段不为空
if(StringUtils.isNotBlank(values)){
String[] elements = values.split("-");
// 获取账户名或者密码
if(StringUtils.isNotBlank(elements[0])){
name = elements[0];
}
if(StringUtils.isNotBlank(elements[1])){
password = elements[1];
}
}
}
}
}
}catch(Exception e){
}
%>
<div class="wrapper" >
<div class="content">
<div class="login">
<!-- 主要的内容部分开始 -->
<div class="easyui-layout" fit="true" border="false">
<div region="west" border="false">
<div class="easyui-layout" fit="true" border="false">
<div region="west" border="false" >
</div>
<div region="center" border="false">
<p >
<span >汽车维修管理系统</span><br/>
<span>Vehicle Maintenance Management System</span>
</p>
</div>
</div>
</div>
<div region="center" border="false" >
<div class="easyui-layout" fit="true" border="false">
<div region="north" border="false">
</div>
<div region="west" border="false">
<img src="${tPath}/img/split.png" />
</div>
<div region="center" border="false">
<div class="easyui-panel" title="⽤户登录" iconCls="icon-user"
>
<form id="ff" method="post">
<div>
<input id="account" class="easyui-textbox" name="accountnumber"
data-options="iconCls:'icon-man',prompt:'请输⼊⽤户名'" value="<%=name %>"
>
<a id="dd" href="#" title="⽤户的账号不能为空" class="easyui-tooltip"></a>
</div>
<div >
<input id="passwords" class="easyui-textbox" name="passwords" type="password"
data-options="iconCls:'icon-lock',prompt:'请输⼊密码'" value="<%=password %>"
>
</div>
<div >
<span ><input id="flag" name="flag" type="checkbox" value="1" checked="checked" />记住账号</span>
</div>
<div ></div>
<div >
<p>
<a href="#" id="submitbtn" class="easyui-linkbutton" iconCls="icon-accept">登录</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-arrow_undo">取消</a>            </p>
</div>
</form>
</div>
</div>
<div region="east" border="false">
</div>
<div region="south" border="false">
</div>
</div>
</div>
</div>
<!-- 主要的内容部分结束 -->
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
console.log("[汽车维修管理系统\n codeby:pengchan\n email:dntchenpeng@163 \n csdn:blog.csdn/w3chhhhhh/]");    // 提交表单
$("#submitbtn").click(function(){
// 判断是否为空
if($("#account").val()==""){
$.messager.alert('登录消息提⽰','⽤户的账号不能为空','info');
return;
}
if($("#passwords").val()==""){
$.messager.alert('登录消息提⽰','⽤户的密码不能为空','info');
return;
}
$("#ff").submit();
});
$('#ff').form({
url:"${tPath}/users/login.html",
success:function(data){
data = JSON.parse(data);
try{
if(data.isError){
$.messager.alert('登录消息提⽰',Msg,'info');
}else{
//$.messager.alert("登录消息提⽰","登录成功!",'info');
// 如果成功,就跳转到主页⾯
// 这⾥先判断是否有历史请求,如果有就再次访问之前的页⾯
var hisurl = '${hisURL}';
if(hisurl!=null&&hisurl.length>0){
window.location.href="${tPath}"+hisurl;
}else{
window.location.href="${tPath}/index/main.html";
}
}
}catch(e){
$.messager.alert("登录消息提⽰",'服务器返回异常,请稍后重试!','info');
}
},
error:function(error){
$("#ff").form("clear");
}
});
});
</script>
</body>
</html>
后台处理的java部分代码:
package ller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apachemons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import ity.Account;
import com.javaweb.service.impl.ServiceFactory;
import com.javaweb.utils.BaseController;
import com.javaweb.views.LoginBean;
/**
* ⽤户信息控制器
* @author cp
*
*/
@Controller
@Scope("prototype")
@RequestMapping("/users")
public class UserInfoController extends BaseController{
private static final Logger logger = Logger(UserInfoController.class);
@Autowired
private ServiceFactory serviceFactory;
/**
* 登录系统
* @param request 请求
* @param model  model
* @param account 账户信息
* @return
*/
@RequestMapping("/login")
@ResponseBody
public String login(HttpServletRequest request,HttpServletResponse response,Model model,Account account){
logger.info("⽤户尝试登录:"+JSONString(account));
if(account==null){
return responseFail("提交的参数为空!");
}else{
if(StringUtils.Accountnumber())){
return responseFail("⽤户的账号为空");
}
if(StringUtils.Passwords())){
return responseFail("⽤户的密码为空");
}
LoginBean loginBean = null;
loginBean = UserValidateService().userislawable(account);
if(loginBean==null){
return responseFail("⽤户名或者密码输⼊不正确");
}else{// 如果成功
// 把loginbean放到session中
// 放到cookie中
String flag = Parameter("flag");
// 如果需要记住账户就存储账号和密码
if(flag!=null&&flag.equals("1")){
Cookie cookie = new Cookie("cookie_user",Accountnumber()+"-"+Passwords());      cookie.setMaxAge(60*60*24*3);// 保存
response.addCookie(cookie);
logger.info("存储⽤户的cookie:"+Accountnumber()+"-"+Passwords());
}else{// 如果没有要求记住账户密码,就保存账户
Cookie cookie = new Cookie("cookie_user", Accountnumber());
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
logger.info("存储⽤户的cookie:"+Accountnumber());
}
// 跳转到主页
logger.info("⽤户:"+Accountnumber()+"成功进⼊系统");
return responseSuccess(loginBean, "登录成功");
}
}
}
/**
* 退出系统登录
* @param request  请求
springboot和过滤器* @param model  模型
* @param accountnum 账户号
* @return
*/
@RequestMapping("/{accountnum}/logout.html")
public String logout(HttpServletRequest request,Model model,@PathVariable("accountnum") String accountnum){  logger.info("⽤户"+accountnum+",退出系统登录...");
// 设置session为空
// 页⾯跳转
return "login";
}
}
运⾏效果:
输⼊账号密码登录后:
退出后重新登录:
以上所述是⼩编给⼤家介绍的java web中使⽤cookie记住⽤户的账号和密码,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!