我正在努力将现有的Wicket webapp升级到1.5,并且在我们用于呈现HTML电子邮件的renderPage函数中遇到了麻烦.
以前我们使用this StackOverflow question和this (currently broken but maybe fixed later) link中引用/列出的代码,但该代码不再有效,因为很多这些类在1.5中不存在.
我也发现了这个电子邮件主题,但它对细节很清楚,我不知道如何从我的pageClass和参数创建WebPage.
http://apache-wicket.1842946.n4.nabble.com/Render-WebPage-to-String-in-Wicket-1-5-td3622130.html
这是我的代码:
// Renders a page under a temporary request cycle in order to get the rendered markup
public static String renderPage(Class extends Page> pageClass,PageParameters pageParameters)
{
//get the servlet context
WebApplication application = (WebApplication) WebApplication.get();
ServletContext context = application.getServletContext();
//fake a request/response cycle
MockHttpSession servletSession = new MockHttpSession(context);
servletSession.setTemporary(true);
MockHttpServletRequest servletRequest = new MockHttpServletRequest(application,servletSession,context);
MockHttpServletResponse servletResponse = new MockHttpServletResponse(servletRequest);
//initialize request and response
servletRequest.initialize();
servletResponse.initialize();
WebRequest webRequest = new ServletWebRequest(servletRequest);
BufferedWebResponse webResponse = new BufferedWebResponse(servletResponse);
webResponse.setAjax(true);
WebRequestCycle requestCycle = new WebRequestCycle(application,webRequest,webResponse);
requestCycle.setRequestTarget(new BookmarkablePageRequestTarget(pageClass,pageParameters));
try
{
requestCycle.getProcessor().respond(requestCycle);
if (requestCycle.wasHandled() == false)
{
requestCycle.setRequestTarget(new WebErrorCodeResponseTarget(HttpServletResponse.SC_NOT_FOUND));
}
}
finally
{
requestCycle.detach();
requestCycle.getResponse().close();
}
return webResponse.toString();
}
具体来说,代码中断,因为WebRequestCycle和BookmarkablePageRequestTarget类不再存在.我觉得我应该能够使用StringResponse类一些如何,但我错过了可以帮助我触发该响应渲染的链接.
任何帮助,将不胜感激.谢谢.
我的最终解决方案
使用我在下面的答案中指示的示例,我最终得到以下代码.我也在这里粘贴它,以便如果该链接消失或者使用未来版本的Wicket进行更改,那么未来的人们仍然可以获得他们需要的答案.
我最终传入了一个PageProvider,因为在某些情况下我需要传入一个实例化的Page,而在其他情况下我需要传递一个pageClass参数.
public static String renderPage(final PageProvider pageProvider)
{
final RenderPageRequestHandler handler = new RenderPageRequestHandler(pageProvider,RedirectPolicy.NEVER_REDIRECT);
final PageRenderer pageRenderer = Application.get().getPageRendererProvider().get(handler);
RequestCycle requestCycle = RequestCycle.get();
final Response oldResponse = requestCycle.getResponse();
BufferedWebResponse tempResponse = new BufferedWebResponse(null);
try
{
requestCycle.setResponse(tempResponse);
pageRenderer.respond(requestCycle);
}
finally
{
requestCycle.setResponse(oldResponse);
}
return tempResponse.getText().toString();
}
最佳答案