症狀:
剛才在做一個利用session的attribute保存用戶的id的實驗,login.jsp輸入用戶id,提交給LoginServlet去數據庫驗證,然后LoginServlet根據驗證情況跳轉到相應的頁面。
但是發現,LoginServlet中使用了HttpServletRequest.getSession().setAttribute("uid", user_id)卻無法成功保存已登錄的用戶的id,比如說:在welcome.jsp會根據session中
保存的uid attribute顯示一些用戶特定的歡迎信息,但是welcome.jsp中使用session.getAttribute("uid")卻始終返回的是null
在此期間沒有關閉瀏覽器、更沒有重新啟動服務器,經過簡單的debug,session.isNew()返回的是false,但是session.getAttribute("uid")卻始終返回null
分析:
分析過程見http://www.cnblogs.com/qrlozte/p/3515881.html
原因是login.jsp中提交到LoginServlet的action寫法有誤,不應該使用絕對路徑,但是為什么使用絕對路徑提交form會造成session的attribute無法正常保存我暫時還不清楚
錯誤的action路徑:<form action="http://localhost:8080/site/xxx/LoginServlet">
解決方案:
action改為相對路徑即可(server.xml配置的path="/site", docBase="X:\...\WebCotent")
<form action="/site/xxx/LoginServlet">
為了具體化我遇到的問題,我將簡化后的代碼列舉如下:
/site/xxx/login.jsp
(注意這里的action使用的是絕對路徑,你會發現,提交之后,uid並沒有保存到session中(你可以在不關閉瀏覽器的情況下刷新login.jsp,你可以看到request.getSession().getAttribute("uid")返回null),而且session也沒有被銷毀(你可以用session.isNew()驗證),怎么解決?action改為"/site/xxx/LoginServlet"或者"LoginServlet"即可)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:8080/site/xxx/LoginServlet" method="post"> attr:<input type="text" name="uid"><br> <input type="submit" value="提交"><input type="reset" value="重置"> </form> <%=request.getSession().getAttribute("uid") %> </body> </html>
/site/xxx/yyy/welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%=request.getSession().getAttribute("uid") %> </body> </html>
/site/xxx/LoginServlet
public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().setAttribute("uid", req.getParameter("uid")); req.getRequestDispatcher("yyy/welcome.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
web.xml
<servlet> <servlet-name>loginServlet</servlet-name> <servlet-class> org.foo.servletdemo.LoginServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>loginServlet</servlet-name> <url-pattern>/xxx/LoginServlet</url-pattern> </servlet-mapping>