Session基本应用

135 阅读2分钟

Session简介

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

创建或获取Session,并以Cookie的方式回写JSESSIONID。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //Session的另外一种获取方式,这种方式只获取不创建。比如查看购物车的操作,如果用户没有购物的话,没有必要创建一个Session。
        //        request.getSession(false);
        String sessionid = session.getId();
        Cookie cookie = new Cookie("JSESSIONID",sessionid);
        cookie.setPath("/");
        //设置cookie的保存时长为30分钟,因为Session一般就在服务器中保存30分钟,多了也没用。。。
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);
        session.setAttribute("name","洗衣机");
    }

获取Session中的内容

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession();
    String product = (String) session.getAttribute("name");
    out.write("您购买的是:"+product);
}

把JESSIONID写到浏览器的url中

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    request.getSession();

    //添加SessionId,因为cookies的SessionId可能会被用户禁用
    String url1 = response.encodeURL("/SessionDemo1");
    String url2 = response.encodeURL("/SessionDemo2");

    out.print("<a href="+url1+">购买</a><br/>");
    out.print("<a href="+url2+">结账</a>");
}

Session 登录实例

首页: index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Heinika Web</title>
  </head>
  <body>
    欢迎你:${user.userName}<br>
    <a href="login.html">登录 </a>
    <a href="/LogoutDemo">退出登录</a>
    <br/>
    this my first web app
  </body>
</html>

登录页: login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="/LoginDemo">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="登录">
</form>

</body>
</html>

登录Servlet:

@WebServlet(name = "LoginDemo")
public class LoginDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        List<User> users = DB.getAll();
        for (User user:users){
            if(user.getUserName().equals(username)&&user.getPassword().equals(password)){
                request.getSession().setAttribute("user",user);
                response.sendRedirect("/index.jsp");
            }
        }

        out.write("用户名或密码不对!");
    }
}

//用于模拟数据库
class DB{
    public static List list = new ArrayList();
    static {
        list.add(new User("aaa","111"));
        list.add(new User("bbb","222"));
        list.add(new User("ccc","333"));
    }

    public static List getAll(){
        return list;
    }
}

退出登录:

@WebServlet(name = "LogoutDemo")
public class LogoutDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if(session == null){
            response.sendRedirect("/index.jsp");
            return;
        }

        session.removeAttribute("user");
        response.sendRedirect("/index.jsp");
    }
}