
几种java乱码情况解决方法:
1、在Servlet中获得通过get方式传递到服务器的数据时出现乱码;
public class RegistServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("userName");
byte[] bytes = name.getBytes("ISO8859-1");
String newName = new String(bytes,"UTF-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}解析:在doGet方法中定义一个name变量获得封装在服务器的客户端数据userName,然后将name以“ISO8859-1”的方式赋值给字节数组bytes,最后将此bytes数组以UTF-8的方式赋值给一个新创建的String变量newName,此时newName就是能正常显示的数据,之所以这么麻烦,是因为没有直接的办法一行代码解决,可以就当此方法为固定用法。
2、在Servlet中获得通过post方式传递到服务器的数据时出现乱码;
立即学习“Java免费学习笔记(深入)”;
public class RegistServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//注意:post方式提交数据的乱码解决方式,放在getParameXXX方法之前
req.setCharacterEncoding("UTF-8");
//得到前台input框中name="username"和password="password"的value值
String username = req.getParameter("username");
String password = req.getParameter("password");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}解析:post传递方式下解决乱码问题很简单,就req.setCharacterEncoding(“UTF-8”); 这一行代码,但需注意,要将这句话放在获取数据之前。
3、Servlet通过服务器将数据响应到客户端时出现乱码;
public class RegistServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//方式一:
resp.setContentType("text/html;charset=utf-8");
//方式二:
resp.setHeader("Content-type", "text/html");
resp.setCharacterEncoding("UTF-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}解析:注意,以上两种方法在应用时要写在输出方法之前,另外,两种方式效果一样,因为方式一较简洁,常用方式一。
4、HTML或JSP页面在客户端展示时出现的乱码情况。
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>form表单</title>
</head>更多java知识请关注java基础教程栏目。
以上就是java几种乱码问题解决方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号