我已经创建了RenderingPlugin
,用于WebSphere Portal
,在向客户端发送标记之前会调用服务器端。插件循环遍历所有cookie,如果'测试'找不到,我想设置那个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
}
}
}
答案 0 :(得分:1)
您是否尝试使用javascript代码设置Cookie?
<script>
document.cookie = "test=1;path=/";
</script>
您将此内容作为您提供给Writer rpm.getWriter()
的内容的一部分发送,并且将由浏览器执行。
答案 1 :(得分:0)
我在模拟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};
}
}
此筛选器仅在测试环境中启动。我的类WebConfig负责此工作:
@HandlesTypes(WebApplicationInitializer.class)
public class WebConfig implements WebApplicationInitializer