我在jsp页面中为会话对象设置了一个属性,如下所示:
String remoteAddr = request.getRemoteAddr();
session.setAttribute("remoteAddr",remoteAddr);
然后,我试图在servlet过滤器中检索该会话属性:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = httpServletRequest.getSession(false).getAttribute("remoteAddr");
}
但是我在这里获得了会话对象的空值。在这里获取相同会话对象的正确方法是什么?
答案 0 :(得分:1)
方法HttpServletRequest.html#getSession(boolean)可能会返回null
如果create为false且请求没有有效的HttpSession,则此方法返回null。
在请求资源之前或请求资源之后,可以调用Filter,具体取决于您执行chain.doFilter(request, response);
在您的情况下,似乎您在执行jsp之前查询会话,即执行以下操作:
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = (String) httpServletRequest.getSession(false).getAttribute("remoteAddr");
// pass the request along the filter chain
chain.doFilter(request, response);
将其更改为
// pass the request along the filter chain
chain.doFilter(request, response);
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String remoteIP = (String) httpServletRequest.getSession(false).getAttribute("remoteAddr");
会让它工作,但我怀疑这是你打算做的,因为你可能想要检查远程IP并决定是允许访问还是拒绝它到所请求的资源,在这种情况下你可能想要做这样的事情:
String remoteIP= request.getRemoteAddr();
if(remoteIP.matches("some pattern")) {
((HttpServletResponse)response).setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
// pass the request along the filter chain
chain.doFilter(request, response);
}