// Parsing csv in j2ee
Step1 ;- Create a dynamic web project
Step2 :- Chang the content in the web.xml as given bellow
<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>CSVReader</servlet-name>
<servlet-class>web.prac.CSVReader</servlet-class>//our reader servlet
<init-param>
<param-name>jsp</param-name>
<param-value>/csvRenderer.jsp</param-value>//declarring the jsp to be loaded
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CSVReader</servlet-name>
<url-pattern>/CSVReader/*</url-pattern>
</servlet-mapping>
</web-app>
Step 3:- Create a bean which will store the data andparse the csv
/*
* Created on 25-Jan-2005
*
*/
package web.prac;
import java.util.*;
import java.io.*;
public class CSVBean {
private int rowCount; // Number of rows (excluding header row)
private int fieldCount; // Number of fields in each row
private String[] headers; // Field names (assumed to be in first row)
private List rows = new ArrayList(); // The data
public CSVBean() {
// Must have a no-argument constructor as a bean.
}
public void parseFile(File f) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
String line;
boolean firstRow = true;
try {
while ((line = br.readLine()) != null) {
if (firstRow) {
headers = tokenize(line);
setFieldCount(headers.length);
firstRow = false;
} else {
String[] row = tokenize(line);
rows.add(row);
rowCount++;
}
}
} catch (IOException e1) {
e1.printStackTrace();
return;
}
}
protected String[] tokenize(String line) {
StringTokenizer st = new StringTokenizer(line, ",");
int tokenCount = st.countTokens();
String[] record = new String[tokenCount];
for (int i = 0; i < tokenCount; i++) {
record[i] = (String) st.nextToken();
}
return record;
}
public int getFieldCount() {
return fieldCount;
}
public void setFieldCount(int fieldCount) {
this.fieldCount = fieldCount;
}
public String[] getHeaders() {
return headers;
}
public void setHeaders(String[] headers) {
this.headers = headers;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Headers: ");
addStringArray(headers, sb);
Iterator it = rows.iterator();
int rowCount = 0;
while (it.hasNext()) {
rowCount++;
sb.append("Row " + rowCount + ": ");
String[] row = (String []) it.next();
addStringArray(row, sb);
}
return sb.toString();
}
protected StringBuffer addStringArray(String[] array, StringBuffer buffer) {
for (int i = 0; i < array.length; i++) {
buffer.append(array[i] + ",");
}
buffer.append("\n");
return buffer;
}
}
Step 4 :- Now create the servletwhichcontrols the flow
package web.prac;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CSVReader extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getPathInfo();
ServletContext context = getServletContext();
String fullPath = context.getRealPath(path);
File f = new File(fullPath);
CSVBean csvBean = new CSVBean();
csvBean.parseFile(f);
request.setAttribute("csv", csvBean);
String jsp = getInitParameter("jsp");
RequestDispatcher rd = context.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}
Step5 :- Final output page displaying csv data using scripletes
<html><head><title>CSV File Renderer</title></head>
<jsp:useBean id="csv" scope="request" type="webcert.ch07.ex0703.CSVBean" />
<%@ page import="java.util.*" %>
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Syntax Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
rows of data, and
<jsp:getProperty name="csv" property="fieldCount" />
columns.</h3>
<table border="1">
<tr>
<th> </th>
<% String[] headers = csv.getHeaders();
for (int i = 0; i < headers.length; i++) { %>
<th><b><%= headers[i] %></b></th>
<% } %>
</tr>
<% List rows = csv.getRows();
Iterator it = rows.iterator();
int rowNumber=0;
while (it.hasNext()) {
%>
<tr>
<td>Row <%= ++rowNumber %></td>
<% String[] fields = (String[]) it.next();
for (int i = 0; i < fields.length; i++) { %>
<td><%= fields[i] %></td>
<% } %>
</tr>
<% } %>
</table>
</body></html>
Step6 :- Final output page displaying csv data usingjsp standard actions
<html xmlns:jsp="http://java.sun.com/JSP/Page" >
<head><title>CSV File Renderer</title></head>
<jsp:output omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html" />
<jsp:directive.page import="java.util.*" />
<jsp:useBean id="csv" scope="request" type="web.prac.CSVBean" />
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Document (XML) Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
rows of data, and
<jsp:getProperty name="csv" property="fieldCount" />
columns.</h3>
<table border="1">
<tr>
<th><![CDATA[ ]]></th>
<jsp:scriptlet> String[] headers = csv.getHeaders();
for (int i = 0; i < headers.length; i++) { </jsp:scriptlet>
<th><b><jsp:expression>headers[i]</jsp:expression></b></th>
<jsp:scriptlet>}</jsp:scriptlet>
</tr>
<jsp:scriptlet>List rows = csv.getRows();
Iterator it = rows.iterator();
int rowNumber=0;
while (it.hasNext()) {
</jsp:scriptlet>
<tr>
<td>Row <jsp:expression>++rowNumber</jsp:expression></td>
<jsp:scriptlet>String[] fields = (String[]) it.next();
for (int i = 0; i < fields.length; i++) { </jsp:scriptlet>
<td><jsp:expression>fields[i]</jsp:expression></td>
<jsp:scriptlet> } </jsp:scriptlet>
</tr>
<jsp:scriptlet> } </jsp:scriptlet>
</table>
</body></html>
Step1 ;- Create a dynamic web project
Step2 :- Chang the content in the web.xml as given bellow
<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>CSVReader</servlet-name>
<servlet-class>web.prac.CSVReader</servlet-class>//our reader servlet
<init-param>
<param-name>jsp</param-name>
<param-value>/csvRenderer.jsp</param-value>//declarring the jsp to be loaded
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CSVReader</servlet-name>
<url-pattern>/CSVReader/*</url-pattern>
</servlet-mapping>
</web-app>
Step 3:- Create a bean which will store the data andparse the csv
/*
* Created on 25-Jan-2005
*
*/
package web.prac;
import java.util.*;
import java.io.*;
public class CSVBean {
private int rowCount; // Number of rows (excluding header row)
private int fieldCount; // Number of fields in each row
private String[] headers; // Field names (assumed to be in first row)
private List rows = new ArrayList(); // The data
public CSVBean() {
// Must have a no-argument constructor as a bean.
}
public void parseFile(File f) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
String line;
boolean firstRow = true;
try {
while ((line = br.readLine()) != null) {
if (firstRow) {
headers = tokenize(line);
setFieldCount(headers.length);
firstRow = false;
} else {
String[] row = tokenize(line);
rows.add(row);
rowCount++;
}
}
} catch (IOException e1) {
e1.printStackTrace();
return;
}
}
protected String[] tokenize(String line) {
StringTokenizer st = new StringTokenizer(line, ",");
int tokenCount = st.countTokens();
String[] record = new String[tokenCount];
for (int i = 0; i < tokenCount; i++) {
record[i] = (String) st.nextToken();
}
return record;
}
public int getFieldCount() {
return fieldCount;
}
public void setFieldCount(int fieldCount) {
this.fieldCount = fieldCount;
}
public String[] getHeaders() {
return headers;
}
public void setHeaders(String[] headers) {
this.headers = headers;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Headers: ");
addStringArray(headers, sb);
Iterator it = rows.iterator();
int rowCount = 0;
while (it.hasNext()) {
rowCount++;
sb.append("Row " + rowCount + ": ");
String[] row = (String []) it.next();
addStringArray(row, sb);
}
return sb.toString();
}
protected StringBuffer addStringArray(String[] array, StringBuffer buffer) {
for (int i = 0; i < array.length; i++) {
buffer.append(array[i] + ",");
}
buffer.append("\n");
return buffer;
}
}
Step 4 :- Now create the servletwhichcontrols the flow
package web.prac;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CSVReader extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getPathInfo();
ServletContext context = getServletContext();
String fullPath = context.getRealPath(path);
File f = new File(fullPath);
CSVBean csvBean = new CSVBean();
csvBean.parseFile(f);
request.setAttribute("csv", csvBean);
String jsp = getInitParameter("jsp");
RequestDispatcher rd = context.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}
Step5 :- Final output page displaying csv data using scripletes
<html><head><title>CSV File Renderer</title></head>
<jsp:useBean id="csv" scope="request" type="webcert.ch07.ex0703.CSVBean" />
<%@ page import="java.util.*" %>
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Syntax Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
rows of data, and
<jsp:getProperty name="csv" property="fieldCount" />
columns.</h3>
<table border="1">
<tr>
<th> </th>
<% String[] headers = csv.getHeaders();
for (int i = 0; i < headers.length; i++) { %>
<th><b><%= headers[i] %></b></th>
<% } %>
</tr>
<% List rows = csv.getRows();
Iterator it = rows.iterator();
int rowNumber=0;
while (it.hasNext()) {
%>
<tr>
<td>Row <%= ++rowNumber %></td>
<% String[] fields = (String[]) it.next();
for (int i = 0; i < fields.length; i++) { %>
<td><%= fields[i] %></td>
<% } %>
</tr>
<% } %>
</table>
</body></html>
Step6 :- Final output page displaying csv data usingjsp standard actions
<html xmlns:jsp="http://java.sun.com/JSP/Page" >
<head><title>CSV File Renderer</title></head>
<jsp:output omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html" />
<jsp:directive.page import="java.util.*" />
<jsp:useBean id="csv" scope="request" type="web.prac.CSVBean" />
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Document (XML) Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
rows of data, and
<jsp:getProperty name="csv" property="fieldCount" />
columns.</h3>
<table border="1">
<tr>
<th><![CDATA[ ]]></th>
<jsp:scriptlet> String[] headers = csv.getHeaders();
for (int i = 0; i < headers.length; i++) { </jsp:scriptlet>
<th><b><jsp:expression>headers[i]</jsp:expression></b></th>
<jsp:scriptlet>}</jsp:scriptlet>
</tr>
<jsp:scriptlet>List rows = csv.getRows();
Iterator it = rows.iterator();
int rowNumber=0;
while (it.hasNext()) {
</jsp:scriptlet>
<tr>
<td>Row <jsp:expression>++rowNumber</jsp:expression></td>
<jsp:scriptlet>String[] fields = (String[]) it.next();
for (int i = 0; i < fields.length; i++) { </jsp:scriptlet>
<td><jsp:expression>fields[i]</jsp:expression></td>
<jsp:scriptlet> } </jsp:scriptlet>
</tr>
<jsp:scriptlet> } </jsp:scriptlet>
</table>
</body></html>
No comments:
Post a Comment