使用 HttpServletRequest 创建 cookie?

Create a cookie using HttpServletRequest?

我创建了一个 RenderingPlugin,用于 WebSphere Portal,在向客户端发送标记之前调用服务器端。该插件循环遍历所有 cookie,如果未找到 'test',我想设置该 cookie。

我知道 HttpServletResponse 可以做到这一点,但 RenderingPlugin 无法访问该对象。它只有一个 HttpServletRequest.

还有其他方法吗?

public class Request implements com.ibm.workplace.wcm.api.plugin.RenderingPlugin {

    @Override
    public boolean render(RenderingPluginModel rpm) throws RenderingPluginException {

        boolean found = false;

        HttpServletRequest servletRequest = (HttpServletRequest) rpm.getRequest();
        Cookie[] cookie = servletRequest.getCookies();

        // loop through cookies
        for (int i = 0; i < cookie.length; i++) {

            // if test found
            if (cookie[i].getName().equals("test")) {

                found = true;
            }
        }

        if (!found){

            // set cookie here
        }
    }
}

您是否尝试过使用 javascript 代码来设置 cookie?

<script>
document.cookie = "test=1;path=/";
</script>

您将此作为内容的一部分发送给作者 rpm.getWriter(),它将由浏览器执行。

我在模拟 cookie 时遇到问题,该 cookie 仅在我的测试环境中发送到生产环境中。 我在过滤器中使用 HttpServletRequestWrapper 解决。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        Cookie cookie = new Cookie("Key", "Value");
        chain.doFilter(new CustomRequest((HttpServletRequest) request, cookie), response);
    }
}

class CustomRequest extends HttpServletRequestWrapper {
     private final Cookie cookie;

        public CustomRequest(HttpServletRequest request, Cookie cookie) {
            super(request);
            this.cookie = cookie;
        }

        @Override
        public Cookie[] getCookies() {
         //This is a example, get all cookies here and put your with a new Array
            return new Cookie[] {cookie};
        }
    }

此过滤器仅在测试环境中启动。我的 class WebConfig 会处理这个:

 @HandlesTypes(WebApplicationInitializer.class)
 public class WebConfig implements WebApplicationInitializer