Home » Java » Importing a class in a JSP file

Importing a class in a JSP file

Posted by: admin December 28, 2021 Leave a comment


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


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?


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