In the previous chapters we have completed everything from defining all ExtJs object and Java objects needed for the application except for our final step, create the servlet.
Tip: Make sure you download the json-lib-2.4-jdk15.jar in addition to your JDBC jar for this project. The jsob-lib helps in creating and parsing JSON objects.
Step 12: Define the Servlet - ItemMaintenance.java
package com.as400samplecode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
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;
import com.as400samplecode.util.Item;
import com.as400samplecode.util.ItemInformation;
public class ItemMaintenance extends HttpServlet {
private static final long serialVersionUID = 1L;
public ItemMaintenance() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get the company from the request
String company = request.getParameter("company");
//get out Grid paging toolbar parameters
String start = request.getParameter("start");
String limit = request.getParameter("limit");
//printwriter to send the JSON response back
PrintWriter out = response.getWriter();
//set content type
response.setContentType("text/html");
//create a new JSON array to send the list of items
JSONArray arrayObj=new JSONArray();
//get arraylist of items based on the request
ItemInformation itemInformation = new ItemInformation(company);
ArrayList<Item> itemList = itemInformation.getItems(start,limit);
//loop thru the array list to populate the JSON array
for(int i=0;i<itemList.size();i++){
//get item Object
Item item = itemList.get(i);
//this creates a JSON object from bean object
JSONObject itemObj = JSONObject.fromObject(item);
//add to array list
arrayObj.add(itemObj);
}
//Create a JSON object to wrap your JSOn array and provide the root element items
JSONObject myObj = new JSONObject();
//sets success to true
myObj.put("success", true);
//set the JSON root to items
myObj.put("items", arrayObj);
//set the total number of Items
myObj.put("totalCount", itemInformation.getTotalCount());
//convert the JSON object to string and send the response back
out.println(myObj.toString());
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get the company from the request
String company = request.getParameter("company");
//the addData has item information during add otherwise null
String addData = request.getParameter("addData");
boolean add = false;
//get payload from request body
String payLoad = getBody(request);
//in case of a ADD use the addData information instead of payLoad
if(addData != null){
add = true;
payLoad = addData;
}
System.out.println("Payload:" + payLoad);
ArrayList<Item> itemList = new ArrayList<Item>();
//If the payload is not a single JSON object then parse the array
//and create the the item arraylist
if(payLoad.startsWith("[")){
JSONArray arrayObj = JSONArray.fromObject(payLoad);
for (int i = 0; i < arrayObj.size(); ++i) {
JSONObject itemObj = arrayObj.getJSONObject(i);
//parse JSON populate the Item bean
Item item = (Item) JSONObject.toBean(itemObj, Item.class);
itemList.add(item);
}
}
//parse the single JSON object and put that in the item arraylist
else {
JSONObject itemObj = (JSONObject) JSONSerializer.toJSON(payLoad);
//parse JSON populate the Item bean
Item item = (Item) JSONObject.toBean(itemObj, Item.class);
itemList.add(item);
}
ItemInformation itemInformation = new ItemInformation(company);
boolean success = false;
if(add){
//add the item information
success = itemInformation.addItems(itemList);
}
else {
//update the item information
success = itemInformation.updateItems(itemList);
}
PrintWriter out = response.getWriter();
response.setContentType("text/html");
//send response whether the request to add or update was successful
JSONObject myObj = new JSONObject();
myObj.put("success", success);
out.println(myObj.toString());
out.close();
}
//Get JSON payLoad from the request body
private String getBody(HttpServletRequest request) throws IOException{
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}
}
Click here for next Chapter
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.