天天看點

HttpSession 第二例|學習筆記

開發者學堂課程【JSP 快速入門:HttpSession 第二例】學習筆記,與課程緊密聯系,讓使用者快速學習知識。

課程位址:

https://developer.aliyun.com/learning/course/33/detail/713

HttpSession 第二例

内容介紹:

一. 分析儲存使用者登入資訊的方法

二. 代碼建立

一.分析儲存使用者登入資訊的方法

(1)建立登入表單 login.jsp

登陸表單包括使用者名和密碼,表單絕大部分指向 LoginServlet 。 LoginServlet 用來擷取表單資料并且校驗使用者名和密碼是否正确,且錯誤時可以顯示錯誤資訊,正确時,儲存使用者資訊到 session 中,重定向到 succ1.jsp ;若錯誤,儲存錯誤資訊到 request 域,轉發回到 login.jsp 。判斷使用者名與密碼是否正确可自己設定。

(2)成功頁面1 succ1.jsp (登入後的使用者可以通路)

從session中擷取使用者資訊,如果存在,說明已經登入顯示使用者名;如果不存在,向 request 域儲存錯誤資訊,轉發到login.jsp 。

(3)成功頁面2 succ2.jsp (登入後的使用者可以通路)

與 succ1.jsp 一樣。從session中擷取使用者資訊,如果存在,說明已經登入顯示使用者名;如果不存在,向 request 域儲存錯誤資訊,轉發到login.jsp 。

二.代碼建立

(1)創立 session 2檔案夾

(2)在 session2 中依次創立 login.jsp , succ1.jsp , succ2.jsp 及 LoginServlet 。

(3)login.jsp 提供登入表單并顯示錯誤資訊

代碼為:

登入

<%

String uname = ””;

Cookie[] cs = request.getCookie();

if(cs != null){

for(Cookie c :cs){

if(”uname”.eqals(c.getName())){

uname = c.getValue();

}

}

}

String message = ””;

String msg = (Sring)request.getAttribute(”msg”);

if(msg !=null){

message = msg;

}

%>

<%=message %><>

action=”/day11-3/LoginServlet”method=”post”>

使用者名:”/>

密碼:

(4)LoginServlet 擷取表單資料,校驗使用者名和密碼是否正确并将使用者名儲存到cookie 中,發送給用戶端浏覽器

LoginServlet 設定為 doPost() ,字首及無用注釋删掉。擷取表單資料包括進行中文資料和擷取。校驗時,若正确,儲存使用者資訊到 session 中并重新定向到 succ1.jsp ;若失敗,儲存錯誤資訊到 request 域中并轉發至 login.jsp 。

request.setCharacterEncoding(”utf-8”);

String username = request.getParameter(”username”);

String password = request.getParameter(”password”);

if(!”itcast”.equalsIgnoreCase(username))

Cookie cookie = new Cookie(”uname”,username);

cookie.setMaxAge(60*60*24);

response.addCookie(cookie);

HttpSession Session = request.getSession();

sesseion.setAttribute(”username”,username);

response.sendRedirect(”/day11-3/session2/succ1.jsp”)

else{

request.setAttribute(”msg”,”使用者名或密碼錯誤!”);

RequestDispatcher qr = request.getRequestDispatcher(”/session2/login.jsp”);

qr.forward(request,response);

}

(4)succ1.jsp

<%

String username =(String)session.getAttribute(”username”);

if(username==null){

request.setAttribute(”msg”,”您還沒有登入,不要冒充上司!”);

requestgetRequestDispatcher(”/session2/login.jsp”).forward(request,response);

return;

}

%>

歡迎歡迎,熱烈歡迎,歡迎<%=username%>上司指導工作!

(5)succ2.jsp(同succ1.jsp)