Session基本應(yīng)用

Session簡介

Session是服務(wù)端技術(shù),利用這個(gè)技術(shù)。利用這個(gè)技術(shù),服務(wù)器在運(yùn)行時(shí)可以為每一個(gè)用戶的瀏覽器創(chuàng)建一個(gè)獨(dú)享的session對象,由于Session為用戶瀏覽器獨(dú)享,所以用戶在訪問瀏覽器資源時(shí),可以把各自的數(shù)據(jù)放在各自的session中,當(dāng)用戶再去訪問服務(wù)器的其他web資源時(shí),其他web資源再從用戶各自的session中取出數(shù)據(jù)為用戶服務(wù)。

創(chuàng)建或獲取Session,并以Cookie的方式回寫JSESSIONID。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //Session的另外一種獲取方式,這種方式只獲取不創(chuàng)建。比如查看購物車的操作,如果用戶沒有購物的話,沒有必要?jiǎng)?chuàng)建一個(gè)Session。
        //        request.getSession(false);
        String sessionid = session.getId();
        Cookie cookie = new Cookie("JSESSIONID",sessionid);
        cookie.setPath("/");
        //設(shè)置cookie的保存時(shí)長為30分鐘,因?yàn)镾ession一般就在服務(wù)器中保存30分鐘,多了也沒用。。。
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);
        session.setAttribute("name","洗衣機(jī)");
    }

獲取Session中的內(nèi)容

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,因?yàn)閏ookies的SessionId可能會被用戶禁用
    String url1 = response.encodeURL("/SessionDemo1");
    String url2 = response.encodeURL("/SessionDemo2");

    out.print("<a href="+url1+">購買</a><br/>");
    out.print("<a href="+url2+">結(jié)賬</a>");
}

Session 登錄實(shí)例

首頁:
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("用戶名或密碼不對!");
    }
}

//用于模擬數(shù)據(jù)庫
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");
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)自 :http://blog.csdn.net/taoff/articles/1921009.aspx 一、術(shù)語...
    stone_yao閱讀 6,266評論 0 31
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 1. cookie 1.1 什么是cookie cookie 是存儲于訪問者的計(jì)算機(jī)中的變量。每當(dāng)同一臺計(jì)算機(jī)通過...
    cbw100閱讀 4,093評論 0 13
  • 一、概念(載錄于:http://www.cnblogs.com/EricaMIN1987_IT/p/3837436...
    yuantao123434閱讀 8,440評論 6 152
  • 周六 貝 八 一起去看牙 想去cascada 先在好運(yùn)來吃了個(gè)飯 結(jié)果車打不著了火了 八很不開心 車也不給力了好像...
    Vanesa閱讀 122評論 0 0