web開發中文資料寫入到資料庫亂碼問題
阿新 • • 發佈:2019-02-11
第一次開發一個小的專案,經驗尚淺,每次測試資料庫時,都是隨便的輸入幾個英文字元就行了的,看看資料庫中是否顯示了,便當做完成任務了。可是由於專案的要求,註冊時可以使用中文,當測試時,到資料庫中檢視居然亂碼。曾經看傳智的老賀講web時,專案的結尾就是來探討和學習這個亂碼的問題。他提到過濾器的處理方法,可是自己學的不多,只會在在頁面中加入字元編碼的控制。現在談談我的這種麻煩的解決辦法,希望對那些和我一樣剛入門的菜鳥有些幫助!
1.在你的jsp頁面,也就是你打算提交啊資料到servlet的頁面頭部新增程式碼<% request.setCharacterEncoding("ISO8859_1");%>,並且將原來的jsp的頁面的編碼修改gb2123
2.在你所提交的servlet頁面設定編碼request.setCharacterEncoding("ISO8859_1");
3.在servlet裡面,對需要寫入中文到資料庫的的程式碼段下面都加上一行,例如
String xxx= request.getParameter("xxx");
xxx=new String(xxx.getBytes("ISO8859_1"),"gb2312");
4.這樣就可以了
附一個servlet程式碼》》》》》》》
package com.action.student; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dao.StuDao; import com.dao.UserDao; import com.test.md5; public class addStu extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("ISO8859_1"); //測試: response.sendRedirect("index.jsp"); /*解決中文插入資料庫亂碼問題 * 將提交的jsp(register.jsp)的<% request.setCharacterEncoding("ISO8859_1");%> * 在servlet中同新增request.setCharacterEncoding("ISO8859_1"); * 在得到的中文String後,進行xxx=new String(xxx.getBytes("ISO8859_1"),"gb2312");處理 */ String name = request.getParameter("name"); name=new String(name.getBytes("ISO8859_1"),"gb2312"); String num1 = request.getParameter("num1"); String num2 = request.getParameter("num2"); //為了區別關鍵字class-->klass String klass = request.getParameter("class"); String post = request.getParameter("post"); post=new String(post.getBytes("ISO8859_1"),"gb2312"); String partynum = request.getParameter("partynum"); partynum=new String(partynum.getBytes("ISO8859_1"),"gb2312"); //測試:System.out.println(partynum); String both = request.getParameter("both"); String school = request.getParameter("school"); String graduate = request.getParameter("graduate"); String dorm = request.getParameter("dorm"); if (num1.equals(num2)) { StuDao stu = new StuDao(); if (stu.findStu(name, num1) != null) { // response.sendRedirect("index.jsp"); System.err.println("使用者已存在!"); request.getRequestDispatcher("adderror.jsp").forward(request, response); } else { md5 md =new md5(); num1 = md5.string2MD5(num1); //測試是否加密成功System.out.println(num1); int i = stu.addStu(name, num1,klass,post,partynum,both,school,graduate,dorm); if (i < 0) { request.getRequestDispatcher("adderror.jsp").forward( request, response); } else { response.sendRedirect("index.jsp"); } } } else { System.out.println("密碼不一致"); request.getRequestDispatcher("adderror.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }