先说结论:
response.addCookie(cookie); 写在 filterChain.doFilter(request, response); 之前导致的
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { log.info("Filter1 begin"); Cookie cookie = new Cookie("testKey", "testVal"); cookie.setDomain(request.getRemoteAddr()); cookie.setPath("/"); cookie.setMaxAge(2 * 60 * 60); cookie.setHttpOnly(true); // 写在doFilter前,Cookie“正常”返回客户端 response.addCookie(cookie); filterChain.doFilter(request, response); // 写在doFilter后,Cookie“无法”返回客户端 response.addCookie(cookie); log.info("Filter1 end"); }response.addCookie(cookie);在执行时,会判断response是否committed,如果为true,则不再写入Cookie。
在filterChain.doFilter(request, response);之后执行,这个时候response的committed状态为true。
committed值是在Controller处理完请求后设置的,在filterChain.doFilter之内执行的