登入頁面login.jsp
Code:
- <body>
- <%
- String[] userInfo={"",""};
- Cookie[] cookie=request.getCookies();
- if(cookie!=null) {
- for(int i=0; i<cookie.length; i++) {
- if(cookie[i].getName().equals("loginInfo")) {
- userInfo = cookie[i].getValue().split("#");
- }
- }
- }
- %>
-
- <form action="servlet/Login" method="post">
- 帳號:<input type="text" class="txt" name="username" value=<%=userInfo[0] %>/><br/>
- 密碼:<input type="password" class="txt" name="password" value=<%=userInfo[1] %>/><br/>
- 允許寫入Cookie:<input type="radio" name="agree" value="yes" checked/>是<input type="radio" name="agree" value="no"/>否<br/>
- <input type="submit" value="提交" /> <input type="reset" value="取消" />
- </form>
- </body>
Servlet中doPost方法
如果doPost方法中均使用response.sendRedirect(request.getContextPath()+"/login.jsp");在result.jsp中始終得到的是null
就是說session裡面的值始終得不到,在網上找了很久也沒找到解決的方法。
Code:
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- response.setContentType("text/html");
- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- String userName = request.getParameter("username");
- String password = request.getParameter("password");
- String agree = request.getParameter("agree");
- User u = new User();
- u.setName(userName);
- u.setPassword(password);
- HttpSession session = null;
- if(u.canPass()) {
- if(agree.equals("yes")) {
- Cookie myCookie = new Cookie("loginInfo", userName+"#"+password);
- myCookie.setMaxAge(60*60*24*7);
- response.addCookie(myCookie);
- session = request.getSession();
- session.setAttribute("user",(User)u);
- }
- ServletContext sc = getServletContext();
- RequestDispatcher rd = null;
- rd = sc.getRequestDispatcher("/result.jsp"); //定向的頁面
- rd.forward(request, response);
- } else {
- response.sendRedirect(request.getContextPath()+"/login.jsp");
- return;
- }
- }
結果頁面
Code:
- <body>
- <%
- User u = (User)session.getAttribute("user");
- System.out.println(u);
- if(u==null) {
- u = new User();
- u.setName("");
- u.setPassword("");
- }
- %>
- 當前登入使用者的資訊:帳號(<%=u.getName() %>)密碼(<%=u.getPassword() %>)
- </body>