1.数据库设计
表名:user
2.服务器端设计
1.新建Web Project
2.项目结构图如下:
3.项目代码
LogLet.java
@WebServlet("/LogLet")
public class LogLet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收客户端信息
String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
String password = request.getParameter("password");
System.out.println(username + "--" + password);
// 新建服务对象
LogService serv = new LogService();
// 验证处理
boolean loged = false;
try
{
loged = serv.login(username, password);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (loged) {
System.out.print("Succss");
//request.getSession().setAttribute("username", username);
// response.sendRedirect("welcome.jsp");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("登录成功");
out.flush();
out.close();
} else {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("登录失败");
out.flush();
out.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
ZcLet.java
@WebServlet("/ZcLet")
public class ZcLet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收客户端信息
String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
String password = request.getParameter("password");
String telephone = request.getParameter("telephone");
System.out.println(username + "--" + password);
// 新建服务对象
LogService serv = new LogService();
// 验证处理
boolean loged = false;
boolean loged1 = false;
try
{
loged = serv.yhmpd(username);
loged1 = serv.telpd(telephone);
} catch (SQLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(loged&&loged1){
System.out.print("用户名和手机号重复");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("用户名和手机号重复");
out.flush();
out.close();
}else if(loged && loged1 == false){
System.out.print("用户名重复");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("用户名重复");
out.flush();
out.close();
}else if(loged1 && loged == false){
System.out.print("手机号重复");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("手机号重复");
out.flush();
out.close();
}else{
try
{
serv.zc(username, password, telephone);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/回头ml");
PrintWriter out = response.getWriter();
out.print("注册成功");
out.flush();
out.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
LogService.java
public class LogService
{
private LoginDao dao = new LoginDao();
public Boolean login(String username, String password) throws SQLException {
System.out.println("进入Service");
Long count = dao.login(username,password);
if(count.intValue() != 0){
return true;
}else{
return false;
}
}
public void zc(String username, String password,String telephone)throws SQLException{
dao.add(username, password, telephone);
}
public Boolean yhmpd(String username)throws SQLException{
Long count = dao.pd(username);
if(count.intValue() != 0){
return true;
}else{
return false;
}
}
public Boolean telpd(String telephone)throws SQLException{
Long count = dao.telpd(telephone);
if(count.intValue() != 0){
return true;
}else{
return false;
}
}
}
LoginDao.java
public class LoginDao
{
private QueryRunner queryRunner=new QueryRunner(new ComboPooledDataSource());
public Long login(String username, String password) throws SQLException{
StringBuilder logSql = new StringBuilder( "select count(*) from user where username = '")
.append(username).append("' and '").append(password).append("'");
System.out.println(logSql.toString());
return queryRunner.query(logSql.toString(), new ScalarHandler());
}
public void add(String username, String password, String telephone) throws SQLException{
String sql = "insert into user (username,password,telephone) values(?,?,?)";
queryRunner.insert(sql,new ScalarHandler<Integer>(),username,password,telephone);
}
public Long pd(String username) throws SQLException{
StringBuilder logSql = new StringBuilder( "select count(*) from user where username = '")
.append(username).append("'");
System.out.println(logSql.toString());
return queryRunner.query(logSql.toString(), new ScalarHandler());
}
public Long telpd(String telephone) throws SQLException{
StringBuilder logSql = new StringBuilder( "select count(*) from user where telephone = '")
.append(telephone).append("'");
System.out.println(logSql.toString());
return queryRunner.query(logSql.toString(), new ScalarHandler());
}
}
3.客户端设计
<1> 登陆和注册页面:布局文件
zc.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_wallet"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:text="注册界面"/>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="用户名:"
android:gravity="center"/>
<EditText
android:id="@+id/et_user"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="密码:"
android:gravity="center"/>
<EditText
android:id="@+id/et_password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:hint="手机号:" />
<EditText
android:id="@+id/et_number"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<TextView
android:id="@+id/tv_getCheckCode"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center"
android:text="获取验证码"
android:clickable="true"/>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ll_user"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="验证码:"/>
<EditText
android:id="@+id/et_checkCode"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_sendCheckCode"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:gravity="center"
android:text="注册"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
dl.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_wallet"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:text="登录界面"/>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="用户名:"
android:gravity="center"/>
<EditText
android:id="@+id/et_user1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="密码:"
android:gravity="center"/>
<EditText
android:id="@+id/et_psd1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="@+id/dl_bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="登录"/>
<Button
android:id="@+id/zc_bt"
android:text="注册"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<2> 登陆和注册页面对应的Activity组件,在activity中进行具体操作
dl.java
public class dl extends AppCompatActivity implements View.OnClickListener {
private Button dl1, zc;
EditText username, password;
// 创建等待框
private ProgressDialog dialog;
// 返回的数据
private String info;
// 返回主线程更新数据
private static Handler handler = new Handler();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dl);
dl1 = (Button) findViewById(R.id.dl_bt2);
zc = (Button)findViewById(R.id.zc_bt);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_wallet);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.return_icon);
}
username = (EditText) findViewById(R.id.et_user1);
password = (EditText)findViewById(R.id.et_psd1);
zc.setOnClickListener(this);
dl1.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.dl_bt2:
if (!checkNetwork()) {
Toast toast = Toast.makeText(dl.this,"网络未连接", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
break;
}
// 提示框
dialog = new ProgressDialog(this);
dialog.setTitle("提示");
dialog.setMessage("正在登陆,请稍后...");
dialog.setCancelable(false);
dialog.show();
// 创建子线程,分别进行Get和Post传输
new Thread(new MyThread()).start();
break;
case R.id.zc_bt:
Intent intent = new Intent(dl.this,zc.class);
startActivity(intent);
break;
}
}
// 子线程接收数据,主线程修改数据
public class MyThread implements Runnable {
@Override
public void run() {
info = WebService.executeHttpGet(username.getText().toString(), password.getText().toString());
// info = WebServicePost.executeHttpPost(username.getText().toString(), password.getText().toString());
handler.post(new Runnable() {
@Override
public void run() {
//infotv.setText(info);
Toast.makeText(dl.this,info,Toast.LENGTH_SHORT).show();
Boolean loged = false;
if(info.equals("登录失败")){
showDailog("用户名和密码错误!");
}else {
loged = true;
}
dialog.dismiss();
if(loged){
Toast.makeText(dl.this,"登录成功",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("data_return", "登录成功");
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
// 检测网络
private boolean checkNetwork() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
default:
}
return true;
}
private void showDailog(String text) {
new AlertDialog.Builder(this)
.setTitle(text)
.setPositiveButton("确定", null)
.show();
}
}
zc.java
public class zc extends AppCompatActivity implements View.OnClickListener{
private String info;
private EditText et_number;
private EditText et_checkCode;
private EditText et_user;
private EditText et_password;
private TextView tv_getCheckCode;
private TextView tv_sendCheckCode;
private String phoneNumber;
private String checkCode;
private ProgressDialog dialog;
private static Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zc);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_wallet);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.return_icon);
}
et_user = (EditText) findViewById(R.id.et_user);
et_password = (EditText) findViewById(R.id.et_password);
et_number = (EditText) findViewById(R.id.et_number);
et_checkCode = (EditText) findViewById(R.id.et_checkCode);
tv_getCheckCode = (TextView) findViewById(R.id.tv_getCheckCode);
tv_sendCheckCode = (TextView) findViewById(R.id.tv_sendCheckCode);
checkCode = et_checkCode.getText().toString().trim();
tv_getCheckCode.setOnClickListener(this);
tv_sendCheckCode.setOnClickListener(this);
MobSDK.init(this,"28c4d19ea6b04","24006ac31eee052e78214ec8208938e6");
//注册短信回调
SMSSDK.registerEventHandler(ev);
}
/**
* 短信验证的回调监听
*/
private EventHandler ev = new EventHandler() {
@Override
public void afterEvent(int event, int result, Object data) {
if (result == SMSSDK.RESULT_COMPLETE) { //回调完成
//提交验证码成功,如果验证成功会在data里返回数据。data数据类型为HashMap<number,code>
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
Log.e("TAG", "提交验证码成功" + data.toString());
HashMap<String, Object> mData = (HashMap<String, Object>) data;
String country = (String) mData.get("country");//返回的国家编号
String phone = (String) mData.get("phone");//返回用户注册的手机号
Log.e("TAG", country + "====" + phone);
/*if(info.equals("手机号重复")){
runOnUiThread(new Runnable() {//更改ui的操作要放在主线程,实际可以发送hander
@Override
public void run() {
showDailog("手机号重复!注册失败!");
dialog.dismiss();
}
});
}else if(info.equals("用户名重复")){
runOnUiThread(new Runnable() {//更改ui的操作要放在主线程,实际可以发送hander
@Override
public void run() {
showDailog("用户名重复!注册失败!");
dialog.dismiss();
}
});
}else{*/
if (phone.equals(phoneNumber)) {
runOnUiThread(new Runnable() {//更改ui的操作要放在主线程,实际可以发送hander
@Override
public void run() {
new Thread(new MyThread()).start();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
showDailog("验证失败");
dialog.dismiss();
}
});
}
//}
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功
Log.e("TAG", "获取验证码成功");
} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表
}
} else {
((Throwable) data).printStackTrace();
}
}
};
private void showDailog(String text) {
new AlertDialog.Builder(this)
.setTitle(text)
.setPositiveButton("确定", null)
.show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_getCheckCode:
toast("getCode");
getCheckCode();
break;
case R.id.tv_sendCheckCode:
sendCheckCode();
break;
}
}
/**
* 获取验证码
*/
public void getCheckCode() {
phoneNumber = et_number.getText().toString().trim();
//发送短信,传入国家号和电话号码
if (TextUtils.isEmpty(phoneNumber)) {
toast("号码不能为空!");
} else {
SMSSDK.getVerificationCode("+86", phoneNumber);
toast("发送成功!");
}
}
/**
* 向服务器提交验证码,在监听回调中监听是否验证
*/
private void sendCheckCode() {
checkCode = et_checkCode.getText().toString();
if(et_user.getText().toString().isEmpty()){
Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
}else{
if(et_password.getText().toString().isEmpty()){
Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
}else{
if (!TextUtils.isEmpty(checkCode)) {
dialog = ProgressDialog.show(this, null, "正在验证...", false, true);
//提交短信验证码
SMSSDK.submitVerificationCode("+86", phoneNumber, checkCode);//国家号,手机号码,验证码
Toast.makeText(this, "提交了注册信息:" + phoneNumber, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* Toast
* @param info
*/
public void toast(String info){
Toast.makeText(zc.this, info, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
SMSSDK.unregisterEventHandler(ev);
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
default:
}
return true;
}
public class MyThread implements Runnable {
@Override
public void run() {
info = WebService.executeHttpGet(et_user.getText().toString(), et_password.getText().toString(),et_number.getText().toString());
// info = WebServicePost.executeHttpPost(username.getText().toString(), password.getText().toString());
handler.post(new Runnable() {
@Override
public void run() {
//infotv.setText(info);
Toast.makeText(zc.this,info,Toast.LENGTH_SHORT).show();
if(info.equals("手机号重复")){
showDailog("手机号重复!");
}else if(info.equals("用户名重复")){
showDailog("用户名重复!");
}else {
showDailog("恭喜您!,注册成功!");
}
dialog.dismiss();
}
});
}
}
}
<3> 能够实现Http以get方式通信的类
public class WebService {
private static String IP = "192.168.1.100:8090";
public static String executeHttpGet(String username, String password) {
HttpURLConnection conn = null;
InputStream is = null;
try {
// 用户名 密码
// URL 地址
String path = "http://" + IP + "/LBSTest/LogLet";
path = path + "?username=" + username + "&password=" + password;
conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(3000); // 设置超时时间
conn.setReadTimeout(3000);
conn.setDoInput(true);
conn.setRequestMethod("GET"); // 设置获取信息方式
conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
return parseInfo(is);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
// 意外退出时进行连接关闭保护
if (conn != null) {
conn.disconnect();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String executeHttpGet(String username, String password, String telephone) {
HttpURLConnection conn = null;
InputStream is = null;
try {
// 用户名 密码
// URL 地址
String path = "http://" + IP + "/LBSTest/ZcLet";
path = path + "?username=" + username + "&password=" + password + "&telephone="+ telephone;
conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(3000); // 设置超时时间
conn.setReadTimeout(3000);
conn.setDoInput(true);
conn.setRequestMethod("GET"); // 设置获取信息方式
conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
return parseInfo(is);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
// 意外退出时进行连接关闭保护
if (conn != null) {
conn.disconnect();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// 将输入流转化为 String 型
private static String parseInfo(InputStream inStream) throws Exception {
byte[] data = read(inStream);
// 转化为字符串
return new String(data, "UTF-8");
}
// 将输入流转化为byte型
public static byte[] read(InputStream inStream) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inStream.close();
return outputStream.toByteArray();
}
}
<4> 相关权限
1.网路权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
2.用到了MOBSDK的短信验证功能需要去官网注册使用
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
// 注册MobSDK
classpath "com.mob.sdk:MobSDK:2018.0319.1724"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
MobSDK {
appKey "2dd349e12613b"
appSecret "e6efa12532ac07dc9b8952badd929570"
SMSSDK {}
}