How to use a class in a Java Archive (JAR) in Eclipse

Home > Search > How-to
  by

Let's say you have two or more Java applications that need to use the same exact class. In this scenario, it makes sense to create a JAR that contains the class, and then every app that needs to use the class can reference the JAR. As an example, let's say sample.jar contains the People.class in the com.sample.main package that prints the text "John Doe".

com.sample.main.People.class

 

In each application that needs to use the class, the application will need access to the JAR. While developing the application in Eclipse, add the JAR to Java Build Path, so that you can perform testing to determine if the application is able to access the classes in the JAR.

 


Place the JAR in the WEB-INF/lib folder

One the application is ready to be deployed to your development or production application server (JBoss, Tomcat, WebSphere), one option would be to place the JAR in the WEB-INF/lib folder of the application. This is usually undesireable, because if the JAR is updated, then the app will need to be recompiled and redeployed to the application server. This is troublesome with only a single app, and even more troublesome when you have two or more apps using the JAR. The below approaches resolve this trouble, so that there is no need to recompile or redeploy the app when the JAR is updated.

 


Place the JAR in the JVMs classpath (WebSphere)

If the app is being deployed to WebSphere, and two or more apps in a JVM need to use the JAR, you can add the JAR to the JVMs classpath, A significant advantage to this approach is that if the JAR is updated, the new JAR can simply be deployed to WebSphere, with no need to recompile or redeploy the apps in the JVM.

 


Place the JAR in a Shared Library (WebSphere)

If the app is being deployed to WebSphere, and apps in different JVMs need to use the JAR, you can create a Shared Library that contains the JAR, and then configure JVMs to use the shared library. Just like using a JVMs classpath, this approach also has the advantage that if the JAR is updated, the new JAR can simply be deployed to WebSphere, with no need to recompile or redeploy the apps in the JVM.

 


Configure Java App

Regardless of what approach you use for the app to use the JAR, the markup in the app to use the JAR remains the same. In the <head> of your JSP page, import the People class.

<%@page import="com.sample.main.People"%>

 

In the <body> of your JSP page, create a new people object (foo in this example), and then using foo, get the value of the name variable.

<%
  People foo = new People();
  out.print(foo.getName());
%>

 

Navagiating to the JSP page should now display John Doe.

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments