关于cookie的一点见识及一个保存密码实例

       Cookie是一种发送到客户浏览器的文本串句柄,并保存在客户机硬盘上,可以用来在某个Web站点会话之间持久地保持数据。Request和Response对象都有一组Cookie。Request.cookie集合是一系列Cookie,从客户端与HTTP Request一起发送到Web服务器。反过来,如果你希望把Cookie发送到客户机,就可以使用Response.Cookies.


1、Expires属性

该属性可以赋一个日期,过了这个日期Cookie就不能再被使用了。通过给Expires属性赋一个过期的日期,就可以删除Cookie。如:

<%Response.cookies("passtime").Expires=DateAdd("m", 1, NOW)%> 
这样设置Cookie在一个月后过期。 
2、Domain属性
  该属性定义Cookie要传送的唯一域。如:Cookie只传送给Microsoft的人,则可以使用以下代码。
<%Response.Cookies("domain").Domain="http://www.microsoft.com/"%> 

经常的cookie只能在一个应用中共享,即一个cookie只能由创建它的应用获得。 

1.在同一应用服务器内共享的方法:设置cookie.setPath("/");

   设本机tomcat/webapp下面有两个应用:caswebapp_b

                                                                                    
1).原来在cas下面设置的cookie,在webapp_b下面获取不到, path默认是产生cookie的应用的路径。


2).若在cas下面设置cookie的时候,增加一条: cookie.setPath("/");或者cookie.setPath("/webapp_b/"); 就可以在webapp_b下面获取       到cas设置的cookie了。


3).此处的参数,是相对于应用服务器存放应用的文件夹的根目录而言的(比如tomcat下面的webapp),因此cookie.setPath("/");之后,可以在webapp文件夹下的所有应用共享cookie,而cookie.setPath("/webapp_b/"),是指cas应用设置的cookie只能在webapp_b应用下的获得,即便是产生这个cookie的cas应用也不可以。


4).设置cookie.setPath("/webapp_b/jsp/")的时候,只有在webapp_b/jsp下面可以获得cookie,在webapp_b下面但是在jsp文件夹外的都不能获得cookie。



5).设置cookie.setPath("/webapp_b/"),是指在webapp_b下面才可以使用cookie,这样就不可以在产生cookie的应用cas下面获取cookie了。


6).有多条cookie.setPath("XXX");语句的时候,起作用的以最后一条为准。

2.跨域共享cookie的方法:设置cookie.setDomain(".jszx.com");

A机所在的域:home.langchao.com,A有应用cas
B机所在的域:jszx.com,B有应用webapp_b


1)在cas下面设置cookie的时候,增加cookie.setDomain(".jszx.com");,这样在webapp_b下面就可以取到cookie。


2)这个参数必须以“.”开始。


3)输入url访问webapp_b的时候,必须输入域名才能解析。比如说在A机器输入:http://lc-bsp.jszx.com:8080/webapp_b,可以获取cas在客户端设置的cookie,而B机器访问本机的应用,输入:http://localhost:8080/webapp_b则不可以获得cookie。


4)设置了cookie.setDomain(".jszx.com");,还可以在默认的home.langchao.com下面共享。


3.使用cookie实现保存用户和密码的功能实例

使用struts2框架:

User.java:

package com.neusoft.struts.lianxi0409;

public class User {
	private String username;
	private String password;
	private String jilu;
	
	public String getJilu() {
		return jilu;
	}
	public void setJilu(String jilu) {
		this.jilu = jilu;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	

}

ActionAttribute.java:

package com.neusoft.struts.lianxi0409;

import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class ActionAttribute extends ActionSupport implements SessionAware{
	private Map<String, Object> session;
	private User user;
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public void setSession(Map<String, Object> session) {
		// TODO Auto-generated method stub
		this.session = session;
	}
	public String execute() {
		session.put("user", user.getUsername());
		if (session != null) {
			if (user != null && user.getUsername().equals("qqq") && user.getPassword().equals("qqq")) {
				Cookie usernamecookie = new Cookie("username", user.getUsername());
				Cookie passwordcookie = new Cookie("password", user.getPassword());
				// 设置保存周期
				usernamecookie.setMaxAge(60 * 5);
				passwordcookie.setMaxAge(60 * 5);
				// 设置cookie共享范围
				usernamecookie.setPath("/struts2_actionattribute_lianxi0409");
				passwordcookie.setPath("/struts2_actionattribute_lianxi0409");
				ServletActionContext.getResponse().addCookie(usernamecookie);
				ServletActionContext.getResponse().addCookie(passwordcookie);

				return SUCCESS;
			} else {
				return "login";
			}
		} else {
			return "login";
		}

	}

}


web.xml:

  <?xml version="1.0" encoding="UTF-8" ?> 
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <filter>
  <filter-name>struts2</filter-name> 
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 
  </filter>
- <filter-mapping>
  <filter-name>struts2</filter-name> 
  <url-pattern>/*</url-pattern> 
  </filter-mapping>
- <welcome-file-list>
  <welcome-file>login.jsp</welcome-file> 
  </welcome-file-list>
  </web-app>

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
     <constant name="struts.devMode" value="true" />
       <constant name="struts.i18n.encoding" value="utf-8" />
   <package name="attribute" namespace="/attribute" extends="struts-default">
       <action name="attribute" class="com.neusoft.struts.lianxi0409.ActionAttribute">
            <result name="success">/index.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>
</struts>

login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
	
<%
		String username = "";
		String password = "";
		response.setContentType("text/html;charset=gbk");
		Cookie[] cookie = request.getCookies();
		if (cookie != null) {
			for (int i = 0; i < cookie.length; i++) {
				if (cookie[i].getName().equals("username")) {
					username = cookie[i].getValue();
				} else if (cookie[i].getName().equals("password")) {
					password = cookie[i].getValue();
					break;
				}
			}
		}
	%>
    <form action="attribute/attribute" method="post">
    <table border="1">
    	<tr>
    	<td>用户名</td>
    	<td><input type="text" name="user.username" value="<%=username%>"></td>
    	</tr>
    	<tr>
    	<td>密码</td>
    	<td><input type="password" name="user.password" value="<%=password%>"></td>
    	</tr>
    	<tr>
    	<td colspan="2">
    		<input type="submit" value="提交">
    		<input type="reset" value="重设">
    	</td>
    	</tr>
    </table>
    </form>
  </body>
</html>

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body> 
   <s:property value="#session.user"/>你好
   <s:debug></s:debug>
  </body>
</html>

用户第一次登陆后,第二次在保存有效时间内就不用再输入用户名和密码了!





  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
localstoragecookie都是用来在浏览器端保存数据的技术。但是它们在保存密码方面有一些区别。 首先是localstorage,它是HTML5新增的Web Storage API之一。可以将数据以键值对的形式存储在浏览器中,并且该数据不会随着网页的关闭而消失。因此,localstorage可以用来保存长期登录的密码,以便下次用户打开网页时可以自动填充密码。然而,localstorage存储的数据是明文形式,只要有人能够访问到用户的设备,就可以轻松获取到存储在localstorage中的密码信息。 而cookie是浏览器常用的一种技术,用于在浏览器和服务器之间传递数据。在保存密码方面,cookie可以设置一个标记来表示用户的登录状态,使得用户可以在一段时间内免登录。然而,cookie也存在一些安全问题。首先,cookie中的数据是明文存储的,可以被他人窃取,因此不能将密码明文存储在cookie中,而是应该将密码进行哈希散列等操作后再存储。其次,cookie有过期时间,如果不合理设置,可能会导致用户的登录状态过长,增加了安全风险。 综上所述,无论是使用localstorage还是cookie保存密码,都存在一定的安全风险。为了提升密码的安全性,应该对密码进行哈希散列等操作后再进行存储,并定期更新密码或设置密码的有效期限,以保护用户的账户安全。此外,还应该使用其他更安全的身份验证方式,如双因素认证等,来加强用户账户的安全性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heroleader

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值