cookie和session
- Cookie,有时也用其复数形式Cookies,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。
- Session具体到Web中的Session指的就是用户在浏览某个网站时,从进入网站到关闭这个网站所经过的这段时间,也就是用户浏览这个网站所花费的时间。因此从上述的定义中我们可以看到,Session实际上是一个特定的时间概念。
在javaee中使用cookie的几个方法
- 因为保证线程的统一,即request和response的高度统一,便于操作,使用的方法都会进行传入request,由于本人用的是tomcat7,tomcat7以上版本对中文cookie的限制,所以要进行编码和解码。把字用utf-8编完存cookie,然后在取的时候再用utf-8解码。
- 加入cookie
//加入cookie
public void addCookie(HttpServletResponse resp,String key,String value) throws UnsupportedEncodingException {
//因为tomcat7以上对中文cookie的限制,所以要编码
if (value==null){
return;
}
Cookie cookie = new Cookie(key, URLEncoder.encode(value, "utf-8"));
cookie.setPath("/");
cookie.setMaxAge(30*24*3600);
resp.addCookie(cookie);
}
//一次性cookie
public void addCookieone(HttpServletResponse resp,String key,String value) throws UnsupportedEncodingException {
//因为tomcat7以上对中文cookie的限制,所以要编码
if (value==null){
return;
}
Cookie cookie = new Cookie(key, URLEncoder.encode(value, "utf-8"));
cookie.setPath("/");
cookie.setMaxAge(-1);
resp.addCookie(cookie);
}
- 删除cookie
public void deleteCookie(HttpServletResponse resp,String key){
Cookie cookie =new Cookie(key,null);
cookie.setPath("/");
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
- 查找cookie
//查找cookie
public static String selectCookie(HttpServletRequest request, String key) throws UnsupportedEncodingException {
Map<String, Cookie> mapcookie = readCookie(request);
if (mapcookie.containsKey(key)){
Cookie cookie=mapcookie.get(key);
//这里是解码
String str = URLDecoder.decode(cookie.getValue(), "utf-8");
return str;
}else return null;
}
- 读取cookie 即查看所有的cookie
//读取cookie
public static Map<String, Cookie> readCookie(HttpServletRequest request) throws UnsupportedEncodingException {
Cookie[] cookies = request.getCookies();
Map<String, Cookie> mapcookie=new HashMap<String, Cookie>();
if (cookies!=null){
for (Cookie cookie:cookies){
mapcookie.put(cookie.getName(),cookie);
}
}
return mapcookie;
}
session的使用
- HttpSession session = req.getSession();//创建session对象
- 这个时候的post的方法内容则为
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println(req.getParameter("username"));//req.getParameter();这个方法就是获取jsp页面form表单传送过来的数据。
//System.out.println(req.getParameter("password"));//这里运行并在页面输入后提交 则会在控制台看到输入内容。
HttpSession session = req.getSession();//创建session对象
String username= (String) req.getParameter("username");
session.setAttribute("username",username);
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
- 在跳转的页面中加入代码
<%=request.getSession().getAttribute("username")%>
- 运行查看 可以看到输入的用户名出现在页面中
- 这样的话只要是在一次浏览器访问中,即可使用该代码进行用户名的使用,不管页面之间是否是相关联的。一次存入,多次使用(在不同的地点)。
下一节讲述信息如何写入数据库(注册),和数据库的信息查找并操作(登录)