SpringMVC的文件下载及中文编码问题

首先配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>fileupload</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置springmvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!-- 开启springm的注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 开启扫描指定位置的包 -->
    <context:component-scan base-package="lhc"></context:component-scan>
    <!-- 开启视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

写一个JSP页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.net.URLEncoder" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/download?filename=<%=URLEncoder.encode("风景.jpg","UTF-8")%>">图片下载</a>
</body>
</html>

写一个Controller,重点是处理中文编码问题

package lhc.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Download {
    @RequestMapping("/todownload")
    public String todownload() {
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) {
        String path = "D:/程序测试/要给客户下载的文件/";
        String filename2 = null;
        try {
            //解决找到文件问题:
            // URLEonder把中文用UTF-8编码,然而,tomcat用iso-8859-1解码
            //,我们需要用iso-8859-1编码,再重新用utf-8解码才能匹配到硬盘文件的名字
            filename2 = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        File file = new File(path + filename2);
        HttpHeaders headers = new HttpHeaders();


        String filename3 = null;
        try {
            //解决提示下载框的中文问题:
            // 所有浏览器都会使用本地编码,即中文操作系统使用GBK
            // 浏览器收到这个文件名后,会使用iso-8859-1来解码
            //编码流程:把中文用GBK编码为字节数组,再用ISO-8859-1编码,浏览器先用ISO-8859-1解码为字节数组,在用GBK解码为中文
            filename3 = new String(filename2.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        headers.setContentDispositionFormData("attachment", filename3);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
### 回答1: 在SpringMVC中,中文乱码问题通常是由于字符集编码不一致所导致的。一般有以下几种解决方法: 1. 在web.xml文件中添加过滤器解决乱码问题: ``` <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 2. 在SpringMVC的配置文件中添加字符集编码过滤器: ``` <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> ``` 3. 在控制器方法上添加字符集编码注解: ``` @RequestMapping(value = "/test", produces = "text/plain;charset=UTF-8") @ResponseBody public String test() { //do something } ``` 以上三种方法都可以解决SpringMVC中的中文乱码问题,可以根据自己的实际情况选择适合自己的方法。 ### 回答2: Spring MVC中文乱码问题通常是由于数据的编码与解码不一致造成的。解决办法可以通过以下几种方式: 1. 在web.xml中配置字符集过滤器(CharacterEncodingFilter)来统一设定请求和响应的编码。可以将编码设置为UTF-8,例如: ```xml <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 2. 在@RequestMapping注解中设置produces属性,指定响应的编码,例如: ```java @RequestMapping(value = "/example", produces = "text/html; charset=UTF-8") ``` 3. 在方法参数上添加@RequestParam注解,指定请求参数的编码,例如: ```java @RequestMapping("/example") public String example(@RequestParam(value = "param", required = false) String param, Model model) { // 使用param参数 return "example"; } ``` 4. 使用@ResponseBody注解返回JSON格式数据时,在@RequestMapping注解上添加produces属性,指定返回的媒体类型和编码,例如: ```java @ResponseBody @RequestMapping(value = "/api/example", produces = "application/json; charset=UTF-8") public Map<String, Object> example() { // 返回JSON格式数据 return resultMap; } ``` 通过以上方式,可以有效解决Spring MVC中文乱码问题,确保数据的传输和显示正常。 ### 回答3: 在Spring MVC框架中,出现中文乱码问题的主要原因是字符编码设置不正确。为了解决这个问题,我们可以采取以下几种方法: 1. 在web.xml文件中配置字符编码过滤器(Filter),将请求和响应的字符编码设置为UTF-8。示例如下: ```xml <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 2. 在Spring MVC的配置文件中,配置视图解析器(ViewResolver)时,指定使用UTF-8编码。示例如下: ```xml <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> <property name="contentType" value="text/html;charset=UTF-8" /> </bean> ``` 3. 在Controller方法中使用`@RequestMapping`注解的`produces`属性,设置响应的Content-Type为"application/json;charset=UTF-8",确保响应的中文乱码问题被正确处理。示例如下: ```java @RequestMapping(value = "/example", produces = "application/json;charset=UTF-8") @ResponseBody public String example() { // 处理逻辑 } ``` 通过以上几种方法的组合使用,我们可以有效解决Spring MVC中文乱码问题,确保正确显示和处理中文字符。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值