6

I wrote some code as a Java Servlet and now I am trying to convert it to a JSP. I wrote a class in a separate file which I was using, and I can't figure out how to get the JSP file to recognize the class. I guess it has something to do with importing. I gave the class a package (package mypackagename;) name and I tried using <%@ page import="mypackagename"%> but I get an error:

The import "mypackagename" cannot be resolved

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Michoel
  • 61
  • 1
  • 1
  • 2
  • possible duplicate of [How do you import classes in JSP?](http://stackoverflow.com/questions/239147/how-do-you-import-classes-in-jsp) – jjnguy Jun 01 '10 at 13:06

2 Answers2

12

Just import it the same way as you do in a real Java class. I.e. import mypackagename.MyClassName or import mypackagename.* and thus not import mypackagename with only the package name.

<%@ page import="mypackagename.MyClassName" %>

That said, you should not write raw Java code in a JSP file. Scriptlets are considered poor practice. That code belongs in a real Java class. It was located perfectly fine in the Servlet class. What is it, the problem for which you think that it is the "right" solution to move it all into the view side and clutter the template text with raw Java code? Elaborate about it in a new question, then we may be able to suggest the right solutions. Maybe you weren't aware of existence and powers of taglibs like JSTL?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • im not too sure what you mean by raw java code in a jsp file. most of my code is in the class i want to import, i just want to run the code from the class in the JSP file and display the results. – Michoel Jun 01 '10 at 13:19
  • 1
    With raw Java code, I mean the over a decade discouraged *scriptlets*. All that Java code between those `<% %>` things. In your specific case, just run that code in the servlet, store it as request attribute and display it using JSTL/EL. [Here](http://stackoverflow.com/questions/1831053/displaying-multiple-records-by-using-resultset/1832524#1832524) and [here](http://stackoverflow.com/questions/384189/how-do-i-make-a-java-resultset-available-in-my-jsp/2428468#2428468) are some examples. [Here](http://courses.coreservlets.com/Course-Materials/csajsp2.html) is the better JSP/Servlet tutorial. – BalusC Jun 01 '10 at 13:27
0

Be sure that your class is in WEB-INF/classes directory of the web application, and modify the import of the package by package.*

  • thanks for the tip about the .* at the end. im just learning java so i forgot about that. i didn't know the files have to go in WEB-INF/classes, they were located in src/ For some reason eclipse does not allow me to create a new directory in WEB-INF? (I am using google appengine plugin) – Michoel Jun 01 '10 at 13:14