writer 是否需要在 render 方法里就 close 掉?
下面是FreeMarkerRender.java 里的代码:
public void render() { response.setContentType(contentType); Enumeration<String> attrs = request.getAttributeNames(); Map root = new HashMap(); while (attrs.hasMoreElements()) { String attrName = attrs.nextElement(); root.put(attrName, request.getAttribute(attrName)); } PrintWriter writer = null; try { Template template = config.getTemplate(view); writer = response.getWriter(); template.process(root, writer); // Merge the data-model and the template } catch (Exception e) { throw new RenderException(e); } finally { if (writer != null) writer.close(); } }
下面这段是 beetl 的WebRender.java代码:
public void render(String key, HttpServletRequest request, HttpServletResponse response, Object... args) { Writer writer = null; OutputStream os = null; try { // response.setContentType(contentType); Template template = gt.getTemplate(key); Enumeration<String> attrs = request.getAttributeNames(); while (attrs.hasMoreElements()) { String attrName = attrs.nextElement(); template.binding(attrName, request.getAttribute(attrName)); } WebVariable webVariable = new WebVariable(); webVariable.setRequest(request); webVariable.setResponse(response); webVariable.setSession(request.getSession()); template.binding("session", new SessionWrapper(webVariable.getSession())); template.binding("servlet", webVariable); template.binding("request", request); template.binding("ctxPath", request.getContextPath()); modifyTemplate(template, key, request, response, args); if (gt.getConf().isDirectByteOutput()) { os = response.getOutputStream(); template.renderTo(os); } else { writer = response.getWriter(); template.renderTo(writer); } } catch (IOException e) { handleClientError(e); } catch (BeetlException e) { handleBeetlException(e); } finally { try { if (writer != null) writer.flush(); if (os != null) { os.flush(); } } catch (IOException e) { handleClientError(e); } } }
FreeMarkerRender里调用了 writer.close(), WebRender里面没有调用 writer.close().
-------------------------------------------------------------------------------------------
writer 是否需要在 render 方法里就 close 掉?
如果 close 掉了, 我在下面的代码中就没办法写入数据了, 该如何处理?
public class TimeHandler extends Handler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { long start = System.currentTimeMillis(); nextHandler.handle(target, request, response, isHandled); long end = System.currentTimeMillis(); Writer writer = null; try { writer = response.getWriter(); writer.write("timehandler: " + (end - start)); } catch (IOException e) { } finally { try { if (writer != null) writer.flush(); } catch (IOException e) { } } } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不需要close,一般web服务器,或者框架会在最后close,所以beetl render里只是flush了一下