最近在重溫JavaWeb基礎內容,碰到了以前也時常遇到的中文亂碼問題,想着反正是常常要處理的,不如立即就把它整理出來放在博客裏,免得遇到時再去處處搜。javascript
1. Post請求亂碼的解決方案:html
手工建立一個過濾器實現javax.servlet.Filter接口:java
public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //解決以Post方式提交的中文亂碼問題 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } @Override public void destroy() { } }
在web.xml中配置該過濾器:web
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>cn.lby.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
固然,實際開發中通常不會去本身作這個Filter,都是利用框架裏封裝好的,傳參也能經過配置來完成,十分方便,好比spring一般咱們會在web.xml中寫入下面的代碼:ajax
<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. Get請求亂碼的解決方案:spring
在字符過濾器中使用動態代理解決中文亂碼:tomcat
public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //解決以Post方式提交的中文亂碼問題 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); ServletRequest requestProxy = getHttpServletRequestProxy((HttpServletRequest)request); chain.doFilter(requestProxy, response); } @Override public void destroy() { } /** * @Method: getHttpServletRequestProxy * @Description: 獲取HttpServletRequest對象的代理對象 * @param request * @return HttpServletRequest對象的代理對象 */ private ServletRequest getHttpServletRequestProxy(final HttpServletRequest request){ ServletRequest proxy = (ServletRequest) Proxy.newProxyInstance( CharacterEncodingFilter.class.getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //若是請求方式是get而且調用的是getParameter方法 if (request.getMethod().equalsIgnoreCase("get") && method.getName().equals("getParameter")) { //調用getParameter方法獲取參數的值 String value = (String) method.invoke(request, args); if(value==null){ return null; } //解決以get方式提交的中文亂碼問題 return new String(value.getBytes("iso8859-1"),"UTF-8"); }else { //直接調用相應的方法進行處理 return method.invoke(request, args); } } }); //返回HttpServletRequest對象的代理對象 return proxy; } }
若是以爲上面的方式太繁瑣,也能夠經過修改 tomcat 的 server.xml 配置文件:app
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
改爲:框架
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
注: 若是是ajax發起的get請求中文依然會亂碼,這時候須要把 useBodyEncodingForURI="true" 改成 URIEncoding="UTF-8" 。jsp
下面是測試兩種亂碼問題解決方案的 demo ,若是懶得寫能夠參考一下:
首先是jsp頁面:
<!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>使用字符過濾器解決解決get、post請求方式下的中文亂碼問題</title> body { text-align: center; padding: 60px 150px; margin-right: 150px; line-height: 2.0em; } </head> <body> <%--使用get的方式訪問 --%> <a onclick="myClick()" href="javascript:void(0)">超連接(get方式請求)</a> <hr/> <form action="EncodingServlet" method="post"> 用戶名:<input type="text" name="username" value="彬爺" /> <input type="submit" value="post方式提交"> </form> <script type="text/javascript"> function myClick() { window.location.href = "EncodingServlet?username=彬爺"; } </script> </body> </html>
後臺服務:
public class EncodingServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public EncodingServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String method = request.getMethod(); PrintWriter out = response.getWriter(); System.out.println("請求方式爲:" + method); out.write("請求方式爲:" + method); out.write("<br/>"); System.out.println("請求參數爲:" + username); out.write("請求參數爲:" + username); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xml 中的 Servlet 配置我這裏就不發了。