SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Maven + JSF + RichFaces + JDBC +
JXL API for Excel Export
(Using Maven Project in Eclipse IDE)
Create New Maven Project
Create a new simple Maven Project in Eclipse. You can search the docmentation for the same online.
Create pom.xml (replace XXXX with your desired value)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.XXXX</groupId>
<artifactId>XXXX</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>XXXX</name>
<description>XXXX </description>
<properties>
<org.richfaces.bom.version>4.3.3.Final</org.richfaces.bom.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.richfaces</groupId>
<artifactId>richfaces-bom</artifactId>
<version>${org.richfaces.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.richfaces.ui</groupId>
<artifactId>richfaces-components-ui</artifactId>
</dependency>
<dependency>
<groupId>org.richfaces.core</groupId>
<artifactId>richfaces-core-impl</artifactId>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>javax.faces-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/test/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<excludes>
<exclude>**/*local.properties</exclude>
</excludes>
</resource>
<resource>
<directory>srcmainresources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.vm</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>srcmainwebappWEB-INF</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0</version>
<configuration>
<server>devserver</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>srcmainwebappWEB-INFweb.xml</webXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
This should automatically start downloading maven jar files related to the
pom.xml entries. If not, then
1) right click on project from project explorer
2) select Run As -> Maven Install
web.xml (replace XXXX with your desired value)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<description>XXXX</description>
<display-name>XXXX</display-name>
<context-param>
<param-name>com.sun.faces.sendPoweredByHeader</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.disableUnicodeEscaping</param-name>
<param-value>auto</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.externalizeJavaScript</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.enableControlSkinning</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.resourceOptimization.enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>blueSky</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.faces</welcome-file>
</welcome-file-list>
</web-app>
FacesServlet related Error
This step is a must to avoid javax.faces.webapp.FacesServlet related errors.
1) Right click on Project
2) Select Deployment Assembly
3) Add Maven Dependiencies directive
Maven Update, Clean and Install
1) Right click on Project from project explorer
2) Select Maven-> Update Project
3) Right click on project from project explorer
4) select Run As -> Maven Clean
5) Right click on project from project explorer
6) select Run As -> Maven Install
faces-config.xml (put your details at XXXX)
<faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
<managed-bean>
<managed-bean-name>baseUIController</managed-bean-name>
<managed-bean-class>XXXX.ui.BaseUIController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>dbConnectionController</managed-bean-name>
<managed-bean-class>XXXX.database.DbConnectionController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>registeredUsersUIController</managed-bean-name>
<managed-bean-class>XXXX.ui.RegisteredUsersUIController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>dbConnectionController</property-name>
<value>#{dbConnectionController}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<navigation-case>
<from-outcome>index</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
<navigation-rule>
<navigation-case>
<from-outcome>registeredUsersReport</from-outcome>
<to-view-id>/registeredUsersReport.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
</faces-config>
DbConnectionController.java
It is always advisable to create a seperate controller class for storing database connection details. In entire project, only
this file should have hard coded database connection details so that in case of changing the connection details, only
one file needs to be modified.
package XXXX.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DbConnectionController {
Connection conn;
Statement stmt;
DriverManager driverManager;
public DbConnectionController() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DB_NAME", "DB_USER",
"DB_PASSWD");
stmt = conn.createStatement();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public Statement getStmt() {
return stmt;
}
public void setStmt(Statement stmt) {
this.stmt = stmt;
}
public DriverManager getDriverManager() {
return driverManager;
}
public void setDriverManager(DriverManager driverManager) {
this.driverManager = driverManager;
}
}
ApplicationConstants.java
Store standard error messages, file names etc in this file. Don't use file names anywhere in the project explicitely. This file
should be the only file where you should be able to update file names (apart from faces-config.xml)
package XXXX.constants;
public class ApplicationConstants {
public static final String ERROR_STRING = "There is some error executing the database query. Go to home page and
please try again.";
public static final String HOME_PAGE = "index";
public static final String REGISTERED_USERS = "registeredUsersReport";
public static final String REGISTERED_USERS_EXCEL = "registeredUsersReport.xls";
}
RegisteredUsersTO.java
Use a transfer object as resultset. This List of these objects will store the data retrieved from the database. This is a
standard coding practice.
package XXXX.resultsets;
import java.util.Date;
public class RegisteredUsersTO {
String firstName;
String lastName;
String emailAddress;
String addressLine1;
String addressLine2;
String country;
String state;
String city;
String pinCode;
Date dateOfBirth;
String gender;
/**
* @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 emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* @param emailAddress the emailAddress to set
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/**
* @return the addressLine1
*/
public String getAddressLine1() {
return addressLine1;
}
/**
* @param addressLine1 the addressLine1 to set
*/
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
/**
* @return the addressLine2
*/
public String getAddressLine2() {
return addressLine2;
}
/**
* @param addressLine2 the addressLine2 to set
*/
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the pinCode
*/
public String getPinCode() {
return pinCode;
}
/**
* @param pinCode the pinCode to set
*/
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
/**
* @return the dateOfBirth
*/
public Date getDateOfBirth() {
return dateOfBirth;
}
/**
* @param dateOfBirth the dateOfBirth to set
*/
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
}
BaseUIController.java
You can store all common methods/procedures which all controller classes will access under this class. Controller classes
will inherit this class.
package XXXX.ui;
import java.io.Serializable;
import javax.faces.context.FacesContext;
public class BaseUIController implements Serializable {
private static final long serialVersionUID = 1L;
private static final String appVersion = "1.0";
public String getRealFileStoragePath() {
return FacesContext.getCurrentInstance().getExternalContext()
.getRealPath("/");
}
}
RegisteredUsersUIController.java
package XXXX.ui;
import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.faces.application.FacesMessage;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import XXXX.constants.ApplicationConstants;
import XXXX.database.DbConnectionController;
import XXXX.resultsets.RegisteredUsersTO;
public class RegisteredUsersUIController extends BaseUIController {
private static final long serialVersionUID = 1L;
List<RegisteredUsersTO> registeredUsersTOList;
DbConnectionController dbConnectionController;
ResultSet resultSet;
String excelFile;
public String getRegisteredUsers()
{
dbConnectionController = new DbConnectionController();
this.registeredUsersTOList = new ArrayList<RegisteredUsersTO>();
String query = "SELECT FIRST_NAME, LAST_NAME, EMAIL_ADDRESS, ADDR_LINE_1, ADDR_LINE_2,"
+ " PIN_CODE, CITY_NAME, STATE_NAME, COUNTRY_NAME, DATE_OF_BIRTH, GENDER"
+ " FROM USER INNER JOIN USER_DETAILS ON USER.USER_ID=USER_DETAILS.USER_ID"
+ " INNER JOIN COUNTRY ON USER_DETAILS.COUNTRY_CODE=COUNTRY.COUNTRY_CODE";
try {
resultSet = dbConnectionController.getStmt().executeQuery(query);
while (resultSet.next()) {
RegisteredUsersTO registeredUsersTO = new RegisteredUsersTO();
registeredUsersTO.setFirstName(resultSet
.getString("FIRST_NAME"));
registeredUsersTO.setLastName(resultSet
.getString("LAST_NAME"));
registeredUsersTO.setEmailAddress(resultSet
.getString("EMAIL_ADDRESS"));
registeredUsersTO.setAddressLine1(resultSet
.getString("ADDR_LINE_1"));
registeredUsersTO.setAddressLine2(resultSet
.getString("ADDR_LINE_2"));
registeredUsersTO.setPinCode(resultSet
.getString("PIN_CODE"));
registeredUsersTO.setCity(resultSet
.getString("CITY_NAME"));
registeredUsersTO.setState(resultSet
.getString("STATE_NAME"));
registeredUsersTO.setCountry(resultSet
.getString("COUNTRY_NAME"));
registeredUsersTO.setDateOfBirth(resultSet
.getDate("DATE_OF_BIRTH"));
registeredUsersTO.setGender(resultSet
.getString("GENDER"));
registeredUsersTOList.add(registeredUsersTO);
}
this.excelFile = ApplicationConstants.REGISTERED_USERS_EXCEL;
exportToExcel();
return ApplicationConstants.REGISTERED_USERS;
} catch (Exception e) {
addFacesMessage(FacesMessage.SEVERITY_ERROR,
ApplicationConstants.ERROR_STRING);
e.printStackTrace();
return null;
}
}
public void exportToExcel() {
try {
File file = new File(getRealFileStoragePath() + excelFile);
int rowcntr = 2;
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file,
wbSettings);
workbook.createSheet(
"Registered Users",
0);
WritableSheet excelSheet = workbook.getSheet(0);
excelSheet.addCell(new Label(0, 1, "FIRST NAME"));
excelSheet.addCell(new Label(1, 1, "LAST NAME"));
excelSheet.addCell(new Label(2, 1, "EMAIL ADDRESS"));
excelSheet.addCell(new Label(3, 1, "ADDRESS LINE 1"));
excelSheet.addCell(new Label(4, 1, "ADDRESS LINE 2"));
excelSheet.addCell(new Label(5, 1, "PIN CODE"));
excelSheet.addCell(new Label(6, 1, "CITY"));
excelSheet.addCell(new Label(7, 1, "STATE"));
excelSheet.addCell(new Label(8, 1, "COUNTRY"));
excelSheet.addCell(new Label(9, 1, "DATE OF BIRTH"));
excelSheet.addCell(new Label(10, 1, "GENDER"));
for (RegisteredUsersTO registeredUsersTO : registeredUsersTOList) {
excelSheet.addCell(new Label(0, rowcntr, registeredUsersTO.getFirstName()));
excelSheet.addCell(new Label(1, rowcntr, registeredUsersTO.getLastName()));
excelSheet.addCell(new Label(2, rowcntr, registeredUsersTO.getEmailAddress()));
excelSheet.addCell(new Label(3, rowcntr, registeredUsersTO.getAddressLine1()));
excelSheet.addCell(new Label(4, rowcntr, registeredUsersTO.getAddressLine2()));
excelSheet.addCell(new Label(5, rowcntr, registeredUsersTO.getPinCode()));
excelSheet.addCell(new Label(6, rowcntr, registeredUsersTO.getCity()));
excelSheet.addCell(new Label(7, rowcntr, registeredUsersTO.getState()));
excelSheet.addCell(new Label(8, rowcntr, registeredUsersTO.getCountry()));
excelSheet.addCell(new Label(9, rowcntr, String.valueOf(registeredUsersTO.getDateOfBirth())));
excelSheet.addCell(new Label(10, rowcntr, registeredUsersTO.getGender()));
rowcntr++;
}
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
addFacesMessage(FacesMessage.SEVERITY_ERROR,
ApplicationConstants.ERROR_STRING);
}
}
public String goToHome() {
try {
resultSet.close();
dbConnectionController.setStmt(null);
dbConnectionController.setConn(null);
dbConnectionController = null;
this.registeredUsersTOList = null;
this.resultSet = null;
this.excelFile = null;
return ApplicationConstants.HOME_PAGE;
} catch (Exception e) {
addFacesMessage(FacesMessage.SEVERITY_ERROR,
ApplicationConstants.ERROR_STRING);
return null;
}
}
/**
* @return the registeredUsersTOList
*/
public List<RegisteredUsersTO> getRegisteredUsersTOList() {
return registeredUsersTOList;
}
/**
* @param registeredUsersTOList the registeredUsersTOList to set
*/
public void setRegisteredUsersTOList(
List<RegisteredUsersTO> registeredUsersTOList) {
this.registeredUsersTOList = registeredUsersTOList;
}
/**
* @return the dbConnectionController
*/
public DbConnectionController getDbConnectionController() {
return dbConnectionController;
}
/**
* @param dbConnectionController the dbConnectionController to set
*/
public void setDbConnectionController(
DbConnectionController dbConnectionController) {
this.dbConnectionController = dbConnectionController;
}
/**
* @return the resultSet
*/
public ResultSet getResultSet() {
return resultSet;
}
/**
* @param resultSet the resultSet to set
*/
public void setResultSet(ResultSet resultSet) {
this.resultSet = resultSet;
}
/**
* @return the excelFile
*/
public String getExcelFile() {
return excelFile;
}
/**
* @param excelFile the excelFile to set
*/
public void setExcelFile(String excelFile) {
this.excelFile = excelFile;
}
}
registeredUsersReport.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:form>
<div style="float: left; margin-left: 235px; margin-bottom: 5px;">
<br /> <br />
<h2>List of Registered Users of Website</h2>
<rich:dataTable id="registeredUsersDataTable" var="registeredUsrs"
style="width:960px;" rows="20"
value="#{registeredUsersUIController.registeredUsersTOList}"
rendered="#{not empty registeredUsersUIController.registeredUsersTOList}">
<f:facet name="header">
<rich:columnGroup>
<rich:column>
<h:outputText value="Name" />
</rich:column>
<rich:column>
<h:outputText value="Email Address" />
</rich:column>
<rich:column>
<h:outputText value="Complete Address" />
</rich:column>
<rich:column>
<h:outputText value="Country" />
</rich:column>
<rich:column>
<h:outputText value="Date of Birth" />
</rich:column>
<rich:column>
<h:outputText value="Gender" />
</rich:column>
</rich:columnGroup>
</f:facet>
<rich:column>
<h:outputText
value="#{registeredUsrs.firstName} #{registeredUsrs.lastName}" />
</rich:column>
<rich:column>
<h:outputText value="#{registeredUsrs.emailAddress}" />
</rich:column>
<rich:column>
<h:outputText value="#{registeredUsrs.addressLine1}" />
, <h:outputText value="#{registeredUsrs.addressLine2}" />
, <h:outputText value="#{registeredUsrs.city}" />
, <h:outputText value="#{registeredUsrs.state}" />
, <h:outputText value="#{registeredUsrs.pinCode}" />
</rich:column>
<rich:column>
<h:outputText value="#{registeredUsrs.country}" />
</rich:column>
<rich:column>
<h:outputText value="#{registeredUsrs.dateOfBirth}" />
</rich:column>
<rich:column>
<h:outputText value="#{registeredUsrs.gender}" />
</rich:column>
</rich:dataTable>
<br />
<div align="center">
<rich:dataScroller for="registeredUsersDataTable" />
</div>
<br />
<h:outputLink
value="#{registeredUsersUIController.excelFile}">Export To Excel</h:outputLink>
<h:commandLink
action="#{registeredUsersUIController.goToHome()}"
value="Go to Home Page" style="margin-left:760px !important;" />
</div>
</h:form>
</html>
index.xhtml
When the application starts, by default index.xhtml will get called. Once the user clicks on the commandLink present in
this file, registeredUsersReport.xhtml will show the detailed report.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:form>
<div style="float: left; margin-left: 235px; margin-bottom: 5px;">
<h2>List Of Registered Users</h2>
<a4j:commandLink
action="#{registeredUsersUIController.getRegisteredUsers()}"
value="List of Registered Users of Website" />
</div>
</h:form>
</html>
Maven Update, Clean and Install
1) Right click on Project from project explorer
2) Select Maven-> Update Project
3) Right click on project from project explorer
4) select Run As -> Maven Clean
5) Right click on project from project explorer
6) select Run As -> Maven Install
This will now generate war file. You need to copy this war file and deploy it on tomcat.

Weitere ähnliche Inhalte

Was ist angesagt?

Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Ryosuke Uchitate
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
GR8Conf
 

Was ist angesagt? (19)

JBoss AS Upgrade
JBoss AS UpgradeJBoss AS Upgrade
JBoss AS Upgrade
 
Test driven development (java script & mivascript)
Test driven development (java script & mivascript)Test driven development (java script & mivascript)
Test driven development (java script & mivascript)
 
java
javajava
java
 
Hibernate
HibernateHibernate
Hibernate
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Unit Testing at Scale
Unit Testing at ScaleUnit Testing at Scale
Unit Testing at Scale
 
Test-driven Development with AEM
Test-driven Development with AEMTest-driven Development with AEM
Test-driven Development with AEM
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
 
Scala active record
Scala active recordScala active record
Scala active record
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 

Ähnlich wie Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example

Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 

Ähnlich wie Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example (20)

JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Db examples
Db examplesDb examples
Db examples
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Database connect
Database connectDatabase connect
Database connect
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example

  • 1. Maven + JSF + RichFaces + JDBC + JXL API for Excel Export (Using Maven Project in Eclipse IDE)
  • 2. Create New Maven Project Create a new simple Maven Project in Eclipse. You can search the docmentation for the same online. Create pom.xml (replace XXXX with your desired value) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.XXXX</groupId> <artifactId>XXXX</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>XXXX</name> <description>XXXX </description> <properties> <org.richfaces.bom.version>4.3.3.Final</org.richfaces.bom.version> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.richfaces</groupId> <artifactId>richfaces-bom</artifactId> <version>${org.richfaces.bom.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.richfaces.ui</groupId> <artifactId>richfaces-components-ui</artifactId> </dependency> <dependency> <groupId>org.richfaces.core</groupId> <artifactId>richfaces-core-impl</artifactId> </dependency> <dependency> <groupId>javax.faces</groupId> <artifactId>javax.faces-api</artifactId> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.faces</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency>
  • 3. <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.20</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency> </dependencies> <build> <resources> <resource> <filtering>true</filtering> <directory>src/test/resources</directory> <includes> <include>**/*.properties</include> </includes> <excludes> <exclude>**/*local.properties</exclude> </excludes> </resource> <resource> <directory>srcmainresources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.vm</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <additionalClasspathElements> <additionalClasspathElement>srcmainwebappWEB-INF</additionalClasspathElement> </additionalClasspathElements> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId>
  • 4. <version>2.0</version> <configuration> <server>devserver</server> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <webXml>srcmainwebappWEB-INFweb.xml</webXml> </configuration> </plugin> </plugins> </build> </project> This should automatically start downloading maven jar files related to the pom.xml entries. If not, then 1) right click on project from project explorer 2) select Run As -> Maven Install web.xml (replace XXXX with your desired value) <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <description>XXXX</description> <display-name>XXXX</display-name> <context-param> <param-name>com.sun.faces.sendPoweredByHeader</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.disableUnicodeEscaping</param-name> <param-value>auto</param-value> </context-param> <context-param> <param-name>com.sun.faces.externalizeJavaScript</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.application.CONFIG_FILES</param-name> <param-value>/WEB-INF/faces-config.xml</param-value> </context-param> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <context-param> <param-name>org.richfaces.enableControlSkinning</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>org.richfaces.resourceOptimization.enabled</param-name> <param-value>true</param-value> </context-param>
  • 5. <context-param> <param-name>org.richfaces.skin</param-name> <param-value>blueSky</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.faces</welcome-file> </welcome-file-list> </web-app> FacesServlet related Error This step is a must to avoid javax.faces.webapp.FacesServlet related errors. 1) Right click on Project 2) Select Deployment Assembly 3) Add Maven Dependiencies directive Maven Update, Clean and Install 1) Right click on Project from project explorer 2) Select Maven-> Update Project 3) Right click on project from project explorer 4) select Run As -> Maven Clean 5) Right click on project from project explorer 6) select Run As -> Maven Install faces-config.xml (put your details at XXXX) <faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"> <managed-bean> <managed-bean-name>baseUIController</managed-bean-name> <managed-bean-class>XXXX.ui.BaseUIController</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>
  • 6. <managed-bean> <managed-bean-name>dbConnectionController</managed-bean-name> <managed-bean-class>XXXX.database.DbConnectionController</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>registeredUsersUIController</managed-bean-name> <managed-bean-class>XXXX.ui.RegisteredUsersUIController</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>dbConnectionController</property-name> <value>#{dbConnectionController}</value> </managed-property> </managed-bean> <navigation-rule> <navigation-case> <from-outcome>index</from-outcome> <to-view-id>/index.xhtml</to-view-id> <redirect /> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>registeredUsersReport</from-outcome> <to-view-id>/registeredUsersReport.xhtml</to-view-id> <redirect /> </navigation-case> </navigation-rule> </faces-config> DbConnectionController.java It is always advisable to create a seperate controller class for storing database connection details. In entire project, only this file should have hard coded database connection details so that in case of changing the connection details, only one file needs to be modified. package XXXX.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class DbConnectionController { Connection conn; Statement stmt; DriverManager driverManager; public DbConnectionController() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/DB_NAME", "DB_USER", "DB_PASSWD");
  • 7. stmt = conn.createStatement(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public DriverManager getDriverManager() { return driverManager; } public void setDriverManager(DriverManager driverManager) { this.driverManager = driverManager; } } ApplicationConstants.java Store standard error messages, file names etc in this file. Don't use file names anywhere in the project explicitely. This file should be the only file where you should be able to update file names (apart from faces-config.xml) package XXXX.constants; public class ApplicationConstants { public static final String ERROR_STRING = "There is some error executing the database query. Go to home page and please try again."; public static final String HOME_PAGE = "index"; public static final String REGISTERED_USERS = "registeredUsersReport"; public static final String REGISTERED_USERS_EXCEL = "registeredUsersReport.xls"; }
  • 8. RegisteredUsersTO.java Use a transfer object as resultset. This List of these objects will store the data retrieved from the database. This is a standard coding practice. package XXXX.resultsets; import java.util.Date; public class RegisteredUsersTO { String firstName; String lastName; String emailAddress; String addressLine1; String addressLine2; String country; String state; String city; String pinCode; Date dateOfBirth; String gender; /** * @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 emailAddress */ public String getEmailAddress() { return emailAddress; } /** * @param emailAddress the emailAddress to set */ public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; }
  • 9. /** * @return the addressLine1 */ public String getAddressLine1() { return addressLine1; } /** * @param addressLine1 the addressLine1 to set */ public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } /** * @return the addressLine2 */ public String getAddressLine2() { return addressLine2; } /** * @param addressLine2 the addressLine2 to set */ public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } /** * @return the country */ public String getCountry() { return country; } /** * @param country the country to set */ public void setCountry(String country) { this.country = country; } /** * @return the state */ public String getState() { return state; } /** * @param state the state to set */ public void setState(String state) { this.state = state; } /** * @return the city */ public String getCity() { return city; } /** * @param city the city to set */ public void setCity(String city) { this.city = city; } /** * @return the pinCode
  • 10. */ public String getPinCode() { return pinCode; } /** * @param pinCode the pinCode to set */ public void setPinCode(String pinCode) { this.pinCode = pinCode; } /** * @return the dateOfBirth */ public Date getDateOfBirth() { return dateOfBirth; } /** * @param dateOfBirth the dateOfBirth to set */ public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } /** * @return the gender */ public String getGender() { return gender; } /** * @param gender the gender to set */ public void setGender(String gender) { this.gender = gender; } } BaseUIController.java You can store all common methods/procedures which all controller classes will access under this class. Controller classes will inherit this class. package XXXX.ui; import java.io.Serializable; import javax.faces.context.FacesContext; public class BaseUIController implements Serializable { private static final long serialVersionUID = 1L; private static final String appVersion = "1.0"; public String getRealFileStoragePath() { return FacesContext.getCurrentInstance().getExternalContext() .getRealPath("/"); } }
  • 11. RegisteredUsersUIController.java package XXXX.ui; import java.io.File; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.faces.application.FacesMessage; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import XXXX.constants.ApplicationConstants; import XXXX.database.DbConnectionController; import XXXX.resultsets.RegisteredUsersTO; public class RegisteredUsersUIController extends BaseUIController { private static final long serialVersionUID = 1L; List<RegisteredUsersTO> registeredUsersTOList; DbConnectionController dbConnectionController; ResultSet resultSet; String excelFile; public String getRegisteredUsers() { dbConnectionController = new DbConnectionController(); this.registeredUsersTOList = new ArrayList<RegisteredUsersTO>(); String query = "SELECT FIRST_NAME, LAST_NAME, EMAIL_ADDRESS, ADDR_LINE_1, ADDR_LINE_2," + " PIN_CODE, CITY_NAME, STATE_NAME, COUNTRY_NAME, DATE_OF_BIRTH, GENDER" + " FROM USER INNER JOIN USER_DETAILS ON USER.USER_ID=USER_DETAILS.USER_ID" + " INNER JOIN COUNTRY ON USER_DETAILS.COUNTRY_CODE=COUNTRY.COUNTRY_CODE"; try { resultSet = dbConnectionController.getStmt().executeQuery(query); while (resultSet.next()) { RegisteredUsersTO registeredUsersTO = new RegisteredUsersTO(); registeredUsersTO.setFirstName(resultSet .getString("FIRST_NAME")); registeredUsersTO.setLastName(resultSet .getString("LAST_NAME")); registeredUsersTO.setEmailAddress(resultSet .getString("EMAIL_ADDRESS")); registeredUsersTO.setAddressLine1(resultSet .getString("ADDR_LINE_1")); registeredUsersTO.setAddressLine2(resultSet .getString("ADDR_LINE_2")); registeredUsersTO.setPinCode(resultSet .getString("PIN_CODE")); registeredUsersTO.setCity(resultSet .getString("CITY_NAME")); registeredUsersTO.setState(resultSet
  • 12. .getString("STATE_NAME")); registeredUsersTO.setCountry(resultSet .getString("COUNTRY_NAME")); registeredUsersTO.setDateOfBirth(resultSet .getDate("DATE_OF_BIRTH")); registeredUsersTO.setGender(resultSet .getString("GENDER")); registeredUsersTOList.add(registeredUsersTO); } this.excelFile = ApplicationConstants.REGISTERED_USERS_EXCEL; exportToExcel(); return ApplicationConstants.REGISTERED_USERS; } catch (Exception e) { addFacesMessage(FacesMessage.SEVERITY_ERROR, ApplicationConstants.ERROR_STRING); e.printStackTrace(); return null; } } public void exportToExcel() { try { File file = new File(getRealFileStoragePath() + excelFile); int rowcntr = 2; WorkbookSettings wbSettings = new WorkbookSettings(); wbSettings.setLocale(new Locale("en", "EN")); WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings); workbook.createSheet( "Registered Users", 0); WritableSheet excelSheet = workbook.getSheet(0); excelSheet.addCell(new Label(0, 1, "FIRST NAME")); excelSheet.addCell(new Label(1, 1, "LAST NAME")); excelSheet.addCell(new Label(2, 1, "EMAIL ADDRESS")); excelSheet.addCell(new Label(3, 1, "ADDRESS LINE 1")); excelSheet.addCell(new Label(4, 1, "ADDRESS LINE 2")); excelSheet.addCell(new Label(5, 1, "PIN CODE")); excelSheet.addCell(new Label(6, 1, "CITY")); excelSheet.addCell(new Label(7, 1, "STATE")); excelSheet.addCell(new Label(8, 1, "COUNTRY")); excelSheet.addCell(new Label(9, 1, "DATE OF BIRTH")); excelSheet.addCell(new Label(10, 1, "GENDER")); for (RegisteredUsersTO registeredUsersTO : registeredUsersTOList) { excelSheet.addCell(new Label(0, rowcntr, registeredUsersTO.getFirstName())); excelSheet.addCell(new Label(1, rowcntr, registeredUsersTO.getLastName())); excelSheet.addCell(new Label(2, rowcntr, registeredUsersTO.getEmailAddress())); excelSheet.addCell(new Label(3, rowcntr, registeredUsersTO.getAddressLine1())); excelSheet.addCell(new Label(4, rowcntr, registeredUsersTO.getAddressLine2())); excelSheet.addCell(new Label(5, rowcntr, registeredUsersTO.getPinCode())); excelSheet.addCell(new Label(6, rowcntr, registeredUsersTO.getCity())); excelSheet.addCell(new Label(7, rowcntr, registeredUsersTO.getState())); excelSheet.addCell(new Label(8, rowcntr, registeredUsersTO.getCountry())); excelSheet.addCell(new Label(9, rowcntr, String.valueOf(registeredUsersTO.getDateOfBirth())));
  • 13. excelSheet.addCell(new Label(10, rowcntr, registeredUsersTO.getGender())); rowcntr++; } workbook.write(); workbook.close(); } catch (Exception e) { e.printStackTrace(); addFacesMessage(FacesMessage.SEVERITY_ERROR, ApplicationConstants.ERROR_STRING); } } public String goToHome() { try { resultSet.close(); dbConnectionController.setStmt(null); dbConnectionController.setConn(null); dbConnectionController = null; this.registeredUsersTOList = null; this.resultSet = null; this.excelFile = null; return ApplicationConstants.HOME_PAGE; } catch (Exception e) { addFacesMessage(FacesMessage.SEVERITY_ERROR, ApplicationConstants.ERROR_STRING); return null; } } /** * @return the registeredUsersTOList */ public List<RegisteredUsersTO> getRegisteredUsersTOList() { return registeredUsersTOList; } /** * @param registeredUsersTOList the registeredUsersTOList to set */ public void setRegisteredUsersTOList( List<RegisteredUsersTO> registeredUsersTOList) { this.registeredUsersTOList = registeredUsersTOList; } /** * @return the dbConnectionController */ public DbConnectionController getDbConnectionController() { return dbConnectionController; } /** * @param dbConnectionController the dbConnectionController to set */ public void setDbConnectionController( DbConnectionController dbConnectionController) { this.dbConnectionController = dbConnectionController; } /** * @return the resultSet
  • 14. */ public ResultSet getResultSet() { return resultSet; } /** * @param resultSet the resultSet to set */ public void setResultSet(ResultSet resultSet) { this.resultSet = resultSet; } /** * @return the excelFile */ public String getExcelFile() { return excelFile; } /** * @param excelFile the excelFile to set */ public void setExcelFile(String excelFile) { this.excelFile = excelFile; } } registeredUsersReport.xhtml <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:form> <div style="float: left; margin-left: 235px; margin-bottom: 5px;"> <br /> <br /> <h2>List of Registered Users of Website</h2> <rich:dataTable id="registeredUsersDataTable" var="registeredUsrs" style="width:960px;" rows="20" value="#{registeredUsersUIController.registeredUsersTOList}" rendered="#{not empty registeredUsersUIController.registeredUsersTOList}"> <f:facet name="header"> <rich:columnGroup> <rich:column> <h:outputText value="Name" /> </rich:column> <rich:column> <h:outputText value="Email Address" /> </rich:column> <rich:column> <h:outputText value="Complete Address" /> </rich:column> <rich:column>
  • 15. <h:outputText value="Country" /> </rich:column> <rich:column> <h:outputText value="Date of Birth" /> </rich:column> <rich:column> <h:outputText value="Gender" /> </rich:column> </rich:columnGroup> </f:facet> <rich:column> <h:outputText value="#{registeredUsrs.firstName} #{registeredUsrs.lastName}" /> </rich:column> <rich:column> <h:outputText value="#{registeredUsrs.emailAddress}" /> </rich:column> <rich:column> <h:outputText value="#{registeredUsrs.addressLine1}" /> , <h:outputText value="#{registeredUsrs.addressLine2}" /> , <h:outputText value="#{registeredUsrs.city}" /> , <h:outputText value="#{registeredUsrs.state}" /> , <h:outputText value="#{registeredUsrs.pinCode}" /> </rich:column> <rich:column> <h:outputText value="#{registeredUsrs.country}" /> </rich:column> <rich:column> <h:outputText value="#{registeredUsrs.dateOfBirth}" /> </rich:column> <rich:column> <h:outputText value="#{registeredUsrs.gender}" /> </rich:column> </rich:dataTable> <br /> <div align="center"> <rich:dataScroller for="registeredUsersDataTable" /> </div> <br /> <h:outputLink value="#{registeredUsersUIController.excelFile}">Export To Excel</h:outputLink> <h:commandLink action="#{registeredUsersUIController.goToHome()}" value="Go to Home Page" style="margin-left:760px !important;" /> </div> </h:form> </html>
  • 16. index.xhtml When the application starts, by default index.xhtml will get called. Once the user clicks on the commandLink present in this file, registeredUsersReport.xhtml will show the detailed report. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:form> <div style="float: left; margin-left: 235px; margin-bottom: 5px;"> <h2>List Of Registered Users</h2> <a4j:commandLink action="#{registeredUsersUIController.getRegisteredUsers()}" value="List of Registered Users of Website" /> </div> </h:form> </html> Maven Update, Clean and Install 1) Right click on Project from project explorer 2) Select Maven-> Update Project 3) Right click on project from project explorer 4) select Run As -> Maven Clean 5) Right click on project from project explorer 6) select Run As -> Maven Install This will now generate war file. You need to copy this war file and deploy it on tomcat.