He Hui He Hui - 4 months ago 10
Java Question

How import a .java file into a JSP page?

this is my first time trying to use java for backend web systems.

I have been reading up some guides on how to do this, and thus far i understand the following points:

  1. I am not allowed to import .java files, but rather, import the class files.

  2. <%@ page language="java" import="somefile.*"%> this is how i import a package.

  3. After importing a package, I am required to create an instance of the class.

However, I am confused with a few things.

I now have a Dynamic Web Project, developing in Eclipse IDE and using TomCat7.0 apache.

I have a directory

and some .java files in the above directory.

Question 1, in Eclipse, when I run these files, they are automatically compiled. Where does these class files go?

Question 2, when I run the following code, I recieved some errors. What am I doing wrong? Is it because I do not have my class files in the right directory?

<%@ page language="java" import="twitter.*"%>

JavaFile jf = new Javafile();

String result = jf.searchTweets("someString");

Error report:

type Exception report


description The server encountered an internal error () that prevented it from fulfilling this request.


org.apache.jasper.JasperException: An exception occurred processing JSP page /hello.jsp at line 10

7: <%@ page language="java" import="twitter.*"%>
9: <%
10: Javafile jf = new JavaFile();
12: String result = jf.searchTweets("someString");
13: System.out.println(result);

Thank you for your time and effort.

note: I have read the following links, but they do not seem to provide a solution on how to write your own .java files and import these classes into your jsp files.


How do you import classes in JSP?


EDIT: I found my own answer.

This is my original directory

enter image description here

As you can see, my WEB-INF/lib is empty.

All that was required to do, is to move the relevant .jar files into this directory.

Note: I have already imported the relevant .jar files to the Eclipse project, but it seems that I need to move them into WEB-INF/lib on top of importing them into the project.

Thank you to all that helped answer my question.

This is my final directory imageenter image description here


Only classes may be imported into a .java file, and a JSP "compiles" to a .java file, so this requirement holds for JSP files too.

From a quick glance at the API, it seems that your import is formatted correctly; but, you are importing the wrong namespace. The javadoc for the twitter4j API indicates that you should be importing "twitter4j" namespaces, not "twitter" namespaces.