10

晚上好,我想知道如何清除写入 PrintWriter 的数据,即是否可以在打印后从 PrintWriter 中删除数据?

在这个 servlet 中,我将一些文本打印到响应中,并在 # 表示的行处,我想删除所有以前打印的数据并打印新的东西:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String uName = request.getParameter("uName");
    String uPassword = request.getParameter("uPassword");

    if (uName .equals("Islam")) {
        out.println("Valid-Name");
        if (uPassword !=null) {
            if (uPassword .equals("Islam")) {
                // # clear the writer from any printed data here
                out.println("Valid-password");
            } else {
                out.println("");
                out.println("InValid-password");
            }
        }
    } else {
        out.println("InValid-Name");

    }

}

注意:我尝试了 out.flush() 但旧的打印文本仍然存在

4

4 回答 4

10

PrintWriter使用StringWriter. _ 如果需要,您可以从中获取底层缓冲区StringWriter并清除它。

StringWriter sr = new StringWriter();
PrintWriter w = new PrintWriter(sr);

w.print("Some stuff");
// Flush writer to ensure that it's not buffering anything
w.flush();
// clear stringwriter
sr.getBuffer().setLength(0);

w.print("New stuff");

// write to Servlet out
w.flush();
response.getWriter().print(sr.toString());
于 2013-03-23T23:13:20.973 回答
3

HttpServlteResponse.resetBuffer()将清除缓冲的内容。但是是的,如果响应已经刷新到客户端,它将抛出IllegalStateException. 因为在向客户端发送部分响应后清除是非法的。

重置缓冲区…………

void resetBuffer()
清除响应中底层缓冲区的内容,而不清除标头或状态代码。如果已提交响应,则此方法将引发 IllegalStateException。

参考:

Servlet“响应已提交”的原因

于 2013-03-24T07:03:59.890 回答
0

您不能使用PrintWriter从响应中获得的原始数据来执行此操作,因为它由OutputStream与客户端连接对应的实际数据支持。你在那里写的东西通过电线直接进入浏览器(经过一些缓冲),所以你不能“把它拿回来”。

你能做的就是把你的信息写在一些StringBuilder地方,一旦你知道它很好,就把它写到PrintWriter.

如果您希望将此逻辑应用于多个地方(透明地),您可以考虑编写一个过滤器,将原始响应包装在一个HttpServletResponseWrapper返回“假”的响应中,OutputStream或者PrintWriter在实际通过网络发送之前执行此检查。

public class CensorshipFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        CensorshipResponseWrapper wrapper = new CensorshipResponseWrapper(httpServletResponse);
        chain.doFilter(request, wrapper);
        String output = wrapper.sw.toString();
        if ( output.contains("Some forbidden pattern") ) { // your check goes here
            // throw exception or whatever
        } else { // write the whole thing
            httpServletResponse.getWriter().write(output);
        }
    }

    @Override
    public void destroy() {
    }

    static class CensorshipResponseWrapper extends HttpServletResponseWrapper {
        private final StringWriter sw = new StringWriter();

        public CensorshipResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            // you may also fake the output stream, if some of your servlets use this method
            return super.getOutputStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            return new PrintWriter(sw);
        }
    }
}
于 2013-03-23T23:05:28.777 回答
0

最终对我有用的是改变我输出数据的逻辑。

在此处输入图像描述

这是我输出的数据结构,它使用 html 表单中的文本作为输入存储搜索结果。

private final TreeMap<String, ArrayList<SearchResult>> searchResults;

所以我正在迭代这个数据结构的内容并将其打印到 html 中。

public void writeSearchResultsToHtml(PrintWriter writer)
{
    try
    {
        JSONTreeWriter. writeSearchResultsToHtml(searchResults, writer);
    } catch (ArithmeticException | IllegalArgumentException | IOException | NoSuchElementException e)
    {
        System.err.println("Unable to write the search results builder to JSON to the file html.");
    }

    // clear results for next search otherwise
    // the next search will contain the previous
    // results, store them in history.
    searchResults.clear();
}

考虑到我的 servlet 设置,清除数据结构效果很好。

这是我的主要 serverlet 循环逻辑:

public void startServer()
{
    // seed the database for testing
    crawler.startCrawl("http://cs.usfca.edu/~cs212/birds/birds.html");
    index.toJSON("index.json");

    // type of handler that supports sessions
    ServletContextHandler servletContext = null;

    // turn on sessions and set context
    servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContext.setContextPath("/");
    servletContext.addServlet(ViewServlet.class, "/");

    // default handler for favicon.ico requests
    DefaultHandler defaultHandler = new DefaultHandler();
    defaultHandler.setServeIcon(true);

    ContextHandler defaultContext = new ContextHandler("/favicon.ico");
    defaultContext.setHandler(defaultHandler);

    // setup handler order
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{defaultContext, servletContext});

    openWebBrowser();

    // setup jetty server
    Server server = new Server(portNumber);
    server.setHandler(handlers);
    try
    {
        server.start();
        server.join();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}
于 2016-12-15T08:15:37.173 回答