这是一个小型的数据交互案例,即Android手机客户端和后台服务器交互(数据库mysql)
服务器端
首先服务器端数据库(用户名root密码123456),db_student.sql数据库表userinfo(用户名admin,密码123)
访问数据库的工具类DBManager.java
package com.jdbc.db;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 负责访问数据库的工具类
* @author liuya
*
*/
public class DBManager {
//数据库的用户名和密码
private final String USERNAME="root";
private final String PSWD="123456";
//数据库驱动
private final String DRIVER="com.mysql.jdbc.Driver";
private final String URL="jdbc:mysql://localhost:3306/db_student";
private Connection connection;//连接数据库
private PreparedStatement pstmt;//采用预编译的sql语句执行添加、删除、修改和查询的功能,效率高
private ResultSet rs;//查询返回的结果集合
private static DBManager instance;
private DBManager() {
// TODO Auto-generated constructor stub
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getConnection(){
try {
connection=DriverManager.getConnection(URL, USERNAME, PSWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用单例模式获得数据库的访问对象:保证数据的安全性
* @return
*/
public static DBManager getInstance(){
if(instance==null){
instance=new DBManager();
}
return instance;
}
/**
* 释放连接
*/
public void releaseConn(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 功能:对数据库表的增加删除和修改功能
* @param sql
* @param params
* @return
* @throws SQLException
*/
public boolean updateBySql(String sql,List
一、开发服务器端
①创建登录LoginService.java(接口interface)
package com.android.login;
import java.util.List;
//判断用户是否存在
public interface LoginService {
public boolean isUserExitLogin(List params);
}
②声明LoginDao.java实现
LoginService.java
package com.android.login;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.jdbc.db.DBManager;
public class LoginDao implements LoginService {
private DBManager manager;
public LoginDao() {
// TODO Auto-generated constructor stub
manager=DBManager.getInstance();
}
@Override
public boolean isUserExitLogin(List params) {
// TODO Auto-generated method stub
String sql="select * from userinfo where username=? and password=?";
manager.getConnection();
Map map=null;
boolean flag=false;
try {
map=manager.querySingleMap(sql, params);
flag=map.isEmpty()?false:true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
③给手机客户端提供一个接口(Servlet)LoginAction
package com.android.login;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONSerializer;
/**
* Servlet implementation class LoginAction
*/
@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private LoginService service;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
service=new LoginDao();
}
/**
* @see HttpServlet#HttpServlet()
*/
public LoginAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
List params=new ArrayList();
params.add(username);
params.add(password);
boolean flag=service.isUserExitLogin(params);
if(flag){
ResultMessage message=new ResultMessage(1,"登录成功");
Map
map=new HashMap();
map.put("result", message);
String jsonString=JSONSerializer.toJSON(map).toString();
writer.println(jsonString);
}
writer.flush();
writer.close();
}
}
④创建对象ResultMessage.java
package com.android.login;
public class ResultMessage {
private int resultCode;// 结果码
private String resultMessage;// 结果信息
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public ResultMessage() {
// TODO Auto-generated constructor stub
}
public ResultMessage(int resultCode, String resultMessage) {
super();
this.resultCode = resultCode;
this.resultMessage = resultMessage;
}
}
二、开发手机客户端(简单登录)
①在activity_main.xml设置界面如下,在清单文件中加网络授权:Permissions->Add->Uses Permission->ok->在右边的name中查找INTERNET
③创建工具类HttpUtils.java
package com.example.android_httppost_login.http;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpUtils {
public HttpUtils() {
// TODO Auto-generated constructor stub
}
/**
*
* @param path
* @param params 模拟http表单数据
* @param encode
* @return
*/
public static String sendPostMethod(String path,Map params,String encoding){
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(path);
String result="";
List parameters=new ArrayList();
try {
if(params!=null&&!params.isEmpty()){
for(Map.Entry entry:params.entrySet()){
String name=entry.getKey();
//String value=URLEncoder.encode( entry.getValue().toString(),encoding);//如果出现乱码问题,则修改
String value=entry.getValue().toString();
BasicNameValuePair valuePair=new BasicNameValuePair(name, value);
parameters.add(valuePair);
}
}
UrlEncodedFormEntity encodedFormEntity=new UrlEncodedFormEntity(parameters,encoding);//纯文本表单,不包含文件
httpPost.setEntity(encodedFormEntity);
HttpResponse httpResponse=httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(httpResponse.getEntity(), encoding);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
④创建ResultMessage.java状态码类
package com.example.android_httppost_login.domain;
public class ResultMessage {
private int resultCode;// 结果码
private String resultMessage;// 结果信息
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public ResultMessage() {
// TODO Auto-generated constructor stub
}
public ResultMessage(int resultCode, String resultMessage) {
super();
this.resultCode = resultCode;
this.resultMessage = resultMessage;
}
}
⑤创建json字符串解析工具类JsonTools.java
package com.example.android_httppost_login.json;
import org.json.JSONObject;
import com.example.android_httppost_login.domain.ResultMessage;
public class JsonTools {
public JsonTools() {
// TODO Auto-generated constructor stub
}
/**
* {"result":{"resultCode":1,"resultMessage":"登录成功"}}
* @param jsonString
* @return
*/
public static ResultMessage getResultMessage(String jsonString){
ResultMessage message=null;
try {
JSONObject sourceObject=new JSONObject(jsonString);
JSONObject jsonObject=sourceObject.getJSONObject("result");
message=new ResultMessage();
message.setResultCode(jsonObject.getInt("resultCode"));
message.setResultMessage(jsonObject.getString("resultMessage"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
}
package com.example.android_httppost_login;
import java.util.HashMap;
import java.util.Map;
import com.example.android_httppost_login.domain.ResultMessage;
import com.example.android_httppost_login.http.HttpUtils;
import com.example.android_httppost_login.json.JsonTools;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button btn;
private EditText usernameEdt;
private EditText passwordEdt;
private ProgressDialog dialog;
private final String LOGIN_PATH="http://192.168.1.100:8080/Httppost_Web/LoginAction";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button) this.findViewById(R.id.button1);
usernameEdt=(EditText) this.findViewById(R.id.editText1);
passwordEdt=(EditText) this.findViewById(R.id.editText2);
dialog=new ProgressDialog(this);
dialog.setTitle("提示");
dialog.setMessage("正在登录,请稍候...");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name_value=usernameEdt.getText().toString().trim();
String pswd_value=passwordEdt.getText().toString().trim();
Map params=new HashMap();
params.put("url", LOGIN_PATH);
params.put("username", name_value);
params.put("password", pswd_value);
try {
String result=new LoginAsyncTask().execute(params).get();
ResultMessage message=JsonTools.getResultMessage(result);
if(message.getResultCode()==1){
Toast.makeText(MainActivity.this, message.getResultMessage(), 1).show();
Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
}
System.out.println("--->>"+result);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
class LoginAsyncTask extends AsyncTask