Calling a java method in jsp

I have a java class which performs some operations on files. Since the java code is huge I don't want to write this code in jsp. I want to call the methods in jsp whenever required.

Please tell me the path where I need to keep this file. Also some example code how to use it would be helpful.


In the servlet (which runs before the JSP):

Person p = new Person(); // instantiate business object
p.init(...); // init it or something
request.setAttribute("person", p); // make it available to the template as 'person'

In the template you can use this:

your age is: ${person.age}  <%-- calls person.getAge() --%>

I think the question is, how do you make Java code available to a JSP? You would make it available like any other Java code, which means it needs to be compiled into a .class file and put on the classpath.

In web applications, this means the class file must exist under WEB-INF/classes in the application's .war file or directory, in the usual directory structure matching its package. So, compile and deploy this code along with all of your other application Java code, and it should be in the right place.

Note you will need to import your class in the JSP, or use the fully-qualified class name, but otherwise you can write whatever Java code you like using the <% %> syntax.

You could also declare a method in some other utility JSP, using <%! %> syntax (note the !), import the JSP, and then call the method declared in such a block. This is bad style though.


Depending on the kind of action you'd like to call, there you normally use taglibs, EL functions or servlets for. Java code really, really doesn't belong in JSP files, but in Java classes.

If you want to preprocess a request, use the Servlet doGet() method. E.g.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Preprocess request here.
    doYourThingHere();
    // And forward to JSP to display data.
    request.getRequestDispatcher("page.jsp").forward(request, response);
}

If you want to postprocess a request after some form submit, use the Servlet doPost() method instead.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Postprocess request here.
    doYourThingHere();
    // And forward to JSP to display results.
    request.getRequestDispatcher("page.jsp").forward(request, response);
}

If you want to control the page flow and/or HTML output, use a taglib like JSTL core taglib or create custom tags.

If you want to execute static/helper functions, use EL functions like JSTL fn taglib or create custom functions.