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();
           }

       }
   }
相关推荐
Frank_refuel几秒前
C++日期类实现
开发语言·c++·算法
Jeremy爱编码1 分钟前
电话号码的字母组合
java·算法·leetcode
月明长歌2 分钟前
JavaThread类详解核心属性、常用方法与实践
java·开发语言·jvm
kaico20182 分钟前
JVM的垃圾回收
开发语言·jvm
Good_Starry2 分钟前
Java——网络编程
java
pulinzt5 分钟前
【python第三节】循环+函数初步
开发语言·python
zfj3215 分钟前
java垃圾收集 minorgc majargc fullgc
java·开发语言·jvm·gc·垃圾收集器
Vic101017 分钟前
华为云高斯数据库:gsqlexec用法
java·大数据·数据库·postgresql·华为云
姓蔡小朋友8 分钟前
算法-子串
java·数据结构·算法
耀耀_很无聊13 分钟前
16_大文件上传方案:分片上传、断点续传与秒传
java·spring boot·后端