首先要先建立一个android_test数据库,在数据库中建立一张userinfo的表。
表中包含字段username,password。
然后创建一个android项目,在res/layout中新建一个page_2.xml的xml文件。设计界面如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:text="@string/welcome"
android:textSize="28sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="30dp">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:text="学号"
android:textSize="30sp" />
<AutoCompleteTextView
android:id="@+id/auto1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:ems="10"
android:hint="请输入你的学号"
android:inputType="phone"
android:singleLine="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="30dp">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:text="密码"
android:textSize="30sp"/>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:ems="10"
android:hint="请输入你的密码"
android:inputType="textPassword"
android:singleLine="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="50dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:text="课程"
android:textSize="30sp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="60dp"
android:layout_toRightOf="@+id/textView1" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_marginTop="30dp"
>
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="52dp"
android:layout_marginTop="26dp"
android:text="@string/sign_in" />
<Button
android:id="@+id/button2"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="28dp"
android:layout_toRightOf="@+id/button1"
android:text="清空" />
</RelativeLayout>
</LinearLayout>
注意:spinner中的数据源可以根据自己的需求来更改,只是为了实现把本页面的数据传到下一个界面的功能。
然后新建page2.java文件
package com.example.sign_in_system_2;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.sign_in_system_2.Json.JsonTools;
import com.example.sign_in_system_2.domain.ResultMessage;
import com.example.sign_in_system_2.http.HttpUtils;
import android.widget.ArrayAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
/**
*
* @author traject0ry
* 在界面2中完成界面的登陆和登陆账号自动填充的功能
*/
public class page_2 extends Activity implements OnItemSelectedListener {
private final String TAG = "page_2";
private Button button, button2;
private AutoCompleteTextView usernameEditText;
private EditText passwordEditText;
private ArrayAdapter<String> adapter;// 数组适配器
private Spinner spinner;
private ArrayAdapter<CharSequence> adapter2;
private final String LOGIN_PATH = HttpUtils.BASE_URL+"LoginAction";// 验证账号密码功能的地址
private final String Username_PATH = HttpUtils.BASE_URL+"UsernameAction";
// 创建dialog
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
button = (Button) this.findViewById(R.id.button1);
usernameEditText = (AutoCompleteTextView) this.findViewById(R.id.auto1);
passwordEditText = (EditText) this.findViewById(R.id.editText2);
button2 = (Button) this.findViewById(R.id.button2);
spinner=(Spinner)this.findViewById(R.id.spinner1);
adapter2=ArrayAdapter.createFromResource(this, R.array.course, android.R.layout.simple_spinner_dropdown_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter2);
spinner.setOnItemSelectedListener(this);
dialog = new ProgressDialog(this);
dialog.setTitle("提示");
dialog.setMessage("正在连接,请稍后....");
new MyTask().execute(Username_PATH);
// button的按键监听器
//也可以继承onclicklistener来实现鼠标监听器的功能
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
click();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
usernameEditText.setText("");
passwordEditText.setText("");
}
});
passwordEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// 当按下回车时执行的操作
if (event.getAction() == KeyEvent.ACTION_DOWN
&& keyCode == KeyEvent.KEYCODE_ENTER) {
click();
}
return false;
}
});
}
/*
* public boolean onKeyDown(int keyCode, KeyEvent event) {
* super.onKeyDown(keyCode, event); return false; }
*/
// click函数
public void click() {
String value1 = usernameEditText.getText().toString().trim();
String value2 = passwordEditText.getText().toString().trim();
if (value1 == null || value1.equals("")) {
usernameEditText.setError("请输入学号");
} else if (value2 == null || value2.equals("")) {
passwordEditText.setError("请输入密码");
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("url", LOGIN_PATH);
params.put("username", value1);
params.put("password", value2);
try {
String result = new LoginAsyncTask().execute(params).get();
ResultMessage message = JsonTools.getResultMessage(result);
if (message.getResultCode() == 1) {
Toast.makeText(page_2.this, message.getResultMessage(), 1)
.show();//显示登陆成功
Intent intent = new Intent(page_2.this, page_3.class);
/* 通过Bundle对象存储封装需要传递的数据 */
Bundle bundle = new Bundle();
/*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/
bundle.putString("username", value1);
bundle.putString("course", spinner.getSelectedItem().toString());
intent.putExtras(bundle);
startActivity(intent);
}
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(page_2.this, "账号密码错误", 1).show();// if中的条件错误也会在catch中执行
}
}
}
// 异步任务
class LoginAsyncTask extends AsyncTask<Map<String, String>, Void, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
@Override
protected String doInBackground(Map<String, String>... params) {
// TODO Auto-generated method stub
Map<String, String> map = params[0];
// 表单数据
Map<String, Object> params2 = new HashMap<String, Object>();
params2.put("username", map.get("username"));
params2.put("password", map.get("password"));
String result = HttpUtils.sendPostMethod(map.get("url"), params2,
"utf-8");
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
// AutoCompleteTextview的异步任务
class MyTask extends AsyncTask<String, Void, List<String>> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
@Override
protected List<String> doInBackground(String... params) {
// TODO Auto-generated method stub
List<String> list = null;
String jsonString = HttpUtils.sendPostMethod2(params[0], "utf-8");
Log.i(TAG, "--->>"+jsonString);
System.out.println("----->>"+jsonString);
list = JsonTools.parseList(jsonString);
System.out.println("---list-->>"+list);
return list;
}
@Override
protected void onPostExecute(List<String> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter = new ArrayAdapter<String>(page_2.this, android.R.layout.simple_list_item_1, result);
usernameEditText.setAdapter(adapter);//适配器完成自动填充窗体中数据源的绑定
dialog.dismiss();
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO 自动生成的方法存根
String item=spinner.getItemAtPosition(position).toString();
Toast.makeText(this, "你选中了"+item, 1).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO 自动生成的方法存根
}
}
服务器代码:
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 Traject0ry
*
*/
public class DBManager {
// 数据库的用户名和密码
private final String USERNAME = "root";
private final String PSWD = "root";
// 数据库的驱动
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String URL = "jdbc:mysql://127.0.0.1:3306/android_test";
private Connection connection;// 链接数据库
private PreparedStatement pstmt;// 采用预编译的sql语句执行添加、删除、修改和查询的功能,效率高
private ResultSet rs;// 查询返回的结果集合
private static DBManager instance;
public DBManager() {
// TODO Auto-generated constructor stub
try {
Class.forName(DRIVER);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void getConnection() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PSWD);
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 使用单例模式获得数据库的访问对象:保证数据的安全性
*
* @return
*/
public static DBManager getInstance() {
if (instance == null) {
instance = new DBManager();
}
return instance;
}
/**
* 释放连接:
*/
public void releaseConn() {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
// TODO: handle exception
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (Exception e) {
// TODO: handle exception
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
public List<String> query(String sql) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
pstmt = connection.prepareStatement(sql);
List<String> list = new ArrayList<String>();
rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int cols_len = metaData.getColumnCount();
String key = metaData.getColumnName(1);
System.out.println("key=" + key);
System.out.println("len=" + cols_len);
while (rs.next()) {
String value = rs.getString(key);
System.out.println("value=" + value);
if (value == null) {
value = "";
}
list.add(value);
}
return list;
}
}
LoginDao.java:
package com.android.login;
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<Object> params) {
// TODO Auto-generated method stub
String sql = "select * from userinfo where username = ? and password = ? ";//?为params的值
manager.getConnection();
Map<String, Object> map = null;
boolean flag = false;
try {
map = manager.querySimpleMap(sql, params);
flag = map.isEmpty() ? false : true;
} catch (Exception e) {
// TODO: handle exception
}
return flag;
}
}
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;
}
}
建立接口LoginService.java:
package com.android.login;
import java.util.List;
public interface LoginService {
// 判断用户是否存在
public boolean isUserExitLogin(List<Object> params);
}
LoginAction.java:
package com.android.login;
/**
* @author 张仁杰
*/
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)
*/
@Override
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)
*/
@Override
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<Object> params = new ArrayList<Object>();
params.add(username);
params.add(password);
boolean flag = service.isUserExitLogin(params);
System.out.println("--->>"+flag);
if(flag){
ResultMessage message = new ResultMessage(1, "登录成功");
Map<String,Object> map = new HashMap<String, Object>();
map.put("result", message);
String jsonString = JSONSerializer.toJSON(map).toString();
writer.println(jsonString);
}
writer.flush();
writer.close();
}
}
这样一个简单的账号密码验证的功能就完成了。