使用HttpServletRequest创建一个cookie?

问题描述 投票:5回答:2

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

我知道这可能与HttpServletResponseRenderingPlugin无法访问该对象。它只有一个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
        }
    }
}
java cookies websphere-portal
2个回答
1
投票

您是否尝试使用javascript代码设置Cookie?

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

你发送这个作为你给作家rpm.getWriter()的内容的一部分,它将由浏览器执行。


0
投票

在我的测试环境中,我遇到了一个模拟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};
        }
    }

此过滤器仅在测试环境中启动。我的班级WebConfig负责这个:

 @HandlesTypes(WebApplicationInitializer.class)
 public class WebConfig implements WebApplicationInitializer
© www.soinside.com 2019 - 2024. All rights reserved.