从筛选器中的ServletRequest获取会话时出现java问题
我的目标是用过滤器截取ServletResponse,并在它显示在网页上之前向它添加一些自定义html。我还想进行一些计算,并将结果添加到会话变量HashMap中,以便在后续调用中访问该变量
我不知道如何从doFilter方法中的ServletRequest获取会话。这是我的密码:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
CountingServletResponse counter = null;
try {
HttpServletResponse httpResp = (HttpServletResponse) response;
counter = new CountingServletResponse(httpResp);
counter.addHeader("UniqueId", String.valueOf(counter.getUniqueId()));
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpSession session = httpReq.getSession(); //this throws error
//I want to add session variable here
chain.doFilter(request, response);
counter.flushBuffer(); // Push the last bits containing HTML comment.
} catch (Throwable t) {
t.printStackTrace();
}
}
带有getSession的行抛出
java.lang.IllegalStateException: Cannot create a session after the response has been committed
如果我做了getSession(false),那么它将通过该行,但是session==null,并且我不能添加任何会话变量。 想法
# 1 楼答案
getSession()
尝试获取当前会话,如果该会话不存在,则尝试创建一个新会话getSession(false)
也尝试获取会话,但如果会话不存在,则返回null(顺便说一句,这意味着getSession() === getSession(true)
)。这就是为什么使用getSession()
时会出现异常(因为无法创建异常),而使用getSession(false)
时会出现null
,因为没有会话,也没有尝试创建新会话由于您已经在向客户端发送响应,因此无法向其添加新的http头,此时为时已晚。不知道你在这里的环境是什么,但你需要尽快完成必要的工作