安卓+servlet+MySql 查询+插入(汉字乱码解决)

Posted 小青年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓+servlet+MySql 查询+插入(汉字乱码解决)相关的知识,希望对你有一定的参考价值。

问题:

  安卓程序,通过servlet连接MySQL数据库,并实现查询和插入(修改,删除类似)。

 

其中遇到的最大的问题是:汉字乱码问题(查询条件有汉字乱码、servlet的汉字到数据乱码、安卓通过servlet方法数据库汉字乱码)

  当所有的编码(客户端,服务端,数据库)都为UTF-8时,但是插入汉字依然为乱码。

  1、安卓客户端中的汉字到servlet中为乱码。

    当插入到数据库的汉字为乱码(而不是问号)时。

    解决方法:

    在安卓客户端将String中的汉字由UTF-8转码为ISO8859-1.

    username = new String(((String) username).getBytes("UTF-8"),"iso8859-1");

    在servlet服务端将String中的汉字由ISO8859-1转码为UTF-8.

    username = new String(username.getBytes("iso8859-1"),"UTF-8");

    至此,servlet中收到的汉字即为正确的汉字而不是乱码。

    如果,此时插入到数据库中的汉字由乱码改成了问号,那么请看2.

  2、servlet到数据库中为问号。

    判断此种情况,可在servlet中的SQL语句直接赋值,而不是再获取。如果数据库中显示为问号时。

    解决方法:

    jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8

    其中必须有 ?useUnicode=true&characterEncoding=utf8 而且不能有其他。

 

 

具体例子:

安卓客户端代码:

  

  1 package com.linfeng;
  2 import java.io.ByteArrayInputStream;
  3 import java.io.DataInputStream;
  4 import java.io.IOException;
  5 import java.io.OutputStream;
  6 import java.io.UnsupportedEncodingException;
  7 import java.net.HttpURLConnection;
  8 import java.net.URL;
  9 import java.net.URLEncoder;
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 
 13 import org.apache.http.HttpClientConnection;
 14 import org.apache.http.HttpEntity;
 15 import org.apache.http.HttpResponse;
 16 import org.apache.http.NameValuePair;
 17 import org.apache.http.client.ClientProtocolException;
 18 import org.apache.http.client.entity.UrlEncodedFormEntity;
 19 import org.apache.http.client.methods.HttpPost;
 20 import org.apache.http.client.methods.HttpUriRequest;
 21 import org.apache.http.client.utils.URLEncodedUtils;
 22 import org.apache.http.impl.client.DefaultHttpClient;
 23 import org.apache.http.message.BasicNameValuePair;
 24 import org.apache.http.protocol.HTTP;
 25 import org.apache.http.util.EntityUtils;
 26 
 27 import android.R.string;
 28 import android.app.Activity;
 29 import android.app.ProgressDialog;
 30 import android.os.AsyncTask;
 31 import android.os.Bundle;
 32 import android.util.Log;
 33 import android.view.View;
 34 import android.view.View.OnClickListener;
 35 import android.widget.Button;
 36 import android.widget.EditText;
 37 import android.widget.TextView;
 38 public class MainActivity extends Activity {
 39     // private static final int REQUEST_CODE = 2;
 40     HttpPost httpRequest = new HttpPost(UriAPI.HTTPCustomer);
 41     EditText et_name;
 42     EditText et_xuenian;
 43     EditText et_xueqi;
 44     TextView show_login;
 45     Button btn_login;
 46     Button btn_cancle;
 47     ProgressDialog progressDialog;
 48     /** Called when the activity is first created. */
 49     @Override
 50     public void onCreate(Bundle savedInstanceState) {
 51         super.onCreate(savedInstanceState);
 52         setContentView(R.layout.main);
 53         // 初始化登陆界面
 54         btn_login = (Button) findViewById(R.id.btn_login);
 55         btn_cancle = (Button) findViewById(R.id.btn_cancle);
 56         et_name = (EditText) findViewById(R.id.et_name);
 57         et_xuenian = (EditText) findViewById(R.id.xuenian);
 58         et_xueqi = (EditText) findViewById(R.id.xueqi);
 59         show_login = (TextView) findViewById(R.id.show_login);
 60         progressDialog = new ProgressDialog(this);
 61         btn_login.setOnClickListener(new OnClickListener() {
 62             @SuppressWarnings("unchecked")
 63             @Override
 64             public void onClick(View v) {
 65                 // 通过AsyncTask类提交数据 异步显示
 66                 new AT().execute("20133079", "2016");
 67             }
 68         });
 69     }
 70     public class UriAPI {
 71         /** 定义一个Uri **/
 72         public static final String HTTPCustomer = "http://10.0.2.2:8080/JSONDemo/servlet/Insertdomo";
 73     }
 74     @SuppressWarnings("rawtypes")
 75     class AT extends AsyncTask {
 76         String result = "success";
 77         private HttpURLConnection conn;
 78         @Override
 79         protected void onPreExecute() {
 80             // 加载progressDialog
 81             progressDialog.show();
 82         }
 83         @Override
 84         protected Object doInBackground(Object... params_obj) {
 85             CharSequence username ="20133078";
 86             CharSequence suggest = "铁大jjk";
 87             
 88             suggest = et_name.getText();
 89             
 90             suggest=suggest.toString();
 91         
 92             
 93             try {
 94                 username = new String(((String) username).getBytes("UTF-8"),"iso8859-1");
 95                 suggest = new String(((String) suggest).getBytes("UTF-8"),"iso8859-1");
 96             } catch (Exception e1) {
 97                 // TODO Auto-generated catch block
 98                 e1.printStackTrace();
 99             }
100             
101             
102             if (!username.equals("") && !suggest.equals("")) {
103                 // 请求数据
104                 HttpPost httpRequest = new HttpPost(UriAPI.HTTPCustomer);
105                 // 创建参数
106                 List<NameValuePair> params = new ArrayList<NameValuePair>();
107                 params.add(new BasicNameValuePair("username", username
108                         .toString()));
109                 params.add(new BasicNameValuePair("suggest", suggest.toString()
110                         ));
111                 System.out.println(params);
112                 // params.add(new BasicNameValuePair("flag","0"));
113                 try {
114                     // 对提交数据进行编码
115                     httpRequest.setEntity(new UrlEncodedFormEntity(params,
116                             HTTP.ISO_8859_1));
117                     System.out.println(params);
118                     System.out.println(httpRequest);
119                     HttpResponse httpResponse = new DefaultHttpClient()
120                             .execute(httpRequest);
121                     // 获取响应服务器的数据
122                     if (httpResponse.getStatusLine().getStatusCode() == 200) {
123                         // 利用字节数组流和包装的绑定数据
124                         byte[] data = new byte[2048];
125                         // 先把从服务端来的数据转化成字节数组
126                         data = EntityUtils
127                                 .toByteArray((HttpEntity) httpResponse
128                                         .getEntity());
129                         // 再创建字节数组输入流对象
130                         ByteArrayInputStream bais = new ByteArrayInputStream(
131                                 data);
132                         // 绑定字节流和数据包装流
133                         DataInputStream dis = new DataInputStream(bais);
134                         // 将字节数组中的数据还原成原来的各种数据类型,代码如下:
135                         result = new String(dis.readUTF());
136                         Log.i("服务器返回信息:", result);
137                     }
138                 } catch (ClientProtocolException e) {
139                     e.printStackTrace();
140                 } catch (UnsupportedEncodingException e) {
141                     e.printStackTrace();
142                 } catch (IOException e) {
143                     e.printStackTrace();
144                 }
145             }
146             return result;
147         }
148         @Override
149         protected void onPostExecute(Object result) {
150             // 获得服务器返回信息成功后
151             System.out.print(result);
152             show_login.setText(result.toString()); //显示  success
153             // 取消进度条
154             progressDialog.cancel();
155             
156             if(result.toString()=="success")
157             {
158                 setContentView(R.layout.classlistselect);
159             }
160         }
161     }
162 }

服务端Servlet代码:

  1、连接数据库db:

 1 package db;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 import exception.DbException;
10 public class DbUtils {
11     private final static String DRIVER="com.mysql.jdbc.Driver";
12     private final static String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
13     private final static String NAME="root";
14     private final static String PWD="123456";
15     private static Connection conn=null;
16         public static Connection getConenction(){
17         try {
18             Class.forName(DRIVER);
19             conn=DriverManager.getConnection(URL, NAME, PWD);
20         } catch (ClassNotFoundException e) {
21          throw new DbException("");    
22         } catch (SQLException e) {
23             throw new DbException("");    
24         }catch (Exception e){
25             throw new DbException(e); 
26             
27         }
28         return conn;
29     }
30         public static void freeDb(Connection conn,PreparedStatement pmst,ResultSet rs){
31         try {
32             if (rs!=null) {
33                 rs.close();
34                 
35             }
36         } catch (Exception e) {
37             throw new DbException("");
38         }
39         try {
40             if (pmst!=null) {
41                 pmst.close();
42                 
43             }
44         } catch (Exception e) {
45             throw new DbException("");
46         }
47         try {
48             if (conn!=null) {
49                 conn.close();
50                 
51             }
52         } catch (Exception e) {
53             throw new DbException("");
54         }
55         
56     }
57 
58 }

  2、servlet代码:

 

 1 package servlet;
 2 
 3 
 4 import java.io.DataOutputStream;
 5 import java.io.IOException;
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import dao.Insertdom;
12 public class Insertdomo extends HttpServlet {
13     private static final long serialVersionUID = 314719472293387358L;
14 
15     @Override
16     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
17             throws ServletException, IOException {
18         String re="";
19         String username = req.getParameter("username");
20         String suggest = req.getParameter("suggest");
21         username = new String(username.getBytes("iso8859-1"),"UTF-8");
22         suggest = new String(suggest.getBytes("iso8859-1"),"UTF-8");
23         boolean flag = Insertdom.Add(username,suggest);
24 //        try {
25 //            resp.setCharacterEncoding("UTF-8");
26 //            DataOutputStream output=new DataOutputStream(resp.getOutputStream());
27 //            if ("20133079".equals(username) && "天上".equals(suggest)) {
28 //            re = "suggest";
29 //        }else{
30 //            re = suggest;
31 //        }
32         try {
33             resp.setCharacterEncoding("UTF-8");
34             DataOutputStream output=new DataOutputStream(resp.getOutputStream());
35             if (flag) {
36             re = "成功";
37         }else{
38             re = "失败";
39         }
40         output.writeUTF(re);
41         output.writeInt(1);
42         output.close(); 
43         System.out.print(re);
44         } catch (Exception e) {
45             e.printStackTrace();
46         }
47         
48     }
49 }

 

 

 

 

 

  3、插入具体实现函数:

 

 1 package dao;
 2 
 3 import java.io.UnsupportedEncodingException;
 4 import java.sql.Connection;
 5 import java.sql.PreparedStatement;
 6 import java.sql.SQLException;
 7 
 8 import db.DbUtils;
 9 import exception.DbException;
10 
11 public class Insertdom {
12     static Connection conn = null;
13     /**
14 
15      */
16     static {
17         conn=DbUtils.getConenction();
18         
19     }
20     private final static String SQL="insert into suggest(username,suggest) values (?,?)";
21     /**
22      * @throws UnsupportedEncodingException 
23 
24      */
25     public static boolean Add(String username,String suggest) throws UnsupportedEncodingException{
26         PreparedStatement pmst = null;
27         int rs = 0;
28         boolean flag = true;
29         try {
30             pmst = conn.prepareStatement(SQL);
31             pmst.setString(1, username);
32             pmst.setString(2, suggest);
33             rs=pmst.executeUpdate();
34         } catch (SQLException e) {
35         
36             throw new DbException("查询无", e);
37         }
38          if (rs == 0) {
39                 flag = false;
40                 System.out.println("新增失败");
41             } else {
42                 flag = true;
43                 System.out.println("新增成功");
44             }
45             return flag;
46     }
47 }

 

这只是安卓通过servlet访问数据库的一种方法,还有更多的方法值得我们去学习。 

 

以上是关于安卓+servlet+MySql 查询+插入(汉字乱码解决)的主要内容,如果未能解决你的问题,请参考以下文章

在 jsp/servlet 中将调查数据插入 mySql 数据库

android-servlet-mysql实现登录注册功能

用servlet校验密码2

如何将字符串转换为时间并将其插入 MySQL

Android Studio 实现实现学生信息的查询 -源代码 三(Servlet + 连接MySql数据库) (JSON通信)

Android Studio 实现实现学生信息的查询 -源代码 三(Servlet + 连接MySql数据库) (JSON通信)