Android Login Using JSP/Servlet


Android Login Using JSP/Servlet



CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`uname` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
);

INSERT INTO `users` (`id`,`uname`,`password`) VALUES
(1,'admin','123');

1. Servlet Project

Create a new Servlet Project and name it as AndroidLogin and create a LoginServlet.java class in package com.bari.login and copy the following code.

Note:
You must need the following two jars to be placed to the projects class path.
1. json-simple-1.1.1.jar
2. mysql-connector-java-5.xxx-bin.jar

LoginServlet.java


import dbConnection.DBConnectionHandler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Enumeration;
import org.json.simple.JSONObject;

public class LoginServlet extends HttpServlet {

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
JSONObject json = new JSONObject();


//ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
Enumeration paramNames = request.getParameterNames();
String params[] = new String[2];
int i = 0;
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();

//System.out.println(paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];

//System.out.println(params[i]);
i++;

}

String sql = "SELECT uname, password FROM users where uname=? and password=?";
Connection con = DBConnectionHandler.getConnection();

try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, params[0]);
ps.setString(2, params[1]);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
json.put("info", "success");
} else {
json.put("info", "fail");
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json.toString());
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}



Manage your database connection using the following class or any suitable way you prefer.
DBConnectionHandler.java


import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DBConnectionHandler {

Connection con = null;

public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "root", "pass");//mysql database

} catch (SQLException ex) {
Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
}

2. Android Project


activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<!-- View Title Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:text="LOGIN"
android:textSize="25dip"
android:textStyle="bold" />
<!-- User Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="User Name" />
<!-- User Name TextField -->
<EditText
android:id="@+id/txtUser"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<!-- Password Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Password" />
<!-- Password TextField -->
<EditText
android:id="@+id/txtPass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true" />

<!-- Login Button -->
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:text="Login" />
</LinearLayout>

</ScrollView>




activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:gravity="center"
android:text="WELCOME"
android:textSize="40dip" />

<Button
android:id="@+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dip"
android:background="@null"
android:text="Logout"
android:textColor="#21dbd4"
android:textSize="20dip"
android:textStyle="bold" />

</LinearLayout>


MainActivity.java

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
EditText uname, password;
Button submit;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();

JSONObject json;
private static String url_login = "http://192.168.2.2:8080/AndroidLogin/login_servlet";
//JSONArray incoming_msg = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
//and get output response from InputStream and return it.
new Login().execute();

}
});
}
private void findViewsById() {

uname = (EditText) findViewById(R.id.txtUser);
password = (EditText) findViewById(R.id.txtPass);
submit = (Button) findViewById(R.id.button1);
}
private class Login extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... args) {
// Getting username and password from user input
String username = uname.getText().toString();
String pass = password.getText().toString();

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("u",username));
params.add(new BasicNameValuePair("p",pass));
json = jParser.makeHttpRequest(url_login, "GET", params);
String s=null;

try {
s= json.getString("info");
Log.d("Msg", json.getString("info"));
if(s.equals("success")){
Intent login = new Intent(getApplicationContext(), Welcome.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}




Welcome.java


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Welcome extends Activity {
Button btnLogout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_home);
btnLogout = (Button) findViewById(R.id.btnLogout);

btnLogout.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
});

}
}



JSONParser.java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

static InputStream iStream = null;
static JSONArray jarray = null;
//static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
/////////////////////////////////
public JSONArray getJSONFromUrl(String url) {

StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

// Parse String to JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON Object
return jarray;

}


public JSONObject makeHttpRequest2(String url) {

// Making HTTP request
try {

// check for request method
//if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

// }else if(method == "GET"){
// // request method is GET
// DefaultHttpClient httpClient = new DefaultHttpClient();
// //String paramString = URLEncodedUtils.format(params, "utf-8");
// url += "?" + paramString;
// HttpGet httpGet = new HttpGet(url);
//
// HttpResponse httpResponse = httpClient.execute(httpGet);
// HttpEntity httpEntity = httpResponse.getEntity();
// is = httpEntity.getContent();
// }

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}



AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loginmysqlservlet"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Welcome"></activity>
</application>

</manifest>
I Am Not The Owner Of These Code .I Merely Have Copied Them From Various Sources. The Only Thing I Did Is That I Am Going To Present Them In More Easy Way To Understand.

Comments

Popular posts from this blog

LED Blinking using 8051 Microcontroller and Keil C – AT89C51

Android Camera Example 2

Java Script to make text change text color