freemarker 读取template.xml ,通过response 输出文件,解决中文乱码问题

采用

try (Writer writer = new OutputStreamWriter(os, "UTF-8"))

UTF-8 内容转换
复制代码
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            // fileName = "中文.xls";
             try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            //response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);//
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 public void xml2XmlOutFromResources(HttpServletResponse response, Map<String, Object> dataMap, String templetFile, String fileName) throws IOException, TemplateException {

       //设置响应头
       ExportExcel.setResponseHeader(response, fileName);

       Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

       configuration.setDefaultEncoding("UTF-8");
       configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "");
       Template template = null;
       try {
           template = configuration.getTemplate("templates/exportTemplate.xml","UTF-8");
       } catch (Exception e) {
           e.printStackTrace();
       }

       //模板和数据模型合并生成文件
       OutputStream os = null;

       try {
           os = response.getOutputStream();
           try (Writer writer = new OutputStreamWriter(os, "UTF-8")) {
               template.process(dataMap, writer);
           }

       } catch (Exception ex) {

       } finally {
           try {

               if (os != null) {
                   os.close();
               }

           } catch (IOException e) {
               e.printStackTrace();
           }

       }
   }
相关推荐
好家伙VCC几秒前
**发散创新:基于Solidity的通证经济模型设计与智能合约实现**在区块链技术日益成熟的今天,**通证经济(Token Econo
java·python·区块链·智能合约
jjjava2.03 分钟前
计算机体系与进程管理全解析
java·开发语言
AI人工智能+电脑小能手4 分钟前
【大白话说Java面试题】【Java基础篇】第5题:HashMap的底层原理是什么
java·开发语言·数据结构·后端·面试·hash-index·hash
旷世奇才李先生4 分钟前
Java微服务实战:Spring Cloud Alibaba架构优化(从单体到分布式高可用)
java·微服务·架构
小成202303202655 分钟前
数据结构(整理常见结构总结到树层级)
java·c语言·数据结构·c++·链表
谢谢 啊sir6 分钟前
L1-120 智慧文本编辑器 - java
java·开发语言
sycmancia10 分钟前
Qt——缓冲区操作与目录操作
开发语言·qt
weisian15110 分钟前
进阶篇-LangChain篇-15--高级Agent架构—复杂任务拆解(Plan-and-Execute架构)和多智能体协作(LangGraph)
java·架构·langchain·langgraph·planexecute架构
AIGC设计所11 分钟前
网络安全SRC漏洞挖掘学习路线 - 第四期:常见漏洞挖掘实操,实现首次挖洞突破
开发语言·网络·学习·安全·web安全
就叫飞六吧11 分钟前
在线考试翻页抓取题目导出js
开发语言·前端·javascript