当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Filter is not retrieving request.getAttribute()

问题描述:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

try {

String logged = (String) ((HttpServletRequest) request).getAttribute("loginstatus");

if(logged != null) {

out.print("ok");

} else {

out.print("not ok");

}

Why is the value of logged always null?

网友答案:

A filter is by default the very first thing which get executed on a HTTP request. The request attribtues are usually managed by server side code. Who/what should have set the request attribute before this filter does its job?

Aren't you confusing how HTTP requests/responses work? A request get finished/garbaged, including all attributes, when the associated response is finished. Every subsequent request is a brand new one which doesn't contain at all the same attributes as the previous one.

Don't you actually want to use the session scope? Do the following on login:

request.getSession().setAttribute("user", user);

And then the following in authentication filter:

if (((HttpServletRequest).getSession().getAttribute("user") != null) {
    chain.doFilter(request, response); // Continue.
} else {
    ((HttpServletResponse) response).sendRedirect("login"); // Redirect to login.
}

See also:

  • How does a servlet environment work? ServletContext, HttpSession, HttpServletRequest/Response.
  • Servlet filters wiki page
分享给朋友:
您可能感兴趣的文章:
随机阅读: