How do I use getOutputStream() and getWriter() in the same servlet request?

后端 未结 2 766
深忆病人
深忆病人 2021-01-07 03:56

How do I use getOutputStream() and getWriter() in the same servlet request?

2条回答
  •  感情败类
    2021-01-07 05:00

    You can't use them both at the same time. If you first did getOutputStream() you can't consequently in the same request do getWriter() and vice versa. You can however wrap your ServletOuptputStream in a PrintWriter to get the same kind of writer you would have from getWriter().

    ServletOutputStream out = response.getOutputStream();
    // Notice encoding here, very important that it matches that of
    // response.setCharacterEncoding();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
    

    Another solution to not using getWriter() is to use a PrintStream which is somewhat similar, but then you don't have type compatibility with Writer or PrintWriter.

    // Encoding again very important to match that of your output.
    PrintStream print = new PrintStream(os, true, "utf-8");
    

提交回复
热议问题