1、使用该方法,比较繁琐,但是有时也不能很好解决get方式下传递的参数 String str=new String(request.getparemter("id").getBytes("iso-8859-1"),"UTF-8"); 2、使用过滤器过滤乱码问题。不过过滤器很难解决使用get方式传递的参数中的乱码。 过滤器: java文件:
public class CharacterFilter implements Filter {
private String encoding = null; private FilterConfig filter = null;
public void destroy() { this.encoding = null; this.filter = null; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding != null) { request.setCharacterEncoding(encoding); response.setContentType("text/html; charset=" + encoding); } chain.doFilter(request, response); }
public void init(FilterConfig filterConfig) throws ServletException { this.filter = filterConfig; this.encoding = filter.getInitParameter("encoding"); }
} web.xml文件的配置 <filter> <filter-name>CharacterFilter</filter-name> <filter-class>com.phonebook.Filter.CharacterFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> 3、使用URLDecoder的方法 public static String getQueryParam(HttpServletRequest request, String name) { if (StringUtils.isBlank(name)) { return null; } if (request.getMethod().equalsIgnoreCase(POST)) { return request.getParameter(name); } String s = request.getQueryString(); if (StringUtils.isBlank(s)) { return null; } try { s = URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) {
} int i = s.indexOf("="); if (i > 0) { s = s.substring(i+1); } return s; } 使用该方法获取传递的参数,可以解决post或get方式下传递的参数。 4、在spring中使用自带的过滤器 <filter> <filter-name>NewCmsCharacterFilter</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>
这几种是我现阶段总结的,或使用过的解决汉字乱码的方式