设置内容类型xml在servlet响应中不起作用

时间:2017-04-20 16:07:18

标签: java xml jsp servlets

所以我有一个servlet从另一个servlet获取响应以进行一些格式化,从中生成pdf并编码为base64:

//setting response to get xml
response.setContentType("text/xml;charset=iso-8859-1");
response.addHeader("Content-Type", "text/xml");

String pdf = "";
final StringWriter buffer = new StringWriter();
RequestDispatcher dispatcher = request.getRequestDispatcher(url); //another Servlet

//getting response from another servlet
if (dispatcher != null) {
    dispatcher.include(request, new HttpServletResponseWrapper(response) {
        private PrintWriter writer = new PrintWriter(buffer);
        @Override
        public PrintWriter getWriter() throws IOException {
            return writer;
        }
    });
}

String jspResponse = buffer.toString();

/* 
 *  do some stuff with jspResponse
 *  and putting into Document doc
 */

try {
    //generating pdf content and encoding to base64
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(doc, null);
    renderer.layout();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    renderer.createPDF(baos);

    byte[] base64 = Base64.encodeBase64(baos.toByteArray());
    pdf = new String(base64);
}
catch (Throwable e) {
    e.printStackTrace();
}

request.setAttribute("pdf", pdf);
dispatcher = request.getRequestDispatcher("/new.jsp");
dispatcher.include(request, response);

和jsp:

<%@ page contentType="text/xml" %><?xml version="1.0" encoding="iso-8859-1"?>
<MSG-S>
    <PDF>
        <E>
            <!-- variable containing a string with 40K+ -->
            <BASE64>${pdf}</BASE64>
        </E>
    </PDF>
</MSG-S>

问题是我还在获取内容类型的text / html:

enter image description here

1 个答案:

答案 0 :(得分:0)

我仅添加了response.setContentType("text/xml");,并且确实将 contentType 作为 XML

enter image description here