几种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体式格局通报到服务器的数据时涌现乱码;
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几种乱码问题处理要领的细致内容,更多请关注ki4网别的相干文章!