Servlet之中文乱码的解决办法

原因分析

乱码处理方式

服务器端接收中文乱码

解决post提交方式的乱码

解决get提交的方式的乱码

采用过滤器Filter和Proxy动态代理解决Get/Post方法乱码问题

前端页面接收中文乱码

MySQL数据库乱码


 


原因分析

解码的字符集和编码的不一致

数据来源 默认编码格式
浏览器页面 GBK
request(get) ISO-8859-1
request(post) GBK(同浏览器),但是如果是服务器来的页面一般已经设置了UTF-8(例如JSP提交的页面)
Servlet(response) ISO-8859-1

乱码处理方式

  • 服务器端接收中文乱码

解决post提交方式的乱码

request.setCharacterEncoding("UTF-8");

扫描二维码关注公众号,回复: 2346800 查看本文章

解决get提交的方式的乱码

str = newString(str.getbytes("iso8859-1"),"utf-8");

采用过滤器Filter和Proxy动态代理解决Get/Post方法乱码问题

对request方法进行增强

		/*
		 * 对request方法,采用动态代理进行增强
		 */
		final HttpServletRequest req = (HttpServletRequest) request;
		HttpServletRequest enhanceRequset = (HttpServletRequest) Proxy
				.newProxyInstance(req.getClass().getClassLoader(), req
						.getClass().getInterfaces(), new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						// 对getParameter方法进行增强
						String name = method.getName();// 获取requset下所以方法名
						if ("getParameter".equals(name)) {
							String invoke = (String) method.invoke(req, args); // 乱码文字
							invoke = new String(invoke.getBytes("ios8859-1"),
									"utf-8");// 转码
							return invoke;
						}
						return method.invoke(req, args); // request下其他方法,不进行改变
					}
				});

 

  • 前端页面接收中文乱码

           response.setContentType("text/html;charset=UTF-8");或者response.setCharacterEncoding("UTF-8"); 

  • MySQL数据库乱码

useUnicode=true&characterEncoding=UTF-8

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/81130529