淘忆项目之登录界面的修正归纳
登录注册主要分为两个部分,分别是服务器端和客户端。
登录,获取用户名和密码,通过传入到服务器端,获取返回的数据显示就好了。
第一步:用photoshop设计UI界面
先是服务器端:
主要是对数据库的查询校验,传入username和password,先判断用户是否存在,存在则判断用户名密码是否对应正确,不存在则返回用户不存在,请先注册,用户名密码正确就返回登录成功,否则返回用户名或者密码错误。
服务器端也是以mvc模式书写代码。
Com.elaine.login.service的LoginService.java:
package com.elaine.login.service;
import java.util.List;
public interface LoginService {
public boolean LoginUser(List<Object> params); //登陆操作
public boolean isHavedUser(List<Object> params); //用户是否存在判断
public String getUserId(List<Object> params); //登陆成功,获取userId
}
Com.elaine.login.dao的LoginDao.java:
package com.elaine.login.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.elaine.jdbc.JdbcUtils;
import com.elaine.login.service.LoginService;
public class LoginDao implements LoginService {
private JdbcUtils jdbcUtils;
public LoginDao() {
jdbcUtils = new JdbcUtils();
}
@Override
public boolean LoginUser(List<Object> params) {
// TODO Auto-generated method stub
boolean flag = false;
try {
String sql = "select * from userinfo where username=? and password=?"; //sql语句查询是否密码和用户名对于正确
jdbcUtils.getConnection();
Map<String, Object> map = jdbcUtils.findSimpleResult(sql, params);
flag = !map.isEmpty() ? true : false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
@Override
public boolean isHavedUser(List<Object> params) {
// TODO Auto-generated method stub
boolean flag = false;
try {
jdbcUtils.getConnection();
String sql = "select * from userinfo where username=?"; //查询用户是否存在
Map<String, Object> map = jdbcUtils.findSimpleResult(sql, params);
flag = !map.isEmpty() ? true : false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jdbcUtils.releaseConn();
}
return flag;
}
@Override
public String getUserId(List<Object> params) {
String userId = "";
try {
jdbcUtils.getConnection();
String sql = "select userId from userinfo where username=? and password=?"; //获取用户密码
Map<String,Object> map=jdbcUtils.findSimpleResult(sql, params);
userId=(String) map.get("userId");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return userId;
}
}
Com.elaine.login.action的LoginAction:
package com.elaine.login.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import com.elaine.tools.jsonTool;
import com.elaine.login.dao.LoginDao;
import com.elaine.login.service.LoginService;
public class LoginAction extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private LoginService service;
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");//获取客户端传来的用户名
String password = request.getParameter("password");//获取客户端传来的密码
List<Object> params1 = new ArrayList<Object>();
params1.add(username);//首先添加用户名
boolean falg1 = service.isHavedUser(params1);//判断用户是否存在
if (!falg1) {
String loginMsg = "该用户不存在,请先注册";
String loginJson = jsonTool.creataJsonString("msg", loginMsg); //返回数据
out.print(loginJson);
} else {
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(password); //添加密码
boolean flag = service.LoginUser(params);//判断用户登录是否正确
if (flag) {
String loginRes = "登陆成功";
String userId = service.getUserId(params);
JSONObject object = new JSONObject();
object.put("msg", loginRes);
object.put("userId", userId);//向客户端传递userId的值
out.print(object);
} else {
String loginRes = "用户名或者密码错误";
String loginJson = jsonTool.creataJsonString("msg", loginRes);
out.print(loginJson);
}
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
service = new LoginDao();//初始化service
}
}
客户端的处理:
第一步:在BaseActivity中添加两个方法,实现dialog的显示消失,加强交互效果。
private ProgressDialog dialog;
public void showProgressDialog(String msg) { //传入字符串来显示dialog
if (null == dialog) {
dialog = new ProgressDialog(this);
dialog.setCanceledOnTouchOutside(false);
}
dialog.setMessage(msg);
dialog.show();
}
public void missProgressDialog() {//dialog消失
if (null != dialog) {
dialog.dismiss();
}
}
第二步:在UrlUtils中添加地址。
public static String getLoginUrl() { //添加地址
return URL + "/servlet/LoginAction";
}
第三步:书写布局文件,四个按钮,三个TextView,两个EditText。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f8f8f8"
android:orientation="vertical"
tools:context="com.elainetaylor.blog.ui.activity.LoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:orientation="horizontal">
<ImageButton
android:id="@+id/ib_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:src="@mipmap/icon_back" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
android:text="登录"
android:textColor="#707070"
android:textSize="18sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#dadada" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="45dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名"
android:textColor="#707070"
android:textSize="16sp" />
<EditText
android:id="@+id/et_username"
android:layout_width="245dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:background="@android:color/transparent"
android:inputType="text"
android:textColor="#5000"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="300dp"
android:layout_height="1dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#dadada" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码"
android:textColor="#707070"
android:textSize="16sp" />
<EditText
android:id="@+id/et_password"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:background="@android:color/transparent"
android:inputType="textPassword"
android:textColor="#5000"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="300dp"
android:layout_height="1dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#dadada" />
</LinearLayout>
<Button
android:id="@+id/btn_login"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#00b7ee"
android:gravity="center"
android:text="登录"
android:textColor="#fff"
android:textSize="15sp" />
<FrameLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal"
android:padding="5dp">
<Button
android:id="@+id/btn_goRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="@android:color/transparent"
android:gravity="start|center"
android:text="快速注册"
android:textColor="#707070"
android:textSize="12sp" />
<Button
android:id="@+id/btn_goForgetPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:background="@android:color/transparent"
android:gravity="end|center"
android:text="忘记密码?"
android:textColor="#00b7ee"
android:textSize="12sp" />
</FrameLayout>
</LinearLayout>
第四步:LoginActivity.java的书写。
package com.elainetaylor.blog.ui.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.elainetaylor.blog.R;
import com.elainetaylor.blog.common.BaseActivity;
import com.elainetaylor.blog.common.UrlUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends BaseActivity implements View.OnClickListener {
private Button btnLogin, btnGoRegister, btnForget;
private EditText etUsername, etPassword;
private ImageButton ibBack;
private String username, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init(); //初始化控件
initRequestQueue(); //初始化requestQueue
}
public void init() {
btnLogin = (Button) findViewById(R.id.btn_login);
btnGoRegister = (Button) findViewById(R.id.btn_goRegister);
btnForget = (Button) findViewById(R.id.btn_goForgetPwd);
etUsername = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
ibBack = (ImageButton) findViewById(R.id.ib_back);
btnLogin.setOnClickListener(this);
btnGoRegister.setOnClickListener(this);
btnForget.setOnClickListener(this);
ibBack.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_login:
username = etUsername.getText().toString();//获取用户名
password = etPassword.getText().toString();//获取密码
if (username.isEmpty()) {
Toast.makeText(LoginActivity.this, "亲,请输入用户名", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password) || password.length() < 6) {
Toast.makeText(LoginActivity.this, "亲,请输入六位以上的密码哦", Toast.LENGTH_SHORT).show();
} else {
showProgressDialog("登录中...");
makeLogin(username, password);//提交数据
}
break;
case R.id.btn_goRegister://跳转至注册界面
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
break;
case R.id.ib_back://回到主界面
finish();
break;
case R.id.btn_goForgetPwd://跳转至忘记密码界面
Intent iFor = new Intent(LoginActivity.this, ForgetActivity.class);
startActivity(iFor);
break;
}
}
public void writeMes(String userId) { //在本地写入用户的相关信息,方便自动登录和获取userId
SharedPreferences sharedPreferences = getSharedPreferences("mes", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.putString("isLogin", "true");
editor.putString("userId", userId);
editor.apply();
}
public void makeLogin(final String username, final String password) {
StringRequest request = new StringRequest(Request.Method.POST, UrlUtils.getLoginUrl(), new Response.Listener<String>() {
@Override
public void onResponse(String s) {
try {
JSONObject object = new JSONObject(s);
String msg = object.getString("msg");
if (msg.equals("登陆成功")) {
String userId = object.getString("userId");
writeMes(userId);
finish();
}
missProgressDialog();
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
missProgressDialog();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
missProgressDialog();
Toast.makeText(LoginActivity.this, "服务器出现错误", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
addRequestQueue(request);
}
}