android客戶端和servlet服務端的簡單登入實現
阿新 • • 發佈:2019-01-25
本文實現了一個android客戶端輸入使用者名稱和密碼登入跳轉到其他android客戶端介面的簡單demo,主要是熟悉android客戶端的網路程式設計,服務端的程式設計,資料庫的操作。
1、android客戶端
主介面如下所示:
對應的佈局檔案:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="登入" android:textColor="@android:color/holo_blue_bright" android:textSize="22sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="35dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="使用者名稱" android:textSize="20sp" /> <EditText android:id="@+id/et_user_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請輸入使用者名稱" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="35dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密碼" android:textSize="20sp" /> <EditText android:id="@+id/et_user_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請輸入密碼" /> </LinearLayout> <Button android:layout_marginTop="30dp" android:id="@+id/btn_sure" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="登入" /> </LinearLayout> </RelativeLayout>
上述佈局對應的Java程式碼:
package com.yqq.loginclient; import com.yqq.loginclient.utils.LoginUtils; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText mUserName; private EditText mPassword; private Button mLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUserName=(EditText) findViewById(R.id.et_user_name); mPassword=(EditText) findViewById(R.id.et_user_password); mLogin=(Button) findViewById(R.id.btn_sure); mLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(TextUtils.isEmpty(mUserName.getText().toString().trim())||TextUtils.isEmpty(mPassword.getText().toString().trim())){ Toast.makeText(MainActivity.this, "資料不能為空!!!", 300).show(); }else{ new AsyncTask<Void,Void,Void>() { String result1=null; @Override protected Void doInBackground(Void... params) { //必須開啟子執行緒訪問網路 //提交資料到伺服器 result1=LoginUtils.connect("172.22.122.1", mUserName.getText().toString().trim(), mPassword.getText().toString().trim()); return null; } @Override protected void onPostExecute(Void result) { if(result1==null){ return ; } if(result1.equals("welldone")){ startActivity(new Intent(MainActivity.this,MyTestActivity.class)); finish(); }else{ Toast.makeText(MainActivity.this,result1,300).show(); } super.onPostExecute(result); } }.execute(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
登入成功後跳轉到該介面
對應的佈局檔案my_test_activity_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="恭喜登入成功!!!\n\n\n越努力越幸運!" /> </LinearLayout>
上述佈局對應的Java程式碼:
package com.yqq.loginclient;
import android.app.Activity;
import android.os.Bundle;
public class MyTestActivity extends Activity {
public MyTestActivity() {
// TODO Auto-generated constructor stub
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_test_activity_layout);
}
}
聯網訪問伺服器的工具類:
package com.yqq.loginclient.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 連線伺服器
*
* @author yqq_coder
*
*/
public class LoginUtils {
public LoginUtils() {
// TODO Auto-generated constructor stub
}
/**
* http://10.1.17.208:8080/LoginService/LoginServlet?userName=Lihua&passWord=123456
* http://localhost:8080/?userName=Lihua&passWord=123456
* @param ip 伺服器IP
* @param userName GET方式傳遞引數使用者名稱
* @param passWord 密碼
* @return
*/
public static String connect(String ip, String userName, String passWord) {
String str = "http://" + ip
+ ":8080/LoginService/LoginServlet?userName="+userName+"&passWord="+passWord;
URL url=null;
InputStream inputStream = null;
HttpURLConnection connection = null;
StringBuffer sb = null;// 執行緒安全
try {
url = new URL(str);//獲得URL物件
try {
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");//GET方式提交引數
connection.setDoOutput(true);//設定可以向伺服器讀寫
connection.setDoInput(true);
//請求成功
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
//打包成字元流
BufferedReader bufferedReader = new BufferedReader(reader);
String str1 = null;
sb = new StringBuffer();
while ((str1 = bufferedReader.readLine()) != null) {
sb.append(str1);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
//關閉流很重要
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
connection = null;
}
}
if (sb != null) {
return new String(sb);
}
return "伺服器異常!";
}
}
客戶端demo下載地址:http://download.csdn.net/detail/u014600432/8187637
2、servlet服務端
2.1開啟MySQL資料庫。
方式一、利用命令列操作資料庫
(1)命令列執行 create database logininfo;建立logininfo資料庫。
(2)建立資料表
(3)插入資料
中文不成功,要改變編碼方式。
(4)查詢結果
(5)其他
方式二、寫Java程式碼用JDBC框架操作資料庫
類似資料庫操作程式碼如下:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DbUtis {
private static Connection conn;
public static JSONArray getData(String name) throws SQLException {
List<GpsInfo> infos = new ArrayList<GpsInfo>();
JSONArray array = new JSONArray();
GpsInfo info = null;
JSONObject jsonObject = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
// 連線資料庫
try {
Class.forName("com.mysql.jdbc.Driver");
// 連結資料庫
conn = DriverManager.getConnection(
"jdbc:mysql://192.168.253.1:3306/test", "root", "admin");
// Statement stmt =(Statement) conn.prepareStatement("");
String sql="select name,longitude,latitude from gpsinfos where name=?";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
// 從結果集裡取值
//System.out.println(rs.getRow());
while (rs.next()) {
// info=new GpsInfo();
// info.setLatitude(rs.getString(0));//緯度
// info.setLongitude(rs.getString(1));
// infos.add(info);
// info=null;
jsonObject = new JSONObject();
try {
jsonObject.put("name", rs.getString("name"));
jsonObject.put("longitude", rs.getString("longitude"));
jsonObject.put("latitude", rs.getString("latitude"));
array.put(jsonObject);
jsonObject=null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (rs != null) {
rs.close();
rs = null;
}
if(pstmt!=null)
{
pstmt.close();
pstmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
return array;
}
public static void insertGpsInfos(GpsInfo info) throws SQLException{
PreparedStatement pstmt = null; // 資料庫表示式
ResultSet rs = null; // 結果集
try {
/*載入驅動*/
//192.168.173.1
Class.forName("com.mysql.jdbc.Driver");
/*連線到資料庫*/
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "admin");
String sql = "insert into gpsinfos (name,longitude,latitude) values (?,?,?)";
/* 獲取表示式*/
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,info.getName());
pstmt.setString(2, info.getLongitude());
pstmt.setString(3, info.getLatitude());
/* 插入資料*/
pstmt.execute();
/* 執行SQL*/
rs = pstmt.executeQuery("select * from gpsinfos");
/* 檢視裡面的資料*/
while (rs.next()) {
System.out.println("姓名=" + rs.getString("name"));
System.out.println("經度=" + rs.getString("longitude"));
System.out.println("緯度=" + rs.getString("latitude"));
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(rs!=null){
rs.close();
}
if(pstmt!=null)
{
pstmt.close();
pstmt = null;
}
if(conn!=null){
conn.close();
}
}
}
public static void createTable() throws SQLException{
try {
//Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.173.1:3306/test","root","admin");
String sql = "CREATE TABLE gpsinfos (id int primary key auto_increment, name varchar(64) not null, longitude varchar(256) not null , latitude varchar(256) not null );";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[]args) throws SQLException{
/*
try {
createTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
//insertGpsInfos(new GpsInfo("小強","5225.1111111","5333333.888222"));
System.out.println(DbUtis.getData("Lihua"));
}
}
本文的資料庫操作類如下:
package com.yqq.loginservice.DButis;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Synchronization;
//JDBC框架完成資料庫查詢
public class TestDbUtils {
// 表示定義資料庫的使用者名稱
private final String USERNAME = "root";
// 定義資料庫的密碼
private final String PASSWORD = "admin";
// 定義資料庫的驅動資訊
private final static String DRIVER = "com.mysql.jdbc.Driver";
//定義資料庫連線
private static Connection mConnection;
//定義訪問資料庫的地址
private final String URL = "jdbc:mysql://172.22.122.1:3306/logininfo";
// 定義sql語句的執行物件可以防止輸入注入
private PreparedStatement pstmt;
// 定義查詢返回的結果集合
private ResultSet resultSet;
//靜態快載入驅動
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static TestDbUtils mTestDbUtils;
public static synchronized TestDbUtils getSington(){
if(mTestDbUtils==null){
mTestDbUtils=new TestDbUtils();
}
return mTestDbUtils;
}
public List<Map<String,String>> getCheckUserInfo() {
List<Map<String,String>> results=new ArrayList<Map<String,String>>();
Map<String,String> result=null;
try {
//獲得資料庫連線
mConnection=DriverManager.getConnection(URL, "root", "admin");
//獲得SQL語句執行物件
String sql="select name,password from user";
pstmt=mConnection.prepareStatement(sql);
resultSet=pstmt.executeQuery();
while(resultSet.next()){
result=new HashMap<String, String>();
result.put("userName", resultSet.getString("name"));
result.put("passWord", resultSet.getString("password"));
results.add(result);
result=null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//先關結果集
if(resultSet!=null){
try {
resultSet.close();
resultSet=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//再關SQL語句執行物件
if(pstmt!=null){
try {
pstmt.close();
pstmt=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//最後關資料庫連線
if(mConnection!=null){
try {
mConnection.close();
mConnection=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return results;
}
private TestDbUtils(){
}
}
2.2servlet子類
package com.yqq.loginservice;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yqq.loginservice.DButis.TestDbUtils;
public class LoginServlet extends HttpServlet {
private TestDbUtils mTestDbUtils;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設定編碼
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
//獲得客戶端提交的引數
String uesrName=req.getParameter("userName");
String password=req.getParameter("passWord");
System.out.print("提交的引數:"+uesrName+password);
if(checkLogin(uesrName, password)){
out.write("welldone");
System.out.print("返回的資料:"+"welldone"+"登入成功");
}else{
out.write("登入失敗該使用者不存在!請先註冊!");
System.out.print("返回的資料:"+"登入失敗該使用者不存在!請先註冊!");
}
out.flush();
}
/**
* 查詢資料庫檢查是否有該引數存在
* @param userName使用者名稱
* @param password密碼
* @return
*/
private boolean checkLogin(String userName,String password){
List<Map<String,String>> results=new ArrayList<Map<String,String>>();
//獲得資料庫操作例項
mTestDbUtils=TestDbUtils.getSington();
results=mTestDbUtils.getCheckUserInfo();
System.out.println(results.toString());
for(Map<String,String> map:results){
if(map.get("userName").equals(userName)&&map.get("passWord").equals(password)){
return true;
}
}
return false;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
}
該類必須進行配置:
用http協議訪問的時候:http://ip+web工程名+servlet子類。
http://10.1.17.208:8080/LoginService/LoginServlet?userName=Lihua&passWord=123456
demo下載地址:http://download.csdn.net/detail/u014600432/8187651