Wednesday, February 15, 2012

JasperReport with Spring MVC (fully working example with source code and explanation)

Today i am going to discuss how to integrate  jasper report with Spring MVC. i will be using following sample Spring MVC Application to show how the spring mvc and jasper report is integrated. you can download this application through following URL or GitHub repository.

https://github.com/chathurangat/spring-mvc-jpa-example

or

4shared URL

once you download the project, load it with your preferable development IDE. i have use Intelli J IDEA. the project structure is shown in the below screen shot.



the jasper report will be designed to display a list of Users who are already in the database(in User Table). this User table has been mapped to the User.java model that is available inside the org.convey.user.registration.model package. you can see the source code of the User.java model as follows.

User.java

package org.convey.user.registration.model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;


@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int id;

    @Column(name = "username" , nullable = false , unique = true)
    private String userName;

    @Column(name = "password" , nullable = false)
    private String passWord;

    @Column(name = "email" , nullable = false , unique = true)
    private String email;

    @Column(name = "confirmation_code",length = 20)
    private String confirmationCode;

    @Column(name = "first_name" , length = 50,nullable = false)
    private String firstName;

    @Column(name = "last_name" , length = 50)
    private String lastName;

    @Column(name = "register_date")
    private Date registeredDate;

    @Column(name = "activate_status")
    private boolean  activate;

    @Version
    private int version;

    @ManyToMany
    @JoinTable(name ="user_module",
            joinColumns = {@JoinColumn(name = "userID", referencedColumnName = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "moduleID", referencedColumnName ="module_id")})
    private List<Module> modules;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(String confirmationCode) {
        this.confirmationCode = confirmationCode;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getRegisteredDate() {
        return registeredDate;
    }

    public void setRegisteredDate(Date registeredDate) {
        this.registeredDate = registeredDate;
    }

    public boolean isActivate() {
        return activate;
    }

    public void setActivate(boolean activate) {
        this.activate = activate;
    }


    public List<Module> getModules() {
        return modules;
    }

    public void setModules(List<Module> modules) {
        this.modules = modules;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

}//User




now it is the time to design the report using iReport. you can follow the below instructions to design your jasper report with iReport designer.

  • run the iReport tool. then File->New . then you will get the following set of available jasper report templates


  • In my case i have selected the Blank A4 report template. once you select the required report template, click Open this Template button to open the template.then you will get the following window.


then give a name for the report and select a location where the jrxml file should be saved.then click Next . after finishing all required operations you can see the selected template is loaded and ready o start the designing. please see the below.




if the palette is not automatically loaded in your designer, you can load it manually(window->palette)


you will see an another window called Report Inspector. you can add  the required fields for the report through this window. this can be done as follows.


right click on the Fields and select Add new Field Option.then you can see that newly added field is available under the Fields. you can change its attributes (name,type etc...) through the properties window. (Add up to four new fields)

Important:

when naming the fields, please make sure to name each field that is exactly same as the attribute name. In addition the data type (Field class) should also be same as the data type of identical attribute in the class. for more details, please see the below window. (we are going to design the report based on only the four attributes of the User class. therefore we need to create only four fields for the report). make sure to change the necessary properties of the newly added fields to reflect the below values.

attribute name(User class)     Field Name      Data Type(User class)     Field Class
 id                                              id                    int                                      Integer
 userName                                userName       String                                 String
 email                                        email               String                                 String
 firstName                                firstName        String                                 String


you can see that both attribute names and field names are identical. in addition there data types are also identical.now i assume that you have added new fields and changed their names and data types to meet above requirements. you can see all newly added fields as follows.



now you have loaded required components for your report design. now you can start  the design of your report. i will show you how to added newly created fields for your report.


drag and drop the newly added fields to the Detail 1 section of your report. please refer the below screen shot.



you can preview the design with the preview button.

now it is the time to start the jasper report integration with the spring mvc web application.suppose you have already downloaded the sample application given above for proceeding with this tutorial. you need to place the created jrxml file  in the class path. (in my case chathuranga-test-report.jrxml ).

 the jrxml file should be placed in the spring-mvc-jpa-jasper-report-example/src/main/resources location of the above downloaded project.

 then follow the instructions given below.

1. add the following maven dependencies to the pom.xml file.


<dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>3.7.6</version>
            <type>jar</type>
            <scope>compile</scope>           
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.0</version>
        </dependency> 
 
 
2. add the following Report controller to your controller package.
(available in spring-mvc-jpa-jasper-report-example/src/main/java/org/convey/user/registration/controller )

ReportController.java

package org.convey.user.registration.controller;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.convey.user.registration.dao.UserDao;
import org.convey.user.registration.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Controller
@RequestMapping("/report/")
public class ReportController {


    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserDao userDao;

    @RequestMapping(method = RequestMethod.GET , value = "pdf")
    public ModelAndView generatePdfReport(ModelAndView modelAndView){

        logger.debug("--------------generate PDF report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //pdfReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("pdfReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "xls")
    public ModelAndView generateXlsReport(ModelAndView modelAndView){

        logger.debug("--------------generate XLS report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("xlsReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


    @RequestMapping(method = RequestMethod.GET , value = "csv")
    public ModelAndView generateCsvReport(ModelAndView modelAndView){

        logger.debug("--------------generate CSV report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("csvReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "html")
    public ModelAndView generateHtmlReport(ModelAndView modelAndView){

        logger.debug("--------------generate HTML report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("htmlReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


}//ReportController





3. add the following jasper-view.xml file to the same directory where the applicationContext.xml file contains. (in this example, it is should be placed under the spring-mvc-jpa-jasper-report-example/src/main/webapp/WEB-INF/spring/app directory.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util-3.0.xsd">

     <!--here all the url value should contains the valid path for the jrxml file-->
    
    <bean id="pdfReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="xlsReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsXlsView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="htmlReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="csvReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsCsvView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource"/>


</beans>

here all the url properties should contains the valid reference for a jrxml file that should be used as the report template.


4. then make the below XmlViewResolver bean declaration in your  applicationContext.xml file

    <beans:bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <beans:property name="location" value="/WEB-INF/spring/app/jasper-views.xml"/>
        <beans:property name="order" value="0"/>
    </beans:bean>  

the value of location property should contains the reference for the xml file where the jasper view declarations are available.(in this case jasper-view.xml)


In addition, import the jasper-view.xml file to your applicationContext.xml file by placing the below import statement in your applicationContext.xml 


<beans:import resource="jasper-views.xml"/> 

Please make sure to change your database properties in the spring-mvc-jpa-jasper-report-example/src/main/resources/db.properties file.

then build your project with maven and deploy it in the tomcat server. then use following urls for getting the report you need.

PDF Report
 http://localhost:8080/common-user-registration/spring/report/pdf

XLS Report
 http://localhost:8080/common-user-registration/spring/report/xls

CSV Report
 http://localhost:8080/common-user-registration/spring/report/csv

HTML Report
 http://localhost:8080/common-user-registration/spring/report/html


you can download the fully example of this application through the  following git repository .

https://github.com/chathurangat/spring-mvc-jpa-jasper-report-example

Hope this will helpful for you !!!

Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

59 comments:

  1. Hi,
    I have gone throgh your example it is very nice and very understanding.I am using jasper spring integration in my own project.I have done all the steps whatever you mentioned above.In controller class return statement we mentioned the view name as pdfReport.I didnt create any pdfReport.jsp in my WEB-INF/jsp.When i run my application it is telling that pdfReport.jsp is not available.Is it mandatory to place the pdeReport.jsp in WEB-INF/jsp.I strucked up here.Can you please tell me what is happening there.This is very urgent to me.

    Thanks In Advance.

    ReplyDelete
  2. it seems that you have misunderstood what i have mentioned. you dont have to create pdfReport.jsp page under your views. you can see that i have created a bean called pdfReport in my jasper-view.xml file.
    that is the view name i am returned trough my controller.

    Thanks and Regards
    Chathuranga Tennakoon

    ReplyDelete
    Replies
    1. HiChaturanga Tennakoon,

      I got the solution.I have configured InternalResourseViewResolver and BeanNameViewResolver like that so many resolvers configured.I commented all those and placed just xmlViewResolver.Now its working....Any way thanks alot for your example.I have a small doubt while generating the jrxml file with ireport i am giving the field names as the attribute names in the entity class.But while running the application i am getting the java.lang.NoSuchMethodException: Unknown property 'attribute name'.Any idea on this...

      Delete
  3. can you post the error you are getting here? i did not get such exception anyway. just download my example and build it and run.

    ReplyDelete
    Replies
    1. I am getting the following exception.

      SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/optimer-web] threw exception [Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : active_package] with root cause
      java.lang.NoSuchMethodException: Unknown property 'active_package'
      at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1122)
      at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:686)
      at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:715)
      at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:290)
      at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:111)
      at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getFieldValue(JRAbstractBeanDataSource.java:96)
      at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.getFieldValue(JRBeanCollectionDataSource.java:100)
      at net.sf.jasperreports.engine.fill.JRFillDataset.setOldValues(JRFillDataset.java:895)
      at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:860)
      at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:837)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1434)
      at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:126)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:836)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:765)
      at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:84)
      at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)
      at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.fillReport(AbstractJasperReportsView.java:669)
      at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.renderMergedOutputModel(AbstractJasperReportsView.java:559)
      at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
      at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)

      Delete
  4. Hi,
    Can i write the jpa query as follows

    String startDate = model.getStartDat();
    String endDate = model.getEndDat();
    String callType = model.getCallType();

    TypedQuery uQuery = (TypedQuery) entityManager.createQuery("SELECT activePackage,SUM(duration),SUM(charge),COUNT(*) FROM RaBdrRating WHERE callType=callType and startDate between startDate1 and endDate1 GROUP BY activePackage ");
    List listOfPackages = uQuery.getResultList();

    return listOfPackages;

    activePackage,duration,charge are the attributes in RaBdaRating entity class

    Any thing wrong in my query.I am getting the Unknown column Exception.

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'startDate1' in 'where clause'

    ReplyDelete
  5. Hi while designing the report in ireport the field names should be the attribute names or column names

    ReplyDelete
  6. it should be same as the attribute name

    ReplyDelete
  7. Ok.I want to display the count also as a column in myreport.So i have to give the field name as the attribute name in my entity class.But there is no attribute regarding the count in my Entity class.So how can i give the field name to this count.I think you understood my problem.Sorry for eating your brain.But i am new to jasper reports,springg,jpa.So please dont feel anything and if you have idea can you please give me the reply.


    Thanks alot.

    ReplyDelete
  8. Hello,

    I have given the attribute name as the field name i am getting no such method exception..Any idea why its happening like this.If you want more information i will give you...

    ReplyDelete
    Replies
    1. please give more information... then it will be easy for me to figure out your matter

      Delete
  9. Is it require to set any classpath for ireport or any classes i have to import into my jrxml file.

    ReplyDelete
    Replies
    1. you don't have to a do any modification for the jrxml file and keep it as it is. in addition, you don't have to set the classpath explicitly because, your jrxml file is inside the resource directory. by default, the resource directory is in the class path

      Delete
  10. Hi,In your ReportInspector Detail Band you have $F{first_name} and coming to the design part in detail band you have $F{firstName}.I have a doubt over there how is it possible to give two different.Can you tell me which one to give.

    ReplyDelete
    Replies
    1. that screenshot was taken while i was developing the application for making the blog post. i think i have done some rough works there. you don't have to care about the detail band $F{first_name}. the correct one is $F{firstName} because, it reflects the attribute identifier of the class.

      Delete
  11. Ok,If i give the field names as attributes i am getting the following Exception.
    Servlet.service() for servlet [dispatcher] in context with path [/optimer-web] threw exception [Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : activePackage] with root cause
    java.lang.NoSuchMethodException: Unknown property 'activePackage'.I am trying to post the jrxml file and entity class also but it is not allowing me to post the html content.I strucked up here please can you give me any idea.The total exception i have already posted earlier.If you want i will post it now also.

    ReplyDelete
  12. Can you please explain me because i am keep on searching in the google but i didnt find the proper solution.Can you please look into this and give me the reply.

    ReplyDelete
  13. What is the report Datasource you used while designing the report.

    ReplyDelete
    Replies
    1. you can use any name for the datasource as yu wish. since we are not using the datasource directly through spring application, you are free to use any name as you wish

      Delete
  14. If possible can you give me your project as a tomcat project...

    ReplyDelete
  15. How is it working for you and not for me.The steps i have done as same you did here.Not giving the reply........

    ReplyDelete
    Replies
    1. i am extremely sorry my friend saru. i was bit busy these days with my office stuffs. therefore i was unable to find a time to even visit my blog. just be patient and give me some time to go through your questions. i will reply for all your matters when i have free time.

      Delete
  16. Find out the problem for java.lang.NoSuchMethodException :Unknown Property.In your UserDaoImpl.java class give the select distinct(userName) from User in retrieveAllRegisteredUsers() then you will definately get this problem.If you give from User then it is working fine.For me also if i just give the from Tablename then it is working fine and not giving any exception.But if i use any functions as distinct,sum like this then it is giving the problem.Try with this and give me the reply.

    ReplyDelete
  17. hi,
    I am following your example and in my case the pdf report is generating successfully but at the time of generating xls or csv report it is saving as a htm document like (balanceReportXls.htm or balanceReportCsv.htm) where it should have been saved as balanceReportXls.xls or balanceReportCsv.csv and I also found that the name of the file is exactly same with the value of my request mapping ("balanceReportXls.htm" or "balanceReportCsv.htm").


    In controller I am using the following method for xls report generation(for pdf & csv there are other methods).

    @RequestMapping(value = "/balanceReportXls.htm")
    public ModelAndView balanceReportXls(HttpServletRequest request,HttpServletResponse response,
    @ModelAttribute("balanceReportModel") BalanceReportModel balanceReportModel) throws Exception{
    ......
    ......
    parameterMap.put("datasourceXls", datasource);
    modelAndView = new ModelAndView("balanceReportXls", parameterMap);
    System.out.println("xls generate");
    return modelAndView;

    }

    please help me by solving this.

    ReplyDelete
    Replies
    1. Hi, Abhi
      Have you found the solution for the same? I am still looking in to this issue. Please guide me.

      Delete
    2. Abhi ,any workaround solution to the above.I am struggling with it too.

      Regards
      Amar Sharma

      Delete
  18. How I can define a single view (JasperReportsPdfView) for multiple jasper templates (*. jrxml)?

    ReplyDelete
  19. I am getting problem to generate word report using Jasper in spring MVC.can anybody help me.

    ReplyDelete
  20. Hay chathuranga,
    have you tried to change report title or any other values using your methods. Like How are you going to pass the report title dynamically to the page

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Hi,Can you give me the sample for sub reports using jasper reports with spring.I have googled it but i am not able to understand.

    ReplyDelete
  23. The report design can be also created using DynamicReports. This library allows to create jasper report designs at runtime, it is easy to use and it is open source.
    http://www.dynamicreports.org/

    ReplyDelete
  24. andito si robert ah sa katauhan ni jopet

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. hi
    whenever i try to download the pdf file.. i encounter this problem..
    nested exception is java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfWriter.setRgbTransparencyBlending(Z)V

    with iText-2.1.7 and jasperreports-5.1.0
    what can be the cause?
    Thank you

    ReplyDelete
  27. Hai,

    How to generate jasper reports in table format?..

    Regards
    Kartik

    ReplyDelete
  28. Hi , i tried to implement but i got this error,

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pdfReport' defined in ServletContext resource [/WEB-INF/jasper-views.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)

    Regards
    Hemant

    ReplyDelete
    Replies
    1. I am getting the same error please notify if you fixed it

      Delete
  29. Thanks Chathuranga Tennakoon this is helped me spingmvc jasper integration.In my case i want display data in Display data in the JasperReports's table view using Spring mvc .Kindly help me in this

    ReplyDelete
  30. please find below is my jrxml file :http://community.jaspersoft.com/questions/826043/display-data-jasperreportss-table-view

    ReplyDelete
  31. i have error,please help me, this is my error...[ERROR,ContextLoader,localhost-startStop-1] Context initialization failed
    org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [jasper-views.xml]
    Offending resource: class path resource [applicationContext.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file:/D:/bootcamp/project%20final/final/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/restoran/WEB-INF/classes/jasper-views.xml]; nested exception is java.io.FileNotFoundException: D:\bootcamp\project final\final\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\restoran\WEB-INF\classes\jasper-views.xml (The system cannot find the file specified)
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:218)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:147)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask

    ReplyDelete
  32. Hi,

    Where can I find the db script to create the tables mentioned in this example?

    Regards,
    Ramita Vijay

    ReplyDelete
  33. Hi Chathuranga,

    Actually , i follow your Tutorial , it is really great tutorial for developer.

    i have some stuck regarding HTML Report . i am able to show images in PDF and Excel Report But, not in HTML Report.

    i am unable to resolve this stuck ,even though i work on this stuck for complete two days.

    Kindly , give me some suggestion to resolve this issue as soon as .

    Regards,
    Bipin Pandey.


    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  34. Hi Chathuranga,

    When I am trying to execute the code, I am getting the below error. Please help me on this how to fix this issue?

    ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/db.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/collections/map/LRUMap
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  35. add commons-collections dependency in your pom.xml
    it will work..

    ReplyDelete
    Replies
    1. Hi Saurabh..

      Thank you so much...its worked for me...

      Thank you once again...

      Regards,

      K.Prabhakaran

      Delete
  36. Hi Chathuranga,

    When i execute the code, am getting strange characters in console as shown below.. i am not able to view the data in pdf format.. please help me..
    "%PDF-1.4\n%����\n3 0 obj\n<>stream\nx���MO�0\u0018��{?�s�\u0017�\u001b\u000f�q3zP\u000f��f�iV���\r\u000b��K�h�>��!�\u0004J4�᝭-S\b�#X�n,{b\u0012��Y\u0001|���h\t6��[\u0001��ݲŅ}Kc��p؄�7\t�\u0000��%���O���-�s�\u001d�&�\u001e]h�|\u001cv����2\u001e��LkR�Q��h������\u0014�H�\u0014���9��%j3\u001b\u001c�c���ܗ��Lj\nE!a��\u0007���&�%2!�Gwp��p�p\n%\n!14XժD\u0017$#�RZ\u0017(�T\u0004���TJ�\u0012�@V���)�VJ�@\u000242%P\u0017H�f�T��\\G��p.\u000b4�\f\u0015�*�s�\bh�\u001b#��]�O.�@C\u0015b]$\u0

    ReplyDelete
  37. Hi Chathuranga/Saurab,

    I have included one new table in the code base and trying to generate a report..but not able to execute..am getting the below error message..
    -----------------------------------------------------------------------------------------------------

    SEVERE: Servlet.service() for servlet [appServlet] in context with path [/common-user-registration] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: hud_coc_report_question_7 is not mapped [from hud_coc_report_question_7]] with root cause
    org.hibernate.hql.ast.QuerySyntaxException: hud_coc_report_question_7 is not mapped [from hud_coc_report_question_7]
    at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
    at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
    at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
    at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:322)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3441)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3325)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:733)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:584)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:244)
    at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
    at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
    at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:101)
    at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
    at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
    at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
    at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:272)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    at com.sun.proxy.$Proxy25.createQuery(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    at com.sun.proxy.$Proxy25.createQuery(Unknown Source)
    at org.convey.user.registration.dao.Impl.HudCocReportQuestion7DaoImpl.retrieveAllHudCocReportQuestion7(HudCocReportQuestion7DaoImpl.java:54)
    at
    --------------------------------------------------------------------------------------------------------
    kindly help me on this issue to fix..

    Regards,

    K.Prabhakaran

    ReplyDelete
  38. I am getting the above error when trying to hit the url as follows:
    http://localhost:8099/common-user-registration/spring/hudcocreport/pdf

    ReplyDelete
  39. Is anybody there?..Please help me on this issue to fix...

    ReplyDelete
  40. Hi Chathuranga,

    I am getting the following error and the project is not getting loaded. Please help me on this to fix.

    WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/common-user-registration/spring/] in DispatcherServlet with name 'appServlet'

    ReplyDelete
  41. hi.
    the above reports example
    is it use full in spring boot application

    ReplyDelete
  42. Dear chathurangat,

    Its nice to have example like this. Can you help me to get this report in table (tabular format)? Its urgent.

    Regards,
    Nitesh

    ReplyDelete
  43. When i UPDATED spring version to 4.0.7 I get ClassDefNotFounderror:JasperReportsUtil. What can I do?

    ReplyDelete