最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
jsp cookie+session实现简易自动登录
时间:2025-07-06 16:00:02 编辑:袖梨 来源:一聚教程网
本文实例为大家分享了jsp cookie+session实现简易自动登录的具体代码,供大家参考,具体内容如下
关闭浏览器只会使存储在客户端浏览器内存中的session cookie失效,不会使服务器端的session对象失效。如果设置了过期时间,浏览器就会把cookie保存到硬盘上,关闭后再次打开浏览器,这些cookie依然有效直到超过设定的过期时间。
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"> <head><title>登录</title></head><body><form action="sucess.jsp" method="post"> 用户名:<input name="username" /><br/><%--<input type="checkbox" name="time" />记住用户名 --%><input type="submit" name="submit" id="submit" value="登录"/> </form> <%//读取session值 String val= (String)session.getAttribute("name"); //如果session不存在 if(val==null){val ="不存在"; } out.print("当前""+val+""用户可自动登录"); %></body></html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>主不在乎</title></head><body><% //获取username String name = request.getParameter("username"); //判断用户名是否存在 if(name != null && !name.trim().equals("")){//String[] time = request.getParameterValues("time");//设置session值,(login页面可读取) session.setAttribute("name", name);//设置Cookie Cookie Cookie = new Cookie("name",name);Cookie.setMaxAge(30*24*3600); //设置cookie有效期为30天response.addCookie(Cookie); //在客户端保存Cookieout.println("welcome: " + name+"欢迎登录"); }else{ response.sendRedirect("main.jsp"); } %><a href="login.jsp" >relogin</a></body></html>
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="ISO-8859-1"><title>主不在乎</title></head><body><%String name=(String)session.getAttribute("username");//获取cookieCookie[] cookies = request.getCookies();//cookie存在 if(cookies != null && cookies.length > 0){ for(Cookie cookie:cookies){//获取cookie的名字String cookieName = cookie.getName();//判断是否与name相等if(cookieName.equals("name")){//获取cookie的值String value = cookie.getValue();name = value;}} out.println("welcome again: " + name+"欢迎登录"); //************************* // 另一种写法String v=null; for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("name")){ v=cookies[i].getValue(); } } if(v!=null){ out.println(" Hello World "+v); }}//************************* else { response.sendRedirect("login.jsp"); }%><a href="login.jsp" >relogin</a></body></html>
运行login.jsp
相关文章
- 大侠立志传霸王别姬任务完成指南 07-08
- 《QQ》退出电脑登录方法 07-08
- PS如何把照片制作成时空隧道效果? 07-08
- 斗罗大陆猎魂世界强力武魂推荐 07-08
- Dreamweaver网页制作怎么使用css样式嵌套? 07-08
- Pi币2025年预测!Pi币常见问题解答 07-08