javajspnetbeans

invoke a java project from jsp button click event


I have created a simple java project to draw the bar chart taking certain values from text file and named it as ChartAdvancedBar.java, now i need to invoke it when I press a button in JSP file.

I have added this java project within the libraries of my web project. How can I import this java project to one of my JSP files?

I have added a line:

<%@page import="ChartAdvancedBar.*"%>

But it is giving an error that ChartAdvancedBar doesn't found.


Solution

  • Why you're seeing the error:

    JSP files get compiled into servlets by the application server (like Tomcat). When you use <%@ page import="ChartAdvancedBar.*" %> the JSP compiler tries to find ChartAdvancedBar in the classpath or in the web application's WEB-INF/classes directory (following the package structure).

    But here's the problem:

    To properly structure this

    Package your ChartAdvancedBar.java in a JAR file

    1. Compile your ChartAdvancedBar.java into a JAR.

    2. Place the JAR inside your web app's /WEB-INF/lib/ directory.

    3. Make sure the class has a proper package declaration, like below

      package com.mycompany.chart;
      public class ChartAdvancedBar {
          // your methods
      }
      
    4. Then in your JSP have below.

      <%@ page import="com.mycompany.chart.ChartAdvancedBar" %>`