JavaWeb -cookie&session&application

Cookie【key-value】(不是内置对象):

1. Cookie 是由服务端生成的,在发送给客户端保存

2. 作用:提高访问效率,但安全性较差

  *除了自己设定对象还有个name为JSESSIONID的

3. 常用方法

  Cookie(String name,String value)  构造方法需new

  String getName()          得到name

  String getValue()          得到value

  setMaxAge(int time)        最大有效期(秒)

4. 代码示例(实现记住用户名功能)

登陆界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
    <%!
    String uname;
    %>
    <%
        //用作保留用户名
    Cookie[] cookies=request.getCookies();
    for(Cookie cookie : cookies){
        if(cookie.getName().equals("uname")){
            uname=cookie.getValue();
        }
    }
    %>
    <form action="check.jsp" method="post">
        用户名:<input type="text" name="uname" value="<%=(uname==null?"":uname)%>"><br/>
        密码:   <input type="password" name="upwd"/><br/>
        <input type="submit" value="登陆"><br/>
    </form>
</body>
</html>        

将登入的cookie返回

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>

    <%
            request.setCharacterEncoding("utf-8");
            String name=request.getParameter("uname");
            String pwd=request.getParameter("upwd");
            //将用户名 加入cookies中
            Cookie cookie=new Cookie("uname",name);
            //设置该cookie最大有效期10s
            cookie.setMaxAge(10);
            response.addCookie(cookie);
            
            //实现了一次跳转,目的将cookie转回客户端
            //response.sendRedirect("A.jsp");
        %>
</body>
</html>

 session(内置对象)

1. session机制:

一、客户端第一次请求服务端时:

  服务端会产生一个session对象(用于保存该客户的信息)

  并且每个session对象都有一个唯一的sessionID(用于区分其他session)

  服务端又会产生一个cookie,并且 将该cookie发送给客户端 因此客户端的cookie中JSESSIONID会与服务端的sessionid一一对应

 二、客户端之后请求服务端时:

  服务端会先用客户端的cookie中的JSESSIONID去服务端的session中匹配sessionid 如果匹配成功则无需登录

2. session要点:

1. 存储在服务端

2. 在同一个用户请求时 共享

3. session常用方法:

getId();    //获取sessionid

isNew();   //判断用户是否为新用户(第一次登陆)

invalidate();  //使session失效  (退出登陆、注销)

setAttribute();

getAttribute();

setMaxInactiveInterval(int time)  //设置最大有效 非活动时间(登陆京东 一段时间不动 则会要求重新登陆)

getMaxInactiveInterval()    //得到最大有效 非活动时间

cookie&session的区别

补充:

html中的超链接:<a href="跳转的jsp">name</a>

跳转的jsp中:session.invalidate();  实现注销-删除session所有信息

application(内置对象)

方法:

1. application.getContextPath()  获取当前项目的虚拟路径

2. application.getRealPath()    获取当前项目的绝对路径

猜你喜欢

转载自www.cnblogs.com/cc123nice/p/10693075.html
今日推荐