Session基本應用

heinika1476775901521發表於2017-12-14

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");
    }
}
複製程式碼

相關文章