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();
		}

	}
}
时间: 2024-08-08 17:16:24

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

Android项目之无线点餐(1)--点餐系统数据库设计

(1)使用数据库mysql,脚本语言如下: /* 用户表*/ CREATE TABLE `usertbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `permission` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=gbk; /*餐桌表

Java Web学习(19):阶段项目之使用JSP+JavaBean完成用户登录

Model1简介 Java Web应用程序的开发总体上来说有两个模型就是Model1和Model2.Model1模型出现前,整个Web应用 的情况:几乎全部由JSP页面组成,JSP页面接收处理客户端请求,对请求处理后直接做出响应.这样的弊端显露无 疑:在界面层充斥着大量的业务逻辑的代码和数据访问层的代码,Web程序的可扩展性和可维护性特别差. JavaBean的出现可以使JSP页面中使用JavaBean封装的数据或者调用JavaBean的业务逻辑代码,这样大大提高 了程序的可维护性. Model

无线点餐项目启动

无线点餐项目启动 最近在与高校合作培训的时候,做了一个小项目,无线点餐系统.该系统主要用于学习用途,综合了JavaWeb开发的底层技术,采用JSP+Servlet+MySQL数据库实现开发,虽然这种开发模式在现在的开发中已经很少使用了,但对于初学者来说,学习JavaWeb底层技术还是有一定的帮助的.项目采用MVC思想进行项目的开发,适合入门级JavaWeb的各位朋友们,大神请略过.今天写的第一篇博文主要是关于项目的启动,介绍项目的背景.项目中所用到的技术.软件等等.话不多说,我们先看博文. 无线

Android项目实战(二十五):Android studio 混淆+打包+验证是否成功

前言: 单挑Android项目,最近即时通讯用到环信,集成sdk的时候 官方有一句 在 ProGuard 文件中加入以下 keep. -keep class com.hyphenate.** {*;} -dontwarn com.hyphenate.** 即:混淆规则. 自己没写过关于混淆打包的文章,在此补上. 下面了解Android studio环境下 项目混淆打包的操作. ------------------------------------------------------------

android loginDemo +WebService用户登录验证

本文是基于android4.0下的loginActivity Demo和android下的Webservice实现的.loginActivity是android4.0下的自带演示例程,他自带登录界面.用户名格式设定.输入密码和用户名格式是否正确.用户登录时间进度条等功能,用户可以在这个例程的基础上延伸出自己login用户登录程序.在这里我没有对这个程序做过多的延伸,只是增加Webservice验证用户登录的功能,使其成为一个完整的网络用户登录验证的模块程序.在这我会对这个Demo做全面的解析,使

iOS开发——网络编程OC篇&amp;(二)XMPP实现用户登录与注销

登录: 步骤: * 在AppDelegate实现登录 1. 初始化XMPPStream 2. 连接到服务器[传一个JID] 3. 连接到服务成功后,再发送密码授权 4. 授权成功后,发送"在线" 消息 一:导入框架,根据上一篇文章的说明去导入相应的库与文件 二:定义一个XMPP的成员变量 1 @interface AppDelegate ()<XMPPStreamDelegate>{ 2 XMPPStream *_xmppStream; 3 } 三:按步骤在代理方法中声明四

2016年最牛逼的分类Android项目源码免费一次性打包下载!

之前发过一个帖子,但是那个帖子有点问题我就重新发一个吧,下面的源码是我从今年开始不断整理源码区和其他网站上的安卓例子源码,目前总共有810套左右,根据实现的功能被我分成了100多个类,总共接近2.5G,还在不断更新.初学者可以快速方便的找到自己想要的例子,大神也可以看一下别人的方法实现.虽然的例子都是我一个人辛辛苦苦花了很多时间和精力整理的,但是既然这些例子是来自于社区那就让他们免费回归社区吧,(是的!特么的不要一分钱!最看不起那些挂羊头卖狗的)你可以在本帖里面按Ctrl+F查找你需要的关键字,

无线点餐系统应用源码

再给大家介绍我做的:sdk :android 1.6  我的方式android手机通过无线wifi连接servlet,然后再servlet中添加代码,然后在写入数据库,我用的数据库是mssql2005,记住驱动用的sqljdbc4.jar,当然我也试过sqljdbc.jar,但是就是连不上,不信可以试试,数据库的代码我放在附件中 tomcat5.0 myeclipse8.5<ignore_js_op><ignore_js_op> <ignore_js_op><ig

Android项目---TouchListener

public static interface View.OnTouchListener android.view.View.OnTouchListener Known Indirect Subclasses AutoScrollHelper, ListViewAutoScrollHelper, ZoomButtonsController Class Overview Interface definition for a callback to be invoked when a touch e