简体   繁体   中英

Cannot access filter Servlet's session attribute from another normal Http Servlet

I have a problem here:

After i use a filter servlet to set session attribute, i try to retrieve the session attribute in another normal http servlet, but it looks getAttribute('system.userinfo') cannot retrieve anything. what's wrong with this? Thanks!

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");


        }
}

Both servlets are in same web application.

Seems like you are not getting the session in the servlet that you think got created in the Filter. In the filter you are using req.getSession() which is always creating a new session. In the servlet you are giving request.getSession(false), the container is supposed to return null if no session exists or return an existing session. Which servlet container are you using? If you are using an IDE, can you put a debug point and compare the session IDs to confirm they are the same? Also, is your UserDTO serializable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM