Invoking a Java Method in JSP

半世苍凉 提交于 2019-11-29 02:02:07

First, the ugly way (maybe because so similar to ?):

<%= com.example.MyUtility.getSomething() %>

It is called a and is considred a bad practice. In fact this is so wrong that I am ashamed of even writing this. What you should do instead is to have a front controller (a simple servlet will do the trick), place results in the request attributes and forward to a JSP, which in turns uses or for output. Much more work, but better by an order of magnitude:

In Servlet:

request.setAttribute("someData", MyUtility.getSomething())
RequestDispatcher dispatcher = request.getRequestDispatcher("page.jsp");
dispatcher.forward(request, response);  

In page.jsp:

${someData}

There are various frameworks that can reduce the amount of boilerplate ( is a simple example).

Well, the simplest way is to import your class in the JSP and call it's methods via scriptlets.

To include the class:

<%@page import="package.subPackage.TheClassName"%>

Note that TheClassName doesn't contain any suffixes such as .java or .class

Then

<%
   TheClassName theClassInstance = new TheClassName();
   theClassInstance.doSomething();
%>

Effectively here you're writing plain old Java code between <% and %> tags.

This is however not the best way to go from the point of view of how your code is organisd. Only presentation logic should go in the view. Littering it with such scriptlets is bad.

If you need help from some class's instance method call to diplay something in your view, your just make a Tag that does the method call (and any other non-view-related logic) and then returns only what needs to be displayed. Here's the official docs on that

http://docs.oracle.com/javaee/5/tutorial/doc/bnalj.html

I don't know that I have understand your question probably.

What you need is to import java class, and run java code in JSP

<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

import the class, and then

<%
 new ClassXXX().methodYYY();
%>

However, run java code in jsp is not a good idea...

Make any JAVA class in you src folder and import that class in JSP page like this.

<%@ page import="com.MyClass"%>

Now lets suppose you have a function in class that returns String then you will write this in JSP as:

<%
String stringFromJava = MyClass.getStringForJSPPage();
%>

Now you can use stringFromJava anywhere in JSP. You can also get List in the same way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!