美文网首页
cookie 和session 的区别

cookie 和session 的区别

作者: 蘋果_283e | 来源:发表于2017-04-12 18:39 被阅读0次

1、cookie数据存放在客户的浏览器上,session数据放在服务器上。

2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗,考虑到安全应当使用session。

3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能

考虑到减轻服务器性能方面,应当使用COOKIE。

4、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

1、设置Cookie

Cookie cc = new Cookie(“name", “value");

cc.setMaxAge(60 * 1); //参数“秒”过期时间

response.addCookie(cc);

2、取Cookie

<%

Cookie []cc=request.getCookies();//获取Cookie

String user="",pwd="";

if(cc!=null){

for(int i=0;i<cc.length;i++){

if(cc[i].getName().equals("user")){

user=cc[i].getValue();//取过来cookie用户名为user 则设置值

}

if(cc[i].getName().equals("pwd")){

pwd=cc[i].getValue();//取过来cookie用户名为user 则设置值

}

}

}

%>

开发步骤

1、servlet--->发送Cookie

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

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

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

String check=request.getParameter("logincheck");

System.out.println("值:"+check+" "+user+" "+pwd);

if(check==null){

if(user.equals("qq")&&pwd.equals("123")){

response.sendRedirect("index.jsp");

}else{

response.sendRedirect("login.jsp");

}

}else{

Cookie c1=new Cookie("user", user);//设置Cookid

c1.setMaxAge(10*24*60*60);//存储10天

response.addCookie(c1);//响应给客户端,将可以通过request.getCookies()收

Cookie c2=new Cookie("pwd", pwd);//设置Cookid

c2.setMaxAge(10*24*60*60);//存储10天

response.addCookie(c2);//响应给客户端

if(user.equals("qq")&&pwd.equals("123")){

response.sendRedirect("index.jsp");

}else{

response.sendRedirect("login.jsp");

}

}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request,response);

}

}

2、jsp-->接收Cookie

<%

Cookie []cc=request.getCookies();//获取Cookie

String user="",pwd="";

if(cc!=null){

for(int i=0;i<cc.length;i++){

if(cc[i].getName().equals("user")){

user=cc[i].getValue();//取过来cookie用户名为user 则设置值

}

if(cc[i].getName().equals("pwd")){

pwd=cc[i].getValue();//取过来cookie用户名为user 则设置值

}//(或者将user pwd的值放入session.setattribute里,在下面的表单中直接用)

}

}

%>

<form action="LoginServlet" name="kk" method="post">

姓名:<input type="text" name="user" value="<%=user%>">

密码:<input type="text" name="pwd" value="<%=pwd%>">

<input type="checkbox" name="ck">十天免登录

<input type="submit" value="登录">

</form>

String ck = request.getParameter("ck");// 被选中的状态是on 没有被选中的状态下是null

if ("on".equals(ck)) {

// 构造Cookie对象

// 添加到Cookie中

Cookie c = new Cookie("users", uname + "-" + password);

// 设置过期时间

c.setMaxAge(600);// 存储,秒

response.addCookie(c);

相关文章

网友评论

      本文标题:cookie 和session 的区别

      本文链接:https://www.haomeiwen.com/subject/iyamattx.html