解决参数传递参数的乱码的问题

来源:互联网 发布:特种兵知乎 编辑:程序博客网 时间:2024/06/06 10:51

解决参数的乱码问题

1.在web.xml中添加一个字符串编码的过滤器

<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></span>  

如果是编写自己的字符串过滤器,则需要实现对应的filter接口,如下代码所示:

public class CharactorFilter implements Filter {    String encoding = null;  //字符编码    public void destroy() {        encoding = null;    }    public void doFilter(ServletRequest request, ServletResponse response,                         FilterChain chain) throws IOException, ServletException {        if(encoding != null){            request.setCharacterEncoding(encoding);  //设置request的编码格式            response.setContentType("text/html;charset="+encoding); //设置response字符编码        }        chain.doFilter(request, response);  //传递给下一个过滤器    }    public void init(FilterConfig filterConfig) throws ServletException {        encoding = filterConfig.getInitParameter("encoding"); //获取初始化参数    }}`

2.在后台代码中将获取到的中文参数进行重新的编码,如下面代码所示:

byte[] bytes = name.getBytes("ISO-8859-1");String userName  = new String(bytes,"utf-8");

3. 在js中添加对应的函数

3.1 代码如下所示,在对应的中文字符串参数中添加一个encodeURIComponent函数。

 function  downVideo(url,str) {      window.location.href=url+encodeURIComponent(str);}

3.2 encodeURIComponent函数的作用

将文本字符串编码为一个有效的统一资源标识符 (URI)。主要用于url参数传递的值,在面对不同的浏览器或者同一个浏览器,如果他们对应的编码的不同设置,同样也会影响到url的编码,因此,再好不要在url中使用非ASCII编码,可以在js中使用encodeURIComponent()以及encodeURI()进行编码。