jqGrid + Servlet

Hello all, one of my fiend has a requirement to generate a data grid model so, we thought directly using jqGrid component here is my tutorial which will populate data in grid format.
Step 1: jqGrid will call servlet using an Ajax call.
Step 2: Servlet returns data in the form of JSON.
Step 3: jqGrid Component will parse JSON data from servlet and render it in the component.
Step 4: giving additional functionality as “add,edit,delete” directly to jqGrid component.
prj_structure

lets start looking at the logic
GridServlet.java

package com.spark.javaee.servlets;

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.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 * Servlet implementation class LoginServlet
 */
public class GridServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		GridModel gridModel1 = new GridModel();
		gridModel1.setId(1);
		gridModel1.setFirstName("PavanKumar");
		gridModel1.setLastName("Mantha");
		gridModel1.setCity("Hyderabad");
		gridModel1.setState("AndhraPradesh");
		gridModel1.setPhoneNumber("1234567890");
		
		GridModel gridModel2 = new GridModel();
		gridModel2.setId(2);
		gridModel2.setFirstName("PavanKumar");
		gridModel2.setLastName("Mantha");
		gridModel2.setCity("Hyderabad");
		gridModel2.setState("AndhraPradesh");
		gridModel2.setPhoneNumber("1234567890");
		
		List<GridModel> gridModels = new ArrayList<>();
		gridModels.add(gridModel1);
		gridModels.add(gridModel2);
		
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(gridModels);
		String json = "{'page':1,'total':'2','records':'1','rows':"+jsonArray+"}";
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(json);
		
		PrintWriter out = response.getWriter();
		out.print(jsonObject.toString());
	}

}

Lets look at the model class
GridModel.java

/**
 * 
 */
package com.spark.javaee.servlets;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class GridModel implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String city;
	private String State;
	private String phoneNumber;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

	/**
	 * @return the state
	 */
	public String getState() {
		return State;
	}

	/**
	 * @param state
	 *            the state to set
	 */
	public void setState(String state) {
		State = state;
	}

	/**
	 * @return the phoneNumber
	 */
	public String getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}

now its time to look at jsp

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>jqGird Demo</title>
<link rel="stylesheet"
	href="assets/themes/redmond/jquery.ui.all.css">

<script src="assets/js/jquery-1.8.0.min.js"></script>
<script src="assets/ui/jquery.ui.core.js"></script>
<script src="assets/ui/jquery.ui.widget.js"></script>
<script src="assets/ui/jquery.ui.datepicker.js"></script>
<script src="assets/js/grid.locale-en.js"></script>
<script src="assets/js/jquery.jqGrid.src.js"></script>
<script src="assets/js/jquery-ui-1.8.23.custom.min.js"></script>
<script src="assets/js/json2.js"></script>


<link rel="stylesheet" href="assets/demos.css">
<link rel="stylesheet" href="assets/ui.jqgrid.css">
<script src="js/getGridData.js"></script>
</head>
<body>
	<table id="list">
		<tr>
			<td />
		</tr>
	</table>
	<div id="pager"></div>
</body>
</html>

lets look at the javascript

/**
 * Code for JQuery Grid.
 */
$(document)
		.ready(
				function() {
					$("#list")
							.jqGrid(
									{
										url : 'http://localhost:8080/JQueryTest/GridServlet',
										datatype : 'json',
										mtype : 'POST',
										colNames : [ 'id', 'firstName',
												'lastName', 'city', 'state',
												'phoneNumber' ],
										colModel : [ {
											name : 'id',
											index : 'id',
											width : 100
										}, {
											name : 'firstName',
											index : 'firstName',
											width : 150,
											editable : true
										}, {
											name : 'lastName',
											index : 'lastName',
											width : 150,
											editable : true
										}, {
											name : 'city',
											index : 'city',
											width : 80,
											editable : true
										}, {
											name : 'state',
											index : 'state',
											width : 100,
											editable : true
										}, {
											name : 'phoneNumber',
											index : 'phoneNumber',
											width : 80,
											editable : true
										} ],
										pager : '#pager',
										rowNum : 10,
										rowList : [ 10, 20, 30 ],
										sortname : 'invid',
										sortorder : 'desc',
										viewrecords : true,
										gridview : true,
										caption : 'Data Report',
										jsonReader : {
											repeatitems : false,
										},
										editurl : "http://localhost:8080/JQueryTest/GridServlet"
									});
					jQuery("#list").jqGrid('navGrid', '#pager', {
						edit : true,
						add : true,
						del : true,
						search : true
					});
				});


This is how the result looks by loading data
load

This is how the result looks after clicking add button and the request:
request

This is how the result looks after clicking edit button and the request:
edit

Happy Coding 🙂

Calling a remote Servlet using Android Activity.

Hi all, in the past i received some queries regarding “how to call EJB from Android?”, at that time i am not sure but i just replied by saying call a servlet from your Android and its the servlet that internally calls EJB, Yes its true there is no direct implementation to call EJB from Android but we can call a servlet from Android and from there its your logic to call any business components like EJB,etc. following is my tutorial which will take you how to call Servlet from Android
Note:This tutorial will create Servlets with specification 3.0 with no web.xml and uses annotations to map the requests from client.

1.Create a dynamic web project with servlet specification 3.0 and create a servlet in src folder of your project as shown below.
2.Deploy the servlet in local server(Apache-tomcat 7.x) and test the working by hitting the below url http://localhost:8080/AndroidServlet/androidServlet

package com.spark.android.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AndroidServlet
 * @author Mantha Pavan Kumar
 */
@WebServlet("/androidServlet")
public class AndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AndroidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Sample Page !");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Now its time to create android project(using Eclipse), Assuming all the prerequisites of android are already installed in your environment lets start the project.

3.create Android Application project
4.In the main.xml file add the below content

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button" />

    <TextView
        android:id="@+id/outputTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#CC0033"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

5. in res/values/strings.xml add the below content

<resources>

    <string name="app_name">SimpleHttpGetServlet</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
	<string name="button">Invoke Servlet</string>
</resources>

6.Now in the MainActivity.java place the below content

package com.example.simplehttpgetservlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
    Button button;
    TextView outputText;
 
    public static final String URL = "http://10.40.230.98:8080/AndroidServlet/androidServlet";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        findViewsById();
 
        button.setOnClickListener(this);
    }
 
    private void findViewsById() {
        button = (Button) findViewById(R.id.button);
        outputText = (TextView) findViewById(R.id.outputTxt);
    }
 
    public void onClick(View view) {
        GetXMLTask task = new GetXMLTask();
        task.execute(new String[] { URL });
    }
 
    private class GetXMLTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String output = null;
            for (String url : urls) {
                output = getOutputFromUrl(url);
            }
            return output;
        }
 
        private String getOutputFromUrl(String url) {
            String output = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                output = EntityUtils.toString(httpEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return output;
        }
 
        @Override
        protected void onPostExecute(String output) {
            outputText.setText(output);
        }
    }
}

7.Finally we give persmissions to our android app to access internet in the AndroidManifest.xml as below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplehttpgetservlet"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

</manifest>

Thats it launch your AVD by running the Android project and click the button, you will see the response from servlet.
Happy coding 🙂