使用宁静的Web服务(Java + MySQL)进行Android登录和注册

Here you will learn to make android login and register system using restful web services in java and mysql.

在这里,您将学习使用Java和mysql中的静态Web服务来使android登录和注册系统。

In this tutorial I will teach you to develop a very simple android app for login and register system. This system sends the login or register request to the restful web service that is running on local server.

在本教程中,我将教您开发用于登录和注册系统的非常简单的android应用。 该系统将登录或注册请求发送到在本地服务器上运行的静态Web服务。

If you don’t know how to make restful web services in java and use it in android then I would highly recommend you to first read below tutorials.

如果您不知道如何在Java中制作静态Web服务并在android中使用它,那么我强烈建议您首先阅读以下教程。

Also Read: Create Simple Java RESTful Web Services Using Jersey

另请阅读: 使用Jersey创建简单的Java RESTful Web服务

Also Read: Android Restful Web Service Client Example

另请参阅: Android Restful Web服务客户端示例

Android Login and Register Using Restful Web Services (Java + MySQL)

使用宁静的Web服务(Java + MySQL)进行Android登录和注册 (Android Login and Register Using Restful Web Services (Java + MySQL))

创建宁静的Web服务 (Create Restful Web Service)

I have used MySQL database in this web service. Make a login table in database with following schema.

我已在此Web服务中使用MySQL数据库。 使用以下架构在数据库中创建登录表。

mysql database login schema

Below is the code for restful web service developed in Java.

以下是用Java开发的静态Web服务的代码。

DemoService.java

DemoService.java

package example;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("/DemoService")
public class DemoService {
	final static String url = "jdbc:mysql://localhost:3306/test";
	final static String user = "root";
	final static String pass = "root";
 
	@POST
	@Path("/login")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.TEXT_HTML)
	public String login(@FormParam("email") String email, @FormParam("password") String password){
		String result="false";
		
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url, user, pass);
			
			PreparedStatement ps = con.prepareStatement("select * from login where email=? and password=?");
			ps.setString(1, email);
			ps.setString(2, password);
			
			ResultSet rs = ps.executeQuery();
			
			if(rs.next()){
				result = "true";
			}
			
			con.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return result;
	}
 
	@POST
	@Path("/register")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.TEXT_HTML)
	public String register(@FormParam("email") String email, @FormParam("password") String password){
		String result="false";
		int x = 0;
		
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url, user, pass);
						
			PreparedStatement ps = con.prepareStatement("insert into login(email, password) values(?,?)");
			ps.setString(1, email);
			ps.setString(2, password);
			
			x = ps.executeUpdate();
			
			if(x==1){
				result = "true";
			}
			
			con.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return result;
	}
}

创建Android项目 (Create Android Project)

Make a new android project with package name com.loginandregister

用包名称com.loginandregister创建一个新的android项目

For sending and fetching data from server I am using Volley library. So add its dependency in build.gradle file.

为了从服务器发送和获取数据,我使用了Volley库。 因此,将其依赖性添加到build.gradle文件中。

compile 'com.android.volley:volley:1.0.0'

Read below tutorial if you don’t know how to use volley library.

如果您不知道如何使用排球库,请阅读以下教程。

Also Read: Android Volley Tutorial With Example

另请阅读: Android Volley教程示例

As we are doing network related operation so add internet access permission in AndroidManifest.xml file.

由于我们正在进行与网络相关的操作,因此请在AndroidManifest.xml文件中添加互联网访问权限。

<uses-permission android:name="android.permission.INTERNET"/>

Now create three activities in the project Login, Register and Home. Add following code in the respective files.

现在,在项目LoginRegisterHome中创建三个活动。 在相应的文件中添加以下代码。

Login.java

Login.java

package com.loginandregister;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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 java.util.HashMap;
import java.util.Map;
 
public class Login extends AppCompatActivity {
    EditText emailBox, passwordBox;
    Button loginButton;
    TextView registerLink;
    String URL = "http://192.168.1.8/JavaRESTfullWS/DemoService/login";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
 
        emailBox = (EditText)findViewById(R.id.emailBox);
        passwordBox = (EditText)findViewById(R.id.passwordBox);
        loginButton = (Button)findViewById(R.id.loginButton);
        registerLink = (TextView)findViewById(R.id.registerLink);
 
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        if(s.equals("true")){
                            Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_LONG).show();
                            startActivity(new Intent(Login.this,Home.class));
                        }
                        else{
                            Toast.makeText(Login.this, "Incorrect Details", Toast.LENGTH_LONG).show();
                        }
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(Login.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parameters = new HashMap<String, String>();
                        parameters.put("email", emailBox.getText().toString());
                        parameters.put("password", passwordBox.getText().toString());
                        return parameters;
                    }
                };
 
                RequestQueue rQueue = Volley.newRequestQueue(Login.this);
                rQueue.add(request);
            }
        });
 
        registerLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Register.class));
            }
        });
    }
}

activity_login.xml

activity_login.xml

<?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:paddingBottom="20dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="20dp"
    tools:context="com.loginandregister.Login"
    android:orientation="vertical"
    android:gravity="center">
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:id="@+id/emailBox"/>
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:id="@+id/passwordBox"
        android:layout_marginTop="10dp"/>
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/loginButton"
        android:layout_marginTop="10dp"/>
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click here to register"
        android:textSize="20dp"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:id="@+id/registerLink"
        android:textColor="#0D47A1"/>
</LinearLayout>

Register.java

注册.java

package com.loginandregister;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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 java.util.HashMap;
import java.util.Map;
 
public class Register extends AppCompatActivity {
    EditText emailBox, passwordBox;
    Button registerButton;
    TextView loginLink;
    String URL = "http://192.168.1.8/JavaRESTfullWS/DemoService/register";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
 
        emailBox = (EditText)findViewById(R.id.emailBox);
        passwordBox = (EditText)findViewById(R.id.passwordBox);
        registerButton = (Button)findViewById(R.id.registerButton);
        loginLink = (TextView)findViewById(R.id.loginLink);
 
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        if(s.equals("true")){
                            Toast.makeText(Register.this, "Registration Successful", Toast.LENGTH_LONG).show();
                        }
                        else{
                            Toast.makeText(Register.this, "Can't Register", Toast.LENGTH_LONG).show();
                        }
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(Register.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parameters = new HashMap<String, String>();
                        parameters.put("email", emailBox.getText().toString());
                        parameters.put("password", passwordBox.getText().toString());
                        return parameters;
                    }
                };
 
                RequestQueue rQueue = Volley.newRequestQueue(Register.this);
                rQueue.add(request);
            }
        });
 
        loginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Register.this, Login.class));
            }
        });
    }
}

activity_register.xml

activity_register.xml

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.loginandregister.Register"
    android:orientation="vertical"
    android:gravity="center">
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:id="@+id/emailBox"/>
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:id="@+id/passwordBox"
        android:layout_marginTop="10dp"/>
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/registerButton"
        android:layout_marginTop="10dp"/>
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click here to login"
        android:textSize="20dp"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:id="@+id/loginLink"
        android:textColor="#0D47A1"/>
</LinearLayout>

Home.java

家.java

package com.loginandregister;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
public class Home extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
    }
}

activity_home.xml

activity_home.xml

<?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:paddingBottom="20dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="20dp"
    tools:context="com.loginandregister.Home"
    android:gravity="center">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="- Welcome -"
        android:textSize="30dp"
        android:gravity="center"/>
</LinearLayout>

Make sure the web service is already running on the server. Also change the IP 192.168.1.8 in the URL with the IPv4 of your local system. You can find the IPv4 in windows by typing ipconfig command in command prompt.

确保Web服务已在服务器上运行。 另外,使用本地系统的IPv4更改URL中的IP 192.168.1.8 。 通过在命令提示符下键入ipconfig命令,可以在Windows中找到IPv4。

Finally run and test the project.

最后运行并测试项目。

Screenshots

屏幕截图

login
register
home

The whole code is very simple and self-explanatory. If still you are facing any problem then feel free to ask in comment section.

整个代码非常简单,不言自明。 如果您仍然遇到任何问题,请随时在评论部分提问。

翻译自: https://www.thecrazyprogrammer.com/2016/09/android-login-register-using-restful-web-services-java-mysql.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值