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

       }
   }
相关推荐
Js_cold11 分钟前
Verilog函数function
开发语言·fpga开发·verilog
我是苏苏14 分钟前
C#基础:如何从现有类库复制一个新的类库,并且加入解决方案
开发语言·c#
算法与编程之美19 分钟前
理解Java finalize函数
java·开发语言·jvm·算法
怕什么真理无穷25 分钟前
C++面试4-线程同步
java·c++·面试
lkbhua莱克瓦2427 分钟前
Java基础——常用算法5
java·开发语言·笔记·github
cs麦子36 分钟前
C语言--函数(function)
c语言·开发语言
snowfoootball36 分钟前
python函数及面向过程高级特性
开发语言·python
牢七37 分钟前
javan小案例。
java
是苏浙42 分钟前
零基础入门C语言之C语言实现数据结构之顺序表
c语言·开发语言·数据结构
一条晓鱼1 小时前
repo xml语法
xml