Josh,
I was one of the ones trying this earlier. In a previous iteration, i used a solution very similar to yours, but i found a couple issues. In particular, i think you'll find: 1: You'll get a js error when you pass an object that's not an array 2: Your converter won't be defined if your servlet is called before the DWR servlet is loaded (ie, before any page makes a DWR call).
I've been meaning to write up my full solution, so now's as good as time as any for the steps. If anyone notices a problem, please point it out. Also, i definitely second making this a fully supported DWR lib.
1. Add this to the DwrServlet in web.xml <!-- This publishes the converter container as the "myContainer" attribute of the ServletContext object. --> <init-param> <param-name>publishContainerAs</param-name> <param-value>myContainer</param-value> </init-param> <!-- Start DwrServlet on startup, so that the container is published before we call it in any JSP --> <load-on-startup>1</load-on-startup>
2. Get ConverterManager. In the servlet/JSP:
private ConverterManager getConverterManager() { ServletContext servletContext = this.getServletConfig ().getServletContext(); Container container = (Container) servletContext.getAttribute ("myContainer"); ConverterManager converterManager = (ConverterManager) container.getBean (ConverterManager.class.getName()); return converterManager; }
3. Make the converter, escaping the JS string. We used import org.apache.commons.lang.StringEscapeUtils. The prefix used in the StriptBuffer constructor forces the last line of jsData to be an assignment, so that the eval function later returns the correct value.
private String convertToJs(final Object obj, final ConverterManager converterManager) { try { final ScriptBuffer scriptBuffer; final String jsData;
//Prefix needed to avoid a bug in the non-array case //Only using a global var seems to work scriptBuffer = new ScriptBuffer("dwrObject="); scriptBuffer.appendData(obj); jsData = StringEscapeUtils.escapeJavaScript( ScriptBufferUtil.createOutput(scriptBuffer, converterManager)); return jsData; } catch (MarshallException e) { //Do whatever you want here... return ""; } }
private String dwrConvert(Object obj) { return convertToJs(obj, getConverterManager()); }
4. Add these to the JSP:
<% String jsObjString = dwrConvert(javaObject); %>
5. Convert to a JS object: var jsObj = (function () { return eval("<%=jsObjString%>"); })();
Hope this helps, James
http://markmail.org/message/mkjumuunrdnhysim (새 창으로 열기)
rss