Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, 10 September 2014

Simple AJAX example in JSP/Servlet

AJAX (Asynchronous JavaScript and XML) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object.

AJAX comes to your rescue when there is only a small amount of data that needs to be updated on a page already loaded and rest of data remains the same. In such case you need not reload the whole page, rather you would go with the reload of specific data.

Here is the example of how Ajax can be used in JSP and Servlets:

index.jsp

<%@ 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>My Page</title>

<script type="text/javascript">


function getXMLObject()  //XML Object

{
var xmlHttp = false;

    try {

      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  // For Old Microsoft Browsers
}
    catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  // For Microsoft IE 6.0+
      }
      catch (e2) {
        xmlHttp = false;   // No Browser accepts the XMLHTTP Object then false
      }
    }
   
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
      xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
    }
   
    return xmlHttp;  // Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject();    //xmlhttp holds the ajax object


function getEmployeeDetails() {

if(xmlhttp) {  
var empId = document.getElementById("empId").value;
xmlhttp.open("POST","EmployeeDetails?"+"empId="+empId,true);
  xmlhttp.onreadystatechange  = responseHandler;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}

function responseHandler() {

if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.frm.txtarea.value=xmlhttp.responseText;      
      }else {
        alert("Error occured while AJAX call..... Please try again.....");
      }
    }
}
</script>

</head>

<body>
<form name="frm">
<table width="100%">
<tr style="width: 100%;">
<td style="padding-left: 40px;  padding-top: 10px; padding-bottom: 10px">Employee Id ::   
<input type="text" id="empId" style="width: 150px">
   
<a style="padding-right: 40px;">
<input style="background-color:#092A6B;color:#FFFFFF;width: 150px ;font-size: 15; cursor: pointer;" type="button" value="Retrieve Details" onClick="getEmployeeDetails();">
</a>
</td>
</tr>
<tr style="width: 100%;">
<td style="padding-left: 30px; padding-bottom: 10px">
<textarea name="txtarea" style="width: 670px; height: 100px;"></textarea>
</td>
</tr>
</table>
</form>
</body>
</html>



EmployeeDetails.java

package com.shakeel;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**

 * Servlet implementation class EmployeeDetails
 */
public class EmployeeDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

/**

* @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 {

PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String empId = request.getParameter("empId");
String result = "";

if(empId.equalsIgnoreCase("E100")){
result = " Name: Shaan \n Address: Bangalore \n Role: Programmer";
}else if(empId.equalsIgnoreCase("E101")){
result = " Name: Shakeel \n Address: San Francisco \n Role: Lead";
}else{
result = " Employee Id does't exist.... Please try some other Employee Id...";
}

out.println(result);
}


}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxExample</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>

    <description></description>
    <display-name>EmployeeDetails</display-name>
    <servlet-name>EmployeeDetails</servlet-name>
    <servlet-class>com.shakeel.EmployeeDetails</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeDetails</servlet-name>
    <url-pattern>/EmployeeDetails</url-pattern>
  </servlet-mapping>

</web-app>



Output




I hope this example would have helped you in understanding of how exactly AJAX calls are made and the result is retrieved.





Running a Unix script from JSP/Servlet

In this example we are going to see how a UNIX script can be called from a JSP page and the result of the UNIX script is displayed back at the JSP page.

Here is the example illustrating the same:

index.jsp

<%@ 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>My Page</title>

<script type="text/javascript">

function getXMLObject()
{
var xmlHttp = false; 
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
}
    catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e2) {
        xmlHttp = false;
      }
    }
   
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
      xmlHttp = new XMLHttpRequest();   
    }   
    return xmlHttp; 
}

var xmlhttp = new getXMLObject(); 

function getStudentDetails() {
if(xmlhttp) {  
var studentId = document.getElementById("studentId").value;
xmlhttp.open("POST","StudentDetails?"+"studentId="+studentId,true);
  xmlhttp.onreadystatechange  = responseHandler;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}

function responseHandler() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.frm.txtarea.value=xmlhttp.responseText;      
      }else {
        alert("Error occured while AJAX call..... Please try again.....");
      }
    }
}
</script>

</head>
<body>
<form name="frm">

<table width="100%">
<tr style="width: 100%;">
<td style="padding-left: 40px;  padding-top: 10px; padding-bottom: 10px">Student Id ::   
<input type="text" id="studentId" style="width: 150px">
   
<a style="padding-right: 40px;">
<input style="background-color:#092A6B;color:#FFFFFF;width: 150px ;font-size: 15; cursor: pointer;" type="button" value="Retrieve Details" onClick="getStudentDetails();">
</a>
</td>
</tr>
<tr style="width: 100%;">
<td style="padding-left: 30px; padding-bottom: 10px">
<textarea name="txtarea" style="width: 670px; height: 100px;"></textarea>
</td>
</tr>
</table>
</form>
</body>

</html>


StudentDetails.java

package com.shakeel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class StudentDetails
 */
public class StudentDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String studentId = request.getParameter("studentId");
System.out.println(studentId);

String command = "sh getDetails.sh "+studentId; // UNIX command to be executed with parameter paased
out.println(executeCommand(command));
}

BufferedWriter bw = null;
private String executeCommand(String command) throws IOException {
 
StringBuffer output = new StringBuffer();

Process p;
try {
p = Runtime.getRuntime().exec(command); // Process to execute UNIX command 
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

File fout = new File("out.txt");
FileOutputStream fos = new FileOutputStream(fout);
 
bw = new BufferedWriter(new OutputStreamWriter(fos));
            String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
bw.write(line);
bw.newLine();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
bw.close();
}
return output.toString();
}

}



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>UnixCall</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <description></description>
    <display-name>StudentDetails</display-name>
    <servlet-name>StudentDetails</servlet-name>
    <servlet-class>com.shakeel.StudentDetails</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentDetails</servlet-name>
    <url-pattern>/StudentDetails</url-pattern>
  </servlet-mapping>
</web-app>


I hope this example would have given you an idea on how to call a UNIX script from Java.

Monday, 23 September 2013

Writing into Excel file using JExcel API

In this post we will learn how to write data into Excel sheet using JExcel API.

Below is Java code for writing the data into excel sheet:

WriteExcel.java
package com.technsolution;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class WriteExcel {
  private WritableCellFormat timesBold;
  private WritableCellFormat times;
  private String outputFile;
  
  String [] name = {"Rahul","Kiran","Shweta","Raj","Sahil"};
  int [] marks = {87,98,89,87,90};
  
  public static void main(String[] args) throws IOException, WriteException {
 WriteExcel we = new WriteExcel();
 we.setOutputFile("D:/Output.xls");//Location of output file
 we.write();
  }
  
  public void setOutputFile(String outputFile) {
 this.outputFile = outputFile;
  }

  public void write() throws IOException, WriteException {
    
 File file = new File(outputFile);
 WorkbookSettings wbSettings = new WorkbookSettings();

 wbSettings.setLocale(new Locale("en", "EN"));

 WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);//creating workbook
 workbook.createSheet("Report", 0);//creating the first sheet of the workbook
 WritableSheet excelSheet = workbook.getSheet(0);
 createLabel(excelSheet);
 createContent(excelSheet,name,marks);

 workbook.write();
 workbook.close();
  }

  private void createLabel(WritableSheet sheet) throws WriteException {
 // Lets create a times font
 WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
 // Define the cell format
 times = new WritableCellFormat(times10pt);
   
 // Create a bold font
 WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
 UnderlineStyle.NO_UNDERLINE);
 timesBold = new WritableCellFormat(times10ptBoldUnderline);
 // Lets automatically wrap the cells
 timesBold.setWrap(true);

 CellView cv = new CellView();
 cv.setFormat(times);
 cv.setFormat(timesBold);

 // Write a few headers
 addCaption(sheet, 0, 0, "Names");
 addCaption(sheet, 1, 0, "Marks");
  }

  //Method for adding data to the columns
  private void createContent(WritableSheet sheet, String[] names, int[] marks) throws WriteException,
      RowsExceededException {
 
 for (int i = 1; i <= names.length; i++) {
 // First column
 addLabel(sheet, 0, i, names[i-1]);
 // Second column
 addNumber(sheet, 1, i, marks[i-1]);
 }
  }
  
  //Method for adding Headers of the columns
  private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
 Label label;
 label = new Label(column, row, s, timesBold);
 sheet.addCell(label);
  }  

  //Method for adding string values to excel sheet
  private void addLabel(WritableSheet sheet, int column, int row, String s)
throws WriteException, RowsExceededException {
 Label label;
 label = new Label(column, row, s, times);
 sheet.addCell(label);
  }

  //Method for adding numeric values to excel sheet
  private void addNumber(WritableSheet sheet, int column, int row, int num)
throws WriteException, RowsExceededException {
 Number number;
 number = new  Number(column, row, num, times);
 sheet.addCell(number);
  }
} 

Here is the output file generated by the above java file:

Output.xls





To use the JExcel API we need to add jxl-2.6.jar which contains all the classes required for reading and writing so don't forget to include it in the project build path.

Sunday, 8 September 2013

Reading data from Excel file in Java using JExcel API

In this post we will learn how to read data from Excel file in Java.




Java provides an API for reading the data from excel sheet and it is called JExcel API. Java Excel API is a mature, open source java API enabling developers to read, write, and modify Excel spreadsheets dynamically. 

Here is the excel sheet data which we are going to use for reading:

Example.xls


Below is Java code for reading data, here we have tried to read 3 types of data from excel sheet i.e. String, Number and Date using LabelCell, NumberCell and DateCell:

ReadExcel.java
package com.technsolution;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Cell;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {

  private String inputFile;

  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w = null;
    List<String> nameRowList = null;
    List<Double> marksRowList = null;
    List<Date> dateRowList = null;
    LabelCell lc;//for cell having String data
    NumberCell nc;//for cell having Numeric data
    DateCell dc;//for cell having date
    
    try {
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);

      // Loop over columns  
      for (int j = 0; j < sheet.getColumns(); j++) {
     Cell cell = sheet.getCell(j, 0);
     System.out.println("\n"+"Column Name => "+cell.getContents());//To print column values
     
     if(cell.getContents().equalsIgnoreCase("Name")){
     nameRowList = new ArrayList<String>();
     // Loop over rows
     for (int i = 0; i < sheet.getRows()-1; i++) {
     Cell styleColorVal = sheet.getCell(j, i+1);
     lc = (LabelCell)styleColorVal;
     nameRowList.add(i, lc.getString());
     System.out.println(cell.getContents()+(i+1)+" :: "+nameRowList.get(i).toString()); //To print the row values for Name column
     }      
     }
     
     if(cell.getContents().equalsIgnoreCase("Marks")){
     marksRowList = new ArrayList<Double>();
     // Loop over rows
     for (int i = 0; i < sheet.getRows()-1; i++) {
     Cell styleColorVal = sheet.getCell(j, i+1);
     nc = (NumberCell)styleColorVal;
     marksRowList.add(i, nc.getValue());
     System.out.println(cell.getContents()+(i+1)+" :: "+marksRowList.get(i).toString()); //To print the row values for Marks column
     }      
     }
     
     if(cell.getContents().equalsIgnoreCase("Date")){
     dateRowList = new ArrayList<Date>();
     // Loop over rows
     for (int i = 0; i < sheet.getRows()-1; i++) {
     Cell styleColorVal = sheet.getCell(j, i+1);
     dc = (DateCell)styleColorVal;
     dateRowList.add(i, dc.getDate());
     System.out.println(cell.getContents()+(i+1)+" :: "+dateRowList.get(i).toString()); //To print the row values for Date column
     }      
     }
         
     
      }
    } catch (BiffException e) {
    e.printStackTrace();
    } catch (Exception ex){
    ex.printStackTrace();
    }finally{
    w.close();
    }
  }

  public static void main(String[] args) throws IOException {
    ReadExcel rd = new ReadExcel();
    rd.setInputFile("D:/Example.xls");
    rd.read();
  } 


OUTPUT

Column Name => Name
Name1 :: Rahul
Name2 :: Kiran
Name3 :: Shweta
Name4 :: Raj
Name5 :: Sahil

Column Name => Marks
Marks1 :: 87.0
Marks2 :: 98.0
Marks3 :: 89.0
Marks4 :: 87.0
Marks5 :: 90.0

Column Name => Date
Date1 :: Thu Dec 20 05:30:00 IST 2012
Date2 :: Tue Aug 20 05:30:00 IST 2013
Date3 :: Sat Mar 20 05:30:00 IST 2010
Date4 :: Wed Jun 20 05:30:00 IST 2012
Date5 :: Mon Feb 20 05:30:00 IST 2012


To use the JExcel API we need to add jxl-2.6.jar which contains all the classes required for reading and writing so don't forget to include it in the project build path.

[Note: JExcel API works with Excel file having extension .xls only and not with .xlsx]