Cookie与Session【持续更新】

post与get提交乱码方式解决方式,cookie(显示用户上次访问时间)

解决post提交乱码方式:

//post
request.setCharacterEncoding("utf-8");//只对post提交有效。
String username = request.getParameter("username");
System.out.println(username);

解决get提交乱码方式:

String username = request.getParameter("username");
username = new String (username.getBytes("iso-8859-1"),"utf-8");
System.out.println(username);

Cookie:cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。
当用户使用浏览器再去访问服务器中的
web资源时,就会带着各自的数据区,这样,web资源处理的就是各自的数据了。

Session:session是服务器端技术,利用session技术,服务器在运行时可以为每一个用户的浏览器创建其
独享的session对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把
各自的数据放在session中,当用户再次去访问服务器中的其他web资源时,其他web资源再从用户各自的session
取出数据为用户服务。


利用cookie技术实现:显示用户上次访问时间

package cn.lsh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//利用cookie技术实现:显示用户上次访问时间
public class CookieDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//指定以utf-8编码
		response.setCharacterEncoding("utf-8");
		//指定浏览器以UTF-8码表打开
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = response.getWriter();
		//获取所有的cookie
		Cookie [] cookie = request.getCookies();
		String curr = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//判断cookie是否为空,不为空则使用增强for循坏比例
		if(cookie != null){
			for(Cookie cs : cookie){
				if("lastaccesstime".equals(cs.getName())){
					curr = cs.getValue();
					break;
				}else{
					curr = sdf.format(date);
				}
			}
		}else{
			curr = sdf.format(date);
		}
		//给用户会送最新的访问时间
		pw.write("上一次访问的时间是:"+curr);
		Cookie cookies = new Cookie("lastaccesstime",sdf.format(date));
		cookies.setMaxAge(1*60);
		response.addCookie(cookies);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	
}

访问输出结果为:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值