![](/img/trans.png)
[英]What is the mechanism by which a session attribute passes from a filter to a servlet?
[英]Cannot access filter Servlet's session attribute from another normal Http Servlet
我在這里有一個問題:
在使用過濾器servlet設置會話屬性之后,我嘗試在另一個普通的http servlet中檢索會話屬性,但是它看起來getAttribute('system.userinfo')無法檢索任何內容。 這怎么了 謝謝!
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
HttpSession session = httpReq.getSession();
httpReq.setCharacterEncoding("UTF-8");
UserDTO dto = new UserDTO();
session.setAttribute("system.userinfo", dto);
chain.doFilter(request, response);
}
public class FileUpload extends HttpServlet {
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// cannot get anything here
UserDTO userinfo = (UserDTO)request.getSession(false).getAttribute("system.userinfo");
}
}
兩個servlet都在同一個Web應用程序中。
似乎您沒有在您認為是在過濾器中創建的servlet中獲得會話。 在過濾器中,您使用的是req.getSession(),它始終在創建一個新會話。 在servlet中,您要提供request.getSession(false),如果不存在會話,則容器應返回null或返回現有會話。 您正在使用哪個servlet容器? 如果使用的是IDE,是否可以放置調試點並比較會話ID以確認它們相同? 另外,您的UserDTO是否可序列化?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.