Android项目之无线点餐(2)--用户登录的客户端和服务器端实现

一、服务器端实现

(1)创建动态服务器项目

Android项目之无线点餐(2)--用户登录的客户端和服务器端实现_第1张图片

个部分代码如下:

package com.lc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionUtil {

	/**
	 * 打开连接
	 * 
	 * @return
	 */
	public static Connection open() {
		// 1.url
		// 2.driver
		// 3.username
		// 4.password
		// 配置文件xml 属性文件Properties

		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/wiressorder?useUnicode=true&characterEncoding=gbk";
		String username = "xuuu";
		String password = "1234567890";

		try {

			Class.forName(driver);
			return DriverManager.getConnection(url, username, password);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 关闭连接
	 * 
	 * @param conn
	 */
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

package com.lc.dao;

/*
 * 对应数据库中的user表
 * 
 * Entity Class或者是JavaBean---UserTabl ORM
 */
public class User {
	private String username;
	private String password;
	private int id;

	/*
	 * 无参的构造方法
	 */
	public User() {
		super();
	}

	/*
	 * 有参的构造方法
	 */

	public User(String username, String password, int id) {
		super();
		this.username = username;
		this.password = password;
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}

package com.lc.dao;

/*
 * UserDao接口
 * 
 * 定义于User有关的方法
 */
public interface UserDao {
	// 实现用户登录
	public User login(String username, String password);
}
package com.lc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 * 用于实现UserDao中定义的方法
 * 
 * 接口的实现类
 */
public class UserDaoImpl implements UserDao {

	@Override
	public User login(String username, String password) {
		Connection connection = ConnectionUtil.open();
		String sql = "select id,username,password from UserTbl where username=? and password=?";
		try {
			// 预查寻
			PreparedStatement pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);

			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				int id = rs.getInt(1); // 获得一个用户的id
				User user = new User();
				// 设置数据
				user.setId(id);
				user.setUsername(username);
				user.setPassword(password);

				return user;
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			ConnectionUtil.close(connection);
		}

		return null;
	}
}
package com.lc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lc.dao.User;
import com.lc.dao.UserDao;
import com.lc.dao.UserDaoImpl;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response); // 都执行dopost
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf8"); // 设置编码方式
		PrintWriter out = response.getWriter();

		// 获得登录的请求信息
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// 打印出来测试:http://localhost:8080/WiressOrderServer/LoginServlet?username=tom&password=123
		// System.out.println("username:" + username + "password:" + password);

		UserDao userDao = new UserDaoImpl();
		User user = userDao.login(username, password);
		if (user != null) {
			System.out.println("username:" + user.getUsername() + "password:"+ user.getPassword());
			out.println("username:" + user.getUsername() + "password:"+ user.getPassword());
		} else {
			System.out.println("没有你所要的用户,登录失败!");
			out.println("没有你所要的用户,登录失败!");

		}
		out.flush();
		out.close();
	}

}

二、客户端实现


布局文件:

<?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" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_password" />

        <EditText
            android:id="@+id/ed_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_username" />

        <EditText
            android:id="@+id/ed_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword" >

            <requestFocus />
        </EditText>
    </LinearLayout>

    <Button
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/login_loginbutton" />

</LinearLayout>



package com.xuliugen.wiressorderclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.util.EntityUtils;

public class HttpUtil {

	public static String doPost(String url, List<NameValuePair> list) {
		HttpPost post = new HttpPost(url);
		HttpEntity entity = null;
		if (list != null) {
			try {
				entity = new UrlEncodedFormEntity(list, "gbk");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			post.setEntity(entity);
		}

		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity());
				// save SharedPre...
				result = new String(result.getBytes("iso-8859-1"), "gbk");
				System.out.println(result);
				return result;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

package com.xuliugen.wiressorderclient;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	private EditText usernameEditText, passwordEditText;
	private Button login_button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		usernameEditText = (EditText) this.findViewById(R.id.ed_username);
		passwordEditText = (EditText) this.findViewById(R.id.ed_password);
		login_button = (Button) this.findViewById(R.id.login_button);

		login_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String url = "http://172.23.252.89:8080/WiressOrderServer/LoginServlet";
				// 执行异步任务
				new MyTask().execute(url);
			}
		});
	}

	String doLogin(String url) {

		String username = usernameEditText.getText().toString();
		String password = passwordEditText.getText().toString();

		// 1.apache client
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		NameValuePair p1 = new BasicNameValuePair("username", username);
		NameValuePair p2 = new BasicNameValuePair("password", password);
		list.add(p1);
		list.add(p2);

		String msg = HttpUtil.doPost(url, list);

		return msg;

	}

	// 多线程的使用:hander、Asynctask
	class MyTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			String result = doLogin(url);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// 1.保存信息
			Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT)
					.show();
		}

	}
}




你可能感兴趣的:(Android项目之无线点餐(2)--用户登录的客户端和服务器端实现)