mysql存cookie_cookie保存用户名及密码

登陆页中,用户输入用户名密码,点击提交,后台对照mysq数据库中,看是否有对应的用户名,以及密码是否正确。如果正确

则将用户名密码分两份Cookie保存。页面跳转到登陆成功页。

用户再次访问登陆页时,先取出Cookie,判断是否存在用户名密码的Cookie,如果有,则将值保存在变量或者request中。接着

将Cookie的变量或request赋值给用户名密码文本输入框。到此完成了保存用户名密码的功能。

test_6.11_login.jsp

//定义数据库驱动程序

public static final String DBDRIVER="org.gjt.mm.mysql.Driver";

public static final String DBURL="jdbc:mysql://localhost:3307/yunmobile";

public static final String DBUSER="rood";

public static final String DBPASS="234567";

%>

Connection conn=null;

PreparedStatement pstmt=null;

ResultSet rs=null;

%>

String username_ = null;

Cookie c[]=request.getCookies();

if(c!=null)

{

for(int x=0;x

{

if(c[x].getName().equals("username"))

{

//在cookie值保存时如果编码了,取cookie时就需要进行解码。

//将cookie值取出来后,赋值给变量,用以之后的显示

username_ = URLDecoder.decode(c[x].getValue(),"UTF-8");

}

else if(c[x].getName().equals("password"))

{

//将cookie值取出来后,赋值给request,用以之后的显示

request.setAttribute("password",c[x].getValue());

}

}

}

%>

用户名:

密码:

//若用户名密码中有中文,虽然提交给当前页,底下的设置编码方式也是必须的

request.setCharacterEncoding("UTF-8");

String name=request.getParameter("username");

String password=request.getParameter("password");

if(!(name==null||name.equals("")||password==null || password.equals("")))

{

try{

Class.forName(DBDRIVER);

conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);

String sql="SELECT * FROM member WHERE name=? AND password=?";

pstmt=conn.prepareStatement(sql);

pstmt.setString(1,name);

pstmt.setString(2,password);

rs=pstmt.executeQuery();

if(rs.next())

{

if(rs.getString(3).equals(name) && rs.getString(2).equals(password))

{

//如果用户名密码和数据库中值匹配,则跳转到登陆成功页

response.setHeader("refresh","3;URL=test_6.11_page.jsp");

//登陆成功页面通过session传递用户名,用于登陆成功页面显示用户名

session.setAttribute("username",name);

//cookie保存时,如果用户名或密码有汉字或者其他特殊字符需要进行编码

Cookie c1=new Cookie("username",URLEncoder.encode(name,"UTF-8"));

Cookie c2=new Cookie("password",password);

c1.setMaxAge(76000);

c2.setMaxAge(76000);

response.addCookie(c1);

response.addCookie(c2);

}

}

else

{

out.println("

用户名或密码错误哦哦哦!

");

}

}catch(Exception e){

out.println(e);

}

}

%>

test_6.11_page.jsp

if(!(session.getAttribute("username")==null))

{

%>

欢迎光临本系统

}

else

{

%>

请先进行系统的登陆

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值