How to Implementation JSF Chart in JSF
Many times we have requirement of displaying data using charts in our web application. Jsf-comp is a opensource library which I have used in my JSF application. I have used this for simple bar charts and using it is very simple. Below I have explained steps to use it in your application to create a bar chart.
Here I assume you have already had a jsf application running. If you are new to JSF, please read the earlier post JSF tutorial For Beginner .
For the bar chart demo we’ll create a request scoped bean, and a simple jsf view. The data displayed in charts will be some predefined values.
Step 1: Configuration.
Before starting the code download jsf-comp jar file ( jfreechart-1.0.5.jar) from url:
http://sourceforge.net/projects/jfreechart/files/
Copy the jar to web-inf/lib directrory.
Edit your web.xml file to include following:
<servlet>
<servlet-name>Chartlet</servlet-name>
<servlet-class>net.sf.jsfcomp.chartcreator.Chartlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Chartlet</servlet-name>
<url-pattern>*.chart</url-pattern>
</servlet-mapping>
Step 2: Backing bean part.
To create any chart we need object of DefaultCategoryDataset (org.jfree.data.category.DefaultCategoryDataset)
DefaultCategoryDataset categoryDataSet=new DefaultCategoryDataset();
We set graph values in this object using addValue function. The functions is shown below (create a Weather.java and include following function with appropriate getter and setter methods) :
package com.sa.medisys.banamco.chart;
import org.jfree.data.category.DefaultCategoryDataset;
public class Weather {
public Weather(){
}
public DefaultCategoryDataset getGraphData() {
DefaultCategoryDataset categoryDataSet=null;
try{
categoryDataSet = new DefaultCategoryDataset();
Double currentTemperature= 25.3;
//Easy AdSense by Unreal
Double minTemperature=10.2;
Double maxTemperature=45.0;
Double avgTemperature=30.0;
categoryDataSet.addValue(maxTemperature,"","Highest Temperature");
categoryDataSet.addValue(minTemperature,"","Lowest Temperature");
categoryDataSet.addValue(avgTemperature,"","Average Temperature");
categoryDataSet.addValue(currentTemperature,"","current Temperature");
return categoryDataSet;
}catch(Exception sq){
System.out.println("exception2 " +sq);
sq.printStackTrace();
return null;
}
}
}
Define the bean in the faces-config.xml file as Managed Bean:
<managed-bean>
<managed-bean-name>weather</managed-bean-name>
<managed-bean-class> com.sa.medisys.banamco.chart.Weather</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Now in xhtml file you can use the chart library as follows:
Include tag library definition:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:ch="http://sourceforge.net/projects/jsf-comp">
<ui:composition >
<h:outputText value="chart Display" />
<ch:chart id="pichart" datasource="#{weather.graphData}" type="bar" background="orange" orientation="vertical" is3d="false" title="Compare the Temperatures" xlabel="" ylabel="Temperature" height="300" width="500"></ch:chart>
</ui:composition>
</html>
Run the jsf file to see the chart.
Tuesday, January 26, 2010
Saturday, January 23, 2010
Jasper Report Calling from JSF Page
Jasper Report Calling from JSF Page
Step-1. Create ReportBean.Java file as a bean class
/****** ReportBean.java Class Start*******************/
package com.report;
public class ReportBean {
private Date startDate;
private Date endDate;
private String customerID=null;
private String customerName;
private String itemcode;
private String itemname;
ReportDao dao=new ReportDao();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
LoginSession ses=(LoginSession)session.getAttribute("SESSION");
/******* PDF Report ***********/
public void reportCustomer(){
try {
String filename = "Report/KITR009.jasper";
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
//file path of .jasper file
String path = servletContext.getRealPath("/");
String filePath=path+File.separator+filename;
String imgPath=path+File.separator+"images"+File.separator+"MedisysLogo.gif";
dao.report0009(ses.getUserid(),imgPath,filePath);
} catch (Exception e) {
}
}
/******* HTML Report ***********/
public void reportSalesMan(){
try {
String filename = "Report/KITR0042.jasper";
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
//file path of .jasper file
String path = servletContext.getRealPath("/");
String filePath=path+File.separator+filename;
String imgPath=path+File.separator+"images"+File.separator+"MedisysLogo.gif";
dao.report0042(ses.getUserid(),imgPath,filePath);
} catch (Exception e) {
}
}
//////////////////// GETTER SETTER ///////////////////////
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
System.out.println("startDate:: "+startDate);
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getCustomerID() {
return customerID;
}
}
/****** ReportBean.java Class END*******************/
/**************** ReportDao call form bean ***********/
/********* Start ReportDao.java *********/
package com.sa.medisys.banamco.report;
public class ReportDao extends DBConnection{
/* Customer Information PDF Report */
public void report0009(String userid,String imgPath,String filePath ) throws SQLException, JRException, IOException, NamingException {
try{
System.out.println("User ID ::"+userid);
Map parameter = new HashMap();
parameter.put("USER_ID", userid);
parameter.put("LOGO_PATH", imgPath);
Connection con=dbOpen();
System.out.println("Connection Established"+ con);
JasperPrint jasperPrint =JasperFillManager.fillReport(filePath, parameter,con);
//System.out.println("Report Created..."+parameter.get("itemtype"));
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =(HttpServletResponse) context.getExternalContext().getResponse();
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
System.out.println("bytes >> "+bytes.length);
response.setHeader("Content-disposition", "attachment; filename=\"KITR0009.pdf\"");
//response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
response.setContentType("application/pdf");
//response.setContentType("text/html; charset=utf-8");
//response.setHeader ("Content-disposition", "attachment; filename=\"CustomerReport.pdf\"");
context.responseComplete();
dbClose(con);
//session.removeAttribute("kIT0053Bean");
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
/* Salesman Information HTML Report */
public void report0042(String userid,String imgPath,String filePath ) throws SQLException, JRException, IOException, NamingException{
Connection con=dbOpen();
FacesContext context = FacesContext.getCurrentInstance();
try{
System.out.println("User ID ::"+userid);
Map parameter = new HashMap();
parameter.put("USER_ID", userid);
parameter.put("LOGO_PATH", imgPath);
System.out.println("Connection Established"+ con);
JasperPrint jasperPrint =JasperFillManager.fillReport(filePath, parameter,con);
// html ////////
System.out.println("Report Created... in Format");
JRExporter exporter = null;
HttpServletResponse response =(HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("text/html; charset=utf-8");
response.setHeader ("Content-disposition", "attachment; filename=\"KITR0042.html\"");
exporter = new JRHtmlExporter();
exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER, response.getWriter());
exporter.exportReport();
context.responseComplete();
}catch (Exception e) {
System.out.println(e.getMessage());
}finally{
dbClose(con);
System.out.println("Created >>>>>>>>");
}
}
}
/********* END ReportDao.java *********/
Step-1. Create ReportBean.Java file as a bean class
/****** ReportBean.java Class Start*******************/
package com.report;
public class ReportBean {
private Date startDate;
private Date endDate;
private String customerID=null;
private String customerName;
private String itemcode;
private String itemname;
ReportDao dao=new ReportDao();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
LoginSession ses=(LoginSession)session.getAttribute("SESSION");
/******* PDF Report ***********/
public void reportCustomer(){
try {
String filename = "Report/KITR009.jasper";
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
//file path of .jasper file
String path = servletContext.getRealPath("/");
String filePath=path+File.separator+filename;
String imgPath=path+File.separator+"images"+File.separator+"MedisysLogo.gif";
dao.report0009(ses.getUserid(),imgPath,filePath);
} catch (Exception e) {
}
}
/******* HTML Report ***********/
public void reportSalesMan(){
try {
String filename = "Report/KITR0042.jasper";
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
//file path of .jasper file
String path = servletContext.getRealPath("/");
String filePath=path+File.separator+filename;
String imgPath=path+File.separator+"images"+File.separator+"MedisysLogo.gif";
dao.report0042(ses.getUserid(),imgPath,filePath);
} catch (Exception e) {
}
}
//////////////////// GETTER SETTER ///////////////////////
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
System.out.println("startDate:: "+startDate);
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getCustomerID() {
return customerID;
}
}
/****** ReportBean.java Class END*******************/
/**************** ReportDao call form bean ***********/
/********* Start ReportDao.java *********/
package com.sa.medisys.banamco.report;
public class ReportDao extends DBConnection{
/* Customer Information PDF Report */
public void report0009(String userid,String imgPath,String filePath ) throws SQLException, JRException, IOException, NamingException {
try{
System.out.println("User ID ::"+userid);
Map
parameter.put("USER_ID", userid);
parameter.put("LOGO_PATH", imgPath);
Connection con=dbOpen();
System.out.println("Connection Established"+ con);
JasperPrint jasperPrint =JasperFillManager.fillReport(filePath, parameter,con);
//System.out.println("Report Created..."+parameter.get("itemtype"));
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =(HttpServletResponse) context.getExternalContext().getResponse();
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
System.out.println("bytes >> "+bytes.length);
response.setHeader("Content-disposition", "attachment; filename=\"KITR0009.pdf\"");
//response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
response.setContentType("application/pdf");
//response.setContentType("text/html; charset=utf-8");
//response.setHeader ("Content-disposition", "attachment; filename=\"CustomerReport.pdf\"");
context.responseComplete();
dbClose(con);
//session.removeAttribute("kIT0053Bean");
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
/* Salesman Information HTML Report */
public void report0042(String userid,String imgPath,String filePath ) throws SQLException, JRException, IOException, NamingException{
Connection con=dbOpen();
FacesContext context = FacesContext.getCurrentInstance();
try{
System.out.println("User ID ::"+userid);
Map
parameter.put("USER_ID", userid);
parameter.put("LOGO_PATH", imgPath);
System.out.println("Connection Established"+ con);
JasperPrint jasperPrint =JasperFillManager.fillReport(filePath, parameter,con);
// html ////////
System.out.println("Report Created... in Format");
JRExporter exporter = null;
HttpServletResponse response =(HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("text/html; charset=utf-8");
response.setHeader ("Content-disposition", "attachment; filename=\"KITR0042.html\"");
exporter = new JRHtmlExporter();
exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER, response.getWriter());
exporter.exportReport();
context.responseComplete();
}catch (Exception e) {
System.out.println(e.getMessage());
}finally{
dbClose(con);
System.out.println("Created >>>>>>>>");
}
}
}
/********* END ReportDao.java *********/
How to configure Session timeout in jsf
How to Configure Session Timeout in jsf
How to Configure Session Timeout in jsf
Step 1.Create Listener Class such as MySessionListener.java
package com.session;
public class MySessionListener implements HttpSessionListener {
public MySessionListener() {
}
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Current Session created : "+ event.getSession().getId() + "at "+ new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session…
HttpSession session = event.getSession();
System.out.println("Current Session destroyed :" + session.getId() + "Logging out user");
/*
* nobody can reach user data after this point because session is invalidated already.
* So, get the user data from session and save its logout information
* before losing it.
* User’s redirection to the timeout page will be handled by the SessionTimeoutFilter.
*/
// Only if needed
try {
prepareLogoutInfoAndLogoutActiveUser(session);
} catch(Exception e) {
System.out.println("Error while logging out at session destroyed : " + e.getMessage());
}
}
/**
* Clean your logout operations.
*/
public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {
// Only if needed
}
}
Step 2.Create Filter Class SessionTimeoutFilter.java
package com.session;
/**
*When the session destroyed, MySessionListener will do necessary logout operations.
* Later, at the first request of client, this filter will be fired and redirect
* the user to the appropriate timeout page if the session is not valid.
*/
public class SessionTimeoutFilter implements Filter {
// This should be your default Home or Login page
// "login.index" if you use Jboss Seam otherwise "login.jsf" / "login.xhtml" or whatever
private String timeoutPage = "/LOG001.jsf";
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// is session expire control required for this request?
if (isSessionControlRequiredForThisResource(httpServletRequest)) {
// is session invalid?
if (isSessionInvalid(httpServletRequest)) {
String timeoutUrl = httpServletRequest.getContextPath() + "/" + getTimeoutPage();
System.out.println("Session is invalid! redirecting to timeoutpage : " + timeoutUrl);
httpServletResponse.sendRedirect(timeoutUrl);
return;
}
}
}
filterChain.doFilter(request, response);
}
/*
* session shouldn’t be checked for some pages. For example: for timeout page..
* Since we’re redirecting to timeout page from this filter,
* if we don’t disable session control for it, filter will again redirect to it
* and this will be result with an infinite loop…
*/
private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {
String requestPath = httpServletRequest.getRequestURI();
boolean controlRequired = !StringUtils.contains(requestPath, getTimeoutPage());
return controlRequired;
}
private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)
&& !httpServletRequest.isRequestedSessionIdValid();
return sessionInValid;
}
public void destroy() {
}
public String getTimeoutPage() {
return timeoutPage;
}
public void setTimeoutPage(String timeoutPage) {
this.timeoutPage = timeoutPage;
}
}
Step -3
1. Put jar file commons-lang-2.4 into lib folder
2. Change web.xml file
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>com.session.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
<listener>
<listener-class>com.session.MySessionListener</listener-class>
</listener>
Subscribe to:
Posts (Atom)