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

       }
   }
相关推荐
飞滕人生TYF几秒前
java Arrays 详解
java·python·排序算法
xisai884 分钟前
2025年开考科目有哪些?
java·开发语言·javascript·算法·kotlin
想花6 分钟前
源码分析Spring Boot (v3.3.0)
java·spring boot·后端
陶然同学16 分钟前
RabbitMQ轻松构建高效可靠的消息队列系统
java·网络·分布式·rabbitmq·mq
Little At Air22 分钟前
C++之红黑树
开发语言
yangmc041 小时前
判断子序列
开发语言·数据结构·c++·算法·矩阵·图论
李小白661 小时前
二叉树的练习题(中)
java·数据结构·算法
骑鱼过海的猫1231 小时前
【redis】redis
java·数据库·redis
漫天转悠1 小时前
Java21和Java8性能优化详细对比
java
昇腾CANN1 小时前
Ascend C算子性能优化实用技巧05——API使用优化
c语言·开发语言·性能优化