jquery ajax struts2 数据库等中文乱码问题解决大全
ok 乱码了。
乱码第一件事,静下心来,思考一下这乱码出处的流程。
1、后台发页面的乱码。
首先检查下后台打印出来是否是乱码。
数据来源是1)从数据库出来的话,检查数据库里面是否已经乱码了。检查下数据库的字符集。
2)是从文件中读出来的话,一定要注意看是用什么格式读取,文件本身是什么格式编码。
注意了这俩2点,来源就清楚了。
读取文件代码:
try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); while(true){ String line = br.readLine(); if(line!=null){ sb.append(line+"\n"); }else{ break; } } br.close(); //response.setCharacterEncoding("UTF-8"); //注意这里要在getWriter()之前。 PrintWriter out = response.getWriter(); //response.setContentType("text/html"); response.setContentType("text/html;charset=utf-8"); //写这里是没有任何作用的!!!!!! System.out.println("sb:"+sb.toString()); //这么转化一下是否有必要? String des = new String(sb.toString().getBytes("UTF-8"),"UTF-8"); System.out.println("des:"+des); out.print(des); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { System.out.println("文件读取错误"); e.printStackTrace(); } return null; request.setCharacterEncoding("uft-8")以后就不会乱码。URLDecoder.decode(content, "utf-8");解码。这样来解决乱码的问题。
function submitContent(){var content = $("#txt").val();var newcon = encodeURIComponent(content); //post 提交方式$.post("<%=basePath%>pkg_updatePage",{ rootpath: allPath, content: newcon }, function(data){var ll = confirm("are you sure?");if(ll==true){ }else{return;} });}var allPath ;function geteditData(name){var path =rootPath+name;allPath = path;$.ajax({ async: false, cache: false, type:"POST", //post! dataType: "text", contentType:"application/x-www-form-urlencoded;charset=gbk", url: "<%=basePath%>pkg_readPage?rootpath="+path, //?xxx=xxx success : function(data){ //alert(typeof(data)); $("#txt").val(data); }, error: function(){ alert("trsData = error") } });} //更新文件 public String updatePage() throws UnsupportedEncodingException{ request.setCharacterEncoding("gbk"); String fiePath = request.getParameter("rootpath"); String content = request.getParameter("content"); String newcontent=null; try {//编码 newcontent = URLDecoder.decode(content, "utf-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();} FileWriter fw;try {fw = new FileWriter(new File(fiePath));fw.write(newcontent);fw.close();} catch (IOException e) {e.printStackTrace();}System.out.println("更新成功");return null; }