李雨轩 3 years ago
commit ae62bc12e7

@ -1,2 +0,0 @@
# liyuxuan_gitProject

11
src/.gitignore vendored

@ -1,11 +0,0 @@
*.iml
.gradle
/local.properties
/.idea/caches/build_file_checksums.ser
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
.DS_Store
/build
/captures
.externalNativeBuild

@ -1,17 +0,0 @@
### 简介
- 2018年天津市大学生创新训练项目—“基于Android的无线点餐系统的设计与研究”。本课题旨在研究并设计一基于Android的无线点餐系统系统能实现顾客就餐全过程的自动化管理。
- 对于系统功能设计:主要包括功能框架和设计模块,其中功能框架主要包括登录模块、点餐模块、结账模块和餐台管理;功能模块设计分为服务器和客户端,具体包括登录功能、用户管理、菜谱管理、系统管理。各模块之间互相依赖,形成一个完整的无线点餐系统手机(平板)客户端与服务器的交互设计系统。
### 研究内容
- A、确立物理架构Android系统客户端通过无线网络访问后台Web服务器如果需要数据访问则访问后台数据库服务器
- B、确立技术选型Android客户端选用JAVA技术网络通信选用Apache Http协议而中间Web服务器采用Servlet响应可客户请求。后台数据库使用JDBC来访问数据库Android客户端部分数据的存储则采用SQLite数据库
- C、进行系统规划和需求分析通过数据流程图、实体属性图分析数据间的关系设计并创建一个合理可靠的数据库
- D、实现客户端功能设计基于Android开发平台前端客户端功能模块大概分为锁定桌号、桌号查询、菜品查询、加菜功能、退菜功能、结算功能
- E、实现服务器端功能设计后端服务器功能模块大概分为用户评价管理、桌号管理、菜品管理、订单管理、信息管理
- F、后端服务器采用Tomcat服务器利用JDBC访问后台数据库Servlet响应HttpRequest请求并返回响应结果在此过程中采用MVC+DAO的设计模式及分层的开发思想。
### 系统页面
![输入图片说明](https://images.gitee.com/uploads/images/2019/0516/160858_7c04667b_2108662.png "2.png")

@ -0,0 +1,515 @@
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via name/password.
* /
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
* IDREAD_CONTACTS
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
*
* TODO: remove after connecting to a real authentication system.
*
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world",
//DUMMY_CREDENTTALS用于模拟已存在的账户冒号前为账户冒号后为密码
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mUserNameView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
//记住密码
private CheckBox rememberPass;
//自动登录
private CheckBox autoLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up the login form. 设置登录表单
rememberPass = (CheckBox) findViewById(R.id.remember_pass);
autoLogin = (CheckBox) findViewById(R.id.auto_login);
//账号输入
mUserNameView = (AutoCompleteTextView) findViewById(R.id.UserName);
populateAutoComplete();
//密码输入
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
//记住密码
boolean isRemember = preferences.getBoolean("remember_password",false);
boolean isAutoLogin = preferences.getBoolean("auto_Login",false);
if(isRemember ) {
//将账户和密码都设置到文本框中
String account = preferences.getString("UserName", "");
String password = preferences.getString("password", "");
mUserNameView.setText(account);
mPasswordView.setText(password);
rememberPass.setChecked(true);
//自动登录
if (isAutoLogin) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
Toast.makeText(getApplicationContext(), "自动登录", Toast.LENGTH_SHORT).show();
}
}
//登录按钮
Button mUserNameSignInButton = (Button) findViewById(R.id.UserName_sign_in_button);
mUserNameSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
//注册按钮
Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this,registerActivity.class);
startActivity(intent);
}
});
//方法最后两个mLoginFormView和mProgressView是用于获取显示的View
//在登陆的时候可以进行登陆窗口goneProgressBar visible的操作。
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
//先是通过mayRequestContacts判断是否继续执行若通过判断则初始化Loaders通过Loaders后台异步读取用户的账户信息。
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
//这个方法是用于请求用户以获取读取账户的权限主要是为了适配6.0新的权限机制
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mUserNameView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
*
* If there are form errors (invalid UserName, missing fields, etc.), the
*
* errors are presented and no actual login attempt is made.
*
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.重置错误。
mUserNameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.在登录尝试时存储值。
String UserName = mUserNameView.getText().toString();
String password = mPasswordView.getText().toString();
editor = preferences.edit();
if(autoLogin.isChecked()){
editor.putBoolean("auto_Login",true);
}
if (rememberPass.isChecked()) {
editor.putBoolean("remember_password", true);
editor.putString("UserName", UserName);
editor.putString("password", password);
} else {
editor.clear();
}
editor.apply();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.如果用户输入密码,请检查有效的密码。
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check
if (TextUtils.isEmpty(UserName)) {
mUserNameView.setError(getString(R.string.error_field_required));
focusView = mUserNameView;
cancel = true;
} else if (!isUserNameValid(UserName)) {
mUserNameView.setError(getString(R.string.error_invalid_UserName));
focusView = mUserNameView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
//有一个错误;不要尝试登录并首先关注
// form field with an error.
//表单字段有错误。
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
//显示进度微调,并启动后台任务
// perform the user login attempt.
//执行用户登录尝试。
showProgress(true);
mAuthTask = new UserLoginTask(UserName, password);
mAuthTask.execute((Void) null);
}
}
private boolean isUserNameValid(String UserName) {
//TODO: Replace this with your own logic 用你自己的逻辑代替这个
return UserName.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic 用你自己的逻辑代替这个
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
* UI
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
//ViewPropertyAnimator API不可用因此只需显示和隐藏相关的UI组件。
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
//检索设备用户的“个人资料”联系人的数据行。
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.UserName
.CONTENT_ITEM_TYPE},
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> UserNames = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
UserNames.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addUserNamesToAutoComplete(UserNames);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addUserNamesToAutoComplete(List<String> UserNameAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
//创建适配器以告诉AutoCompleteTextView在其下拉列表中显示什么。
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, UserNameAddressCollection);
mUserNameView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.UserName.ADDRESS,
ContactsContract.CommonDataKinds.UserName.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
* /
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mUserName;
private final String mPassword;
UserLoginTask(String UserName, String password) {
mUserName = UserName;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//尝试对网络服务进行身份验证。
try {
LoginRequest(mUserName,mPassword);
// Simulate network access.模拟网络访问。
Thread.sleep(3000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mUserName)) {
// Account exists, return true if the password matches.
//帐户存在如果密码匹配则返回true。
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
//在此注册新帐户。
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
/*
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
*/
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
public void LoginRequest(final String account, final String password) {
//请求地址
String url = "http://8.130.38.15:8080/Whoere/LoginServlet?account="+account+"&password="+password;
String tag = "Login";
//取得请求队列
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
//防止重复请求所以先取消tag标识的请求队列
requestQueue.cancelAll(tag);
//创建StringRequest定义字符串请求的请求方式为POST(省略第一个参数会默认为GET方式)
final StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
//@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = (JSONObject) new JSONObject(response).get("params");
String result = jsonObject.getString("Result");
if (result.equals("success")) {
//做自己的登录成功操作,如页面跳转
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this,"欢迎!",Toast.LENGTH_LONG).show();
} else {
if (result.equals("failed"))
Toast.makeText(LoginActivity.this,"账户或密码错误!",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
//做自己的请求异常操作如Toast提示“无网络连接”等
Log.e("TAG", e.getMessage(), e);
}
}
}, new Response.ErrorListener() {
//@Override
public void onErrorResponse(VolleyError error) {
//做自己的响应错误操作如Toast提示“请稍后重试”等
Log.e("TAG", error.getMessage(), error);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("Account", account);
params.put("Password", password);
return params;
}
};
//设置Tag标签
request.setTag(tag);
//将请求添加到队列中
requestQueue.add(request);
}
}

@ -0,0 +1,56 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
try (PrintWriter out = response.getWriter()) {
//获得请求中传来的用户名和密码
String account = request.getParameter("account").trim();
String password = request.getParameter("password").trim();
//密码验证结果
Boolean verifyResult = verifyLogin(account, password);
Map<String, String> params = new HashMap<>();
JSONObject jsonObject = new JSONObject();
if (verifyResult) {
params.put("Result", "success");
} else {
params.put("Result", "failed");
}
jsonObject.put("params", params);
out.write(jsonObject.toString());
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
//验证用户名密码是否正确
private Boolean verifyLogin(String userName, String password) {
User user = UserDAO.queryUser(userName);
//账户密码验证
return null != user && password.equals(user.getPassword());
}
}

@ -0,0 +1,51 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
try (PrintWriter out = response.getWriter()) {
//获得请求中传来的用户名和密码
String account = request.getParameter("account").trim();
String password = request.getParameter("password").trim();
Map<String, String> params = new HashMap<>();
JSONObject jsonObject = new JSONObject();
if(isExist(account)){
params.put("Result", "账号已存在");
}else{
UserDAO.Register(account, password);
params.put("Result", "注册成功");
}
jsonObject.put("结果", params);
out.write(jsonObject.toString());
}
}
//判断用户是否存在
private Boolean isExist(String account) {
User user = UserDAO.queryUser(account);
if(user.getAccount().isEmpty()){
return false;
}else{
return true;
}
}
}

@ -0,0 +1,79 @@
private int socket_port=9999;
private boolean ifListen =true;
/**
*
*/
private Thread socketThread = new Thread() {
public void run() {
while (true) {
try {
if (serverSocket == null && ifListen) {
serverSocket = new ServerSocket(socket_port);
// serverSocket.setSoTimeout(60*1000);
} else if (serverSocket != null) {
socket = serverSocket.accept();
if (socket != null) {
DataInputStream in = new DataInputStream(new BufferedInputStream(socket
.getInputStream()));
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
dataString = new String(data, "utf-8");
AppLog.Log(dataString);
} catch (Exception e) {
AppLog.Log(AppLog.LogType.ERROR, "DataService read: " + e);
destorySocket();
}
}
}
} catch (IOException e1) {
AppLog.Log(AppLog.LogType.ERROR, "DataService accept: " + e1);
destorySocket(); }
try {
Thread.sleep(Config.KEEP_ALIVE_RESPONSE_TIMEOUT);
} catch (InterruptedException e) {
AppLog.Log(e.toString());
}
}
}
};
public void startListen() {
ifListen = true;
if (!ifSocketThreadStart) {
ifSocketThreadStart = true;
socketThread.start();
}
}
public void stopListen() {
ifListen = false;
destorySocket();
}
private void destorySocket() {
AppLog.Log("destorySocket");
try {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
} catch (IOException e) {
AppLog.Log(e.toString());
} finally {
serverSocket = null;
}
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
AppLog.Log(e.toString());
} finally {
socket = null;
}
}

@ -1,27 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Loading…
Cancel
Save