您的位置:首页 > 移动开发 > Android开发

Android学习之servlet登录、注册实现

2017-10-30 20:00 330 查看
服务器端是tomcat服务器+Mysql数据库,安卓客户端使用POST方法连接servlet,实现简单的登录、注册程序。该servlet在Java web开发中已经实现好了,现在拿到安卓中用。

MVC结构是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。

Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。

  通常模型对象负责在数据库中存取数据。

View(视图)是应用程序中处理数据显示的部分。

  通常视图是依据模型数据创建的。

Controller(控制器)是应用程序中处理用户交互的部分。

  通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。

servlet就是控制层,连接数据库就放在模型层上。

服务器端:

两个servlet,分别负责登录和注册,调用模型层的函数,连接数据库
登录判断,返回result:
public class AndroidLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

//设置客户端的解码方式为utf-8
response.setContentType("text/html;charset=utf-8");
//
response.setCharacterEncoding("UTF-8");

boolean b=false;
userlogin MyPOJO=new userlogin();//新建MyPOJO类的对象myPOJO

//根据标示名获取JSP文件中表单所包含的参数
String id=request.getParameter("id");
String password=request.getParameter("password");
String result = "";

b=MyPOJO.isuserlogin(id,password);//使用模型对账号和密码进行验证,返回一个boolean类型的对象
PrintWriter out = response.getWriter();//回应请求
if(b){  //如果验证结果为真,跳转至登录成功页面
result = "success";
}
else {  //如果验证结果为假,跳转至登录失败页面
result = "fail";
}
out.write(result);
out.flush();
out.close();
System.out.println(result);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}
}
数据库模型层函数,存在返回true,不存在返回false:
import java.sql.*;
public class userlogin {

String drv = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/login";
String usr = "root";
String pwd = "***";

public boolean isuserlogin(String id,String password){
boolean isValid = false;

String sql="select * from ulogin where uname='"+id+"' and password='"+password+"'";
try{
Class.forName(drv).newInstance();
Connection conn = DriverManager.getConnection(url,usr,pwd);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);

if(rs.next()){
isValid = true;
}

rs.close();
stm.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
if(isValid){//判断用户名以及密码是否与设定相符
return true;
}
else return false;
}
}
注册,返回servlet:
public class androidregister extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

//设置客户端的解码方式为utf-8
response.setContentType("text/html;charset=utf-8");
//
response.setCharacterEncoding("UTF-8");

boolean b = false;
register myPOJO=new register();

String id=request.getParameter("id");
String password=request.getParameter("password");
String email = request.getParameter("email");

String result = "";

b=myPOJO.userregister(id,password,email);//连接数据库,插入该用户信息

PrintWriter out = response.getWriter();//回应请求
if(b){
result = "success";
}
else{
result = "fail";
}
out.write(result);
out.flush();
out.close();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}
}
数据库模型层,插入数据
public class register {

String drv = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/login";
String usr = "root";
String pwd = "***";

public boolean userregister(String id,String password,String email){

boolean b = false;

String sql = "select * from ulogin where uname='"+id+"'";

try{
Class.forName(drv).newInstance();
Connection conn = DriverManager.getConnection(url,usr,pwd);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);

if(!rs.next()){

sql = "insert into ulogin(uname,password,email) values('"+id+"','"+password+"','"+email+"')";
stm.execute(sql);
b = true;
}

rs.close();
stm.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}

if(b)
{
return true;
}
else return false;
}
}
web.xml配置
<servlet>
<servlet-name>AndroidLogin</servlet-name>
<servlet-class>service.AndroidLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AndroidLogin</servlet-name>
<url-pattern>/androidlogin.do</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>AndroidRegister</servlet-name>
<servlet-class>service.androidregister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AndroidRegister</servlet-name>
<url-pattern>/androidregister.do</url-pattern>
</servlet-mapping>


安卓客户端

在MainActivity里实现登录,耗时操作放到线程中去
页面
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.konghao.androidservletlogin.MainActivity">

<EditText
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="用户名" />

<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/id"
android:layout_alignRight="@+id/id"
android:layout_below="@+id/id"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="textPassword"
android:hint="密码"/>

<Button
android:id="@+id/register"
android:text="注册"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_alignLeft="@+id/password"/>

<Button
android:id="@+id/login"
android:text="登录"
android:layout_marginTop="20dp"
android:layout_below="@id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@id/password"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener{

private Button login,register;
private EditText id,password;
private final static int LOGIN_JUDGE = 1;
private int RequestCode = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
register = (Button) findViewById(R.id.register);
register.setOnClickListener(this);
id = (EditText) findViewById(R.id.id);
password = (EditText) findViewById(R.id.password);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1&&resultCode==2){
id.setText(data.getStringExtra("id"));
password.setText(data.getStringExtra("password"));
}
}

Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case LOGIN_JUDGE:{
Bundle bundle = new Bundle();
bundle = msg.getData();
String result = bundle.getString("result");
//Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
try {
if (result.equals("success")) {
Toast.makeText(MainActivity.this,"登录成功!",Toast.LENGTH_SHORT).show();
}
}catch (NullPointerException e){
e.printStackTrace();
}
}
break;
}
}
};

@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.login:{
new Thread(new Runnable() {
@Override
public void run() {
//使用下面类里的函数,连接servlet,返回一个result,使用handler处理这个result
String result = HttpLogin.LoginByPost(id.getText().toString(),password.getText().toString());
Bundle bundle = new Bundle();
bundle.putString("result",result);
Message message = new Message();
message.setData(bundle);
message.what = LOGIN_JUDGE;
handler.sendMessage(message);
}
}).start();
}
break;
case R.id.register:{
Intent intent = new Intent(this,RegisterActivity.class);
startActivityForResult(intent,RequestCode);
}
break;
}
}
}
注册实现,如果注册成功,则返回用户名和密码给上一个活动
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

private int ResultCode = 2;
private final static int REGISTER_JUDGE = 2;
private Button register,back;
private EditText id,psw_1,psw_2,email;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);

register = (Button) findViewById(R.id.register_do);
register.setOnClickListener(this);
id = (EditText) findViewById(R.id.id_edit);
psw_1 = (EditText) findViewById(R.id.password_edit);
psw_2 = (EditText) findViewById(R.id.password_edit_1);
email = (EditText) findViewById(R.id.email_edit);
}

Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case REGISTER_JUDGE:{
Bundle bundle = new Bundle();
bundle = msg.getData();
String result = bundle.getString("result");
//Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
try {
if (result.equals("success")) {
Intent intent = new Intent();
intent.putExtra("id",id.getText().toString());
intent.putExtra("password",psw_1.getText().toString());
setResult(ResultCode,intent);//向上一级发送数据
finish();
}
}catch (NullPointerException e){
e.printStackTrace();
}
}
break;
}
}
};

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.register_do:{
if( ! psw_1.getText().toString().equals(psw_2.getText().toString())){
Toast.makeText(RegisterActivity.this,"两次密码不一致!",Toast.LENGTH_LONG).show();
}else {
new Thread(new Runnable() {
@Override
public void run() {
String result = HttpLogin.RegisterByPost(id.getText().toString(),
psw_1.getText().toString(),email.getText().toString());
Bundle bundle = new Bundle();
bundle.putString("result",result);
Message msg = new Message();
msg.what = REGISTER_JUDGE;
msg.setData(bundle);
handler.sendMessage(msg);
}
}).start();
}
}
break;
}
}
}
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.konghao.androidservletlogin.RegisterActivity">

<EditText
android:id="@+id/id_edit"
android:hint="用户名"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/password_edit"
android:layout_below="@+id/id_edit"
android:hint="密码"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/password_edit_1"
android:hint="确认密码"
android:layout_below="@+id/password_edit"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/email_edit"
android:hint="邮箱"
android:layout_below="@+id/password_edit_1"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<LinearLayout
android:layout_marginTop="20dp"
android:layout_below="@+id/email_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:text="返回"
android:layout_weight="0.5"
android:id="@+id/back_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/email_edit"/>

<Button
android:id="@+id/register_do"
android:text="注册"
android:layout_weight="0.5"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

</RelativeLayout>
HttpLogin类,连接servlet,获取返回值
public class HttpLogin {

public static String LoginByPost(String id,String password){
String address = "http://www.khqust.top/MyWebsite/androidlogin.do";
String result = "";
try{
URL url = new URL(address);//初始化URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//请求方式

//超时信息
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);

//post方式不能设置缓存,需手动设置为false
conn.setUseCaches(false);

//我们请求的数据
String data = "id="+ URLEncoder.encode(id,"UTF-8")+
"&password="+ URLEncoder.encode(password,"UTF-8");

//获取输出流
OutputStream out = conn.getOutputStream();

out.write(data.getBytes());
out.flush();
out.close();
conn.connect();

if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
result = new String(message.toByteArray());
//return result;
}

}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}

return result;
}

public static String RegisterByPost(String id,String password,String email){
String address = "http://www.khqust.top/MyWebsite/androidregister.do";
String result = "";

try{
URL url = new URL(address);//初始化URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//请求方式

//超时信息
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);

//post方式不能设置缓存,需手动设置为false
conn.setUseCaches(false);

//我们请求的数据
String data = "id="+ URLEncoder.encode(id,"UTF-8")+
"&password="+ URLEncoder.encode(password,"UTF-8")+
"&email="+ URLEncoder.encode(email,"UTF-8");

//获取输出流
OutputStream out = conn.getOutputStream();

out.write(data.getBytes());
out.flush();
out.close();
conn.connect();

if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
result = new String(message.toByteArray());
//return result;
}

}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}

return result;

}
}





查询:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐