一、PC端使用J2EE
1、在Myeclipse中新建一个web Project
新建一个Entity类User
public class User {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2、在数据库中建立相应的表(这里简单的用了Mysql数据库)
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`email` varchar(200) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=gbk;
3、编写简单的JavaBean(这里需要导入相应的mysql的包)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FindUser {
public static final String URL = "jdbc:mysql://localhost:3306/test";//这里的数据库名按照自己的
public static final String USER = "myroot";//用户名
public static final String PWD = "admin888";//密码
private Connection conn = null;
private PreparedStatement psmt =null;
public FindUser() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection(URL,USER,PWD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean findUser(String username,String password) {
boolean flag = false;
String sql = "select * from tb_user where username=? and password=?";
try {
this.psmt = this.conn.prepareStatement(sql);
this.psmt.setString(1, username);
this.psmt.setString(2, password);
ResultSet rs = psmt.executeQuery();
if(rs.next()){
flag = true ;
}else{
flag = false ;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public boolean createUser(User user) {
boolean flag = false;
String sql = "insert into tb_user values(null,?,?,?)" ;
try {
this.psmt = this.conn.prepareStatement(sql);
this.psmt.setString(1, user.getUsername());
this.psmt.setString(2,user.getPassword());
this.psmt.setString(3, user.getEmail());
int result = this.psmt.executeUpdate();
if(result>0)
flag = true;
else
flag = false;
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}
4、编写登录和注册的Servlet
LoginServlet
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;
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username") ;
String password = request.getParameter("password");
FindUser fu = new FindUser();
if(fu.findUser(username, password)){
out.println("success");
}else{
out.println("failed");
}
out.flush();
out.close();
}
}
RegisterServlet
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;
public class RegisterServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
FindUser fu = new FindUser();
if(fu.createUser(user)){
out.println("success");
}else{
out.println("failed");
}
out.flush();
out.close();
}
}
编写Servlet时别忘了要在web.xml中配置
写到这里PC端差不多写完了
二、Android端
1、由于要访问网络要在AndroidManifest.xml文件中加入访问网络的权限
<uses-permission android:name="android.permission.INTERNET"/>
2、登录界面设计
简单的设计,没怎么顾虑美观
main.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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"/>
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/password"/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"/>
</LinearLayout>
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/submit"/>
<Button
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/register"/>
</LinearLayout>
3、注册界面(可以练习下TableLayout)
second.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" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/labelRegister"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/name"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/name"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/password"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/pwd"
android:password="true"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/password2"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/pwd2"
android:password="true"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/email"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/email"/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
<Button
android:id="@+id/reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/register"/>
</TableRow>
</TableLayout>
</LinearLayout>
4、字符串(string.xml)
string.xml<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="name">用户名</string>
<string name="password">密 码</string>
<string name="password2">确认密码</string>
<string name="email">Email</string>
<string name="submit">登 录</string>
<string name="register">注 册</string>
<string name="labelRegister">用 户 注 册</string>
<string name="app_name">LoginDemo1</string>
</resources>
5、登录处理
这里登录写的比较简单,没有添加什么验证什么的。
MainActivity.java
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
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 MainActivity extends Activity {
/** Called when the activity is first created. */
private EditText username,password;
private Button submit,register;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submit);
register = (Button) findViewById(R.id.register);
submit.setOnClickListener(new loginListener());
register.setOnClickListener(new registerListener());
}
class registerListener implements OnClickListener{
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
class loginListener implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
//http地址
String urlStr = "http://10.0.2.2:8030/login/LoginServlet" ;
//HttpPost链接对象
HttpPost post = new HttpPost(urlStr) ;
//使用默认的HttpClient
HttpClient client = new DefaultHttpClient();
//使用NameValuePair来保存要传递的Post参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username", username.getText().toString()));
list.add(new BasicNameValuePair("password", password.getText().toString()));
HttpResponse response ;
try{
//设置字符集
HttpEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
//请求httpResponse(httpRequest)
post.setEntity(entity);
//取得HttpResponse
response = client.execute(post);
//HttpStatus.SC_OK表示连接成功
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得要返回的字符串
String str = EntityUtils.toString(response.getEntity());
System.out.println("response:"+str);
if(str.trim().equals("success")){
//用户登录成功
System.out.println("登录成功!");
Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
}
else{
//用户登录失败
System.out.println("登录失败!");
Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_LONG).show();
}
}else{
System.out.println("连接失败!");
Toast.makeText(MainActivity.this, "链接失败", Toast.LENGTH_LONG).show();
}
}catch(Exception e){
e.printStackTrace();
} finally {
}
}
}
}
6、注册处理
SecondActivity.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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;
import android.app.Activity;
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 SecondActivity extends Activity {
private EditText name,pwd,pwd2,email;
private Button register;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
name = (EditText) findViewById(R.id.name);
pwd = (EditText) findViewById(R.id.pwd);
pwd2 = (EditText) findViewById(R.id.pwd2);
email = (EditText) findViewById(R.id.email);
register = (Button) findViewById(R.id.reg);
register.setOnClickListener(new regListener());
}
//格式验证
public boolean validate() {
String uname = name.getText().toString();
String upwd = pwd.getText().toString();
String upwd2 = pwd2.getText().toString();
String uemail = email.getText().toString();
if(uname.equals("") || upwd.equals("") || upwd2.equals("") || uemail.equals("")) {
Toast.makeText(SecondActivity.this, "输入不能为空", Toast.LENGTH_LONG).show();
name.setFocusableInTouchMode(true);
return false;
}else if(!upwd2.equals(upwd)){
Toast.makeText(SecondActivity.this, "两次密码输入不一致", Toast.LENGTH_LONG).show();
pwd.setFocusableInTouchMode(true);
return false;
}else if(!uemail.matches("\\w+@\\w+\\.(com\\.cn)|\\w+@\\w+\\.(com|cn)")){
Toast.makeText(SecondActivity.this, "Email格式不正确", Toast.LENGTH_LONG).show();
email.setFocusableInTouchMode(true);
return false;
}
return true;
}
class regListener implements OnClickListener{
public void onClick(View v) {
if(validate()){
//链接地址
String url = "http://10.0.2.2:8030/login/RegisterServlet";
//使用post传值
HttpPost httpRequest = new HttpPost(url);
//使用NameValuePair传值
List<NameValuePair> list = new ArrayList<NameValuePair>();
//保存要传递的值
list.add(new BasicNameValuePair("username", name.getText().toString()));
list.add(new BasicNameValuePair("password", pwd.getText().toString()));
list.add(new BasicNameValuePair("email", email.getText().toString()));
//设置字符集
try {
HttpEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
//请求httpRequest
httpRequest.setEntity(entity);
//得到默认的HttpClient对象
HttpClient client = new DefaultHttpClient();
//使用默认的HttpClient对象client得到HttpResponse对象
HttpResponse response = client.execute(httpRequest);
//判断是否链接成功
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//得到PC端返回的字符串
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
//判断字符串
if(result.trim().equals("success")){
Toast.makeText(SecondActivity.this, "注册成功", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(SecondActivity.this, "注册失败", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(SecondActivity.this, "链接失败", Toast.LENGTH_LONG).show();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
别忘了在AndroidManifest.xml中注册SecondActivity
三、效果图
由于刚开通博客没多久,先写到这吧。。