jsp—(GET传值)—>servlet 中文乱码解决方案

在做web开发的时候,经常涉及到使用GET传递中文到后台,而中文的编码解码很麻烦,以下是亲自实现过的方案,可以正常传递中文,留着以后好用。
方案一:
1、使用encodeURI,两次编码:
javascript端加密中文:

<script> function download(documentPath){ var url = "<c:url value='/product/download.action?documentPath='/>"+documentPath; url = encodeURI(encodeURI(url)); window.location.href=url; } </script>

servlet端取中文:

String documentPath = (String) request.getParameter('documentPath');
 documentPath = URLDecoder.decode(documentPath,"utf-8");

2、使用encodeURIComponent 两次编码
javascript端加密中文:

<script> content=encodeURIComponent(encodeURIComponent(content)); var url="${pageContext.request.contextPath}/BlogAction.do?method=doPublishBlog&content="+content; </script>

servlet端取中文:

String content=(String)request.getParameter("content");  
content=URLDecoder.decode(content,"UTF-8"); 

方案二:
使用servlet过滤器,在包中新建类ParameterEncodingFilter,添加代码:

package com.hwc.a.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ParameterEncodingFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response); // 访问下一个filter类,执行完所有的filter再去执行页面。
    }

    public void init(FilterConfig config) {
    }

    public void destroy() {
    }
}

配置web.xml文件

    <filter>
        <filter-name>FormFilter</filter-name>
        <filter-class>com.hwc.a.servlet.ParameterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>FormFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

servlet端取中文:

String paramName= new String(request.getParameter("paramName").getBytes(
                "ISO-8859-1"), "UTF-8");

你可能感兴趣的:(jsp,乱码)