Invoking a Java Method in JSP
Asked Answered
C

4

16

Setup Mac OSX 10.6.8, Apache Tomcat 6.0.16, Java1.6.0_29, Eclipse IDE Indigo.

I asked a similar question to this before at How to execute and include a Java API from a Web App project but the set up has since changed in that i now have the Java code in the WebAp

I am trying to invoke a Java Method from a JSP page and return the results. I have looked at a lot of posts but I’m afraid my lack of experience with either language is the main problem.

I have a JSP WebAp that searches an XML database and returns content to the user. I have been asked to integrate additional java code that searches predefined Websites and returns content.

I’ve played around with similar code to the below but I think I’m looking for something else

<%@ include file="/Applications/Tomcat/apache-tomcat-6.0.16/webapps/myWebApp/program.java" %>

Can anyone give me a better idea of what I’m looking for?

Also do you know if I have to edit anything else in the WebAp to connect the two files? The class files in the WebINF folder?

Any help is very much appreciated

Deepend


package sliceClient;

import java.util.List;


public class Run {

@Inject
private SliceSearcher sliceSearcher;

@Inject
private SliceCreator sliceCreator;

/**
 * @param args
 */
public static void main(String[] args) {
    Injector injector = Guice.createInjector(new GuiceInjector());
    Run r = injector.getInstance(Run.class);
    r.runSliceConsumer();
}

private void setSlicepediaProductionMode(boolean productionMode){
    sliceSearcher.setProductionMode(productionMode);
    sliceCreator.setProductionMode(productionMode);
}

public void runSliceConsumer() {
    System.out.println("Starting Slice Consumer");

    //Remove this line if the real slicepedia server is to be used
    setSlicepediaProductionMode(true);

    List<SliceHit> sliceHits = searchForSlices();
    if (sliceHits == null) {
        System.err.println("Timeout occurred while fetching slices");
        return;
    }
    if (!sliceHits.isEmpty()) {
        System.out.println("Found some slices Yuhuuuu ! :-) ");
        String sliceContent = createSlices(sliceHits);
        System.out.println("Slice content:");
        System.out.println(sliceContent);
    } else {
        System.out.println("No Slices were found for this query");
    }
    System.out.println("Slice Consumer stopped activity");
}

private String createSlices(List<SliceHit> sliceHits) {
    sliceCreator.setSliceHits(sliceHits);
    if (sliceCreator.run()) {
        SlicePackage slicePackage = sliceCreator.getNextSlicePackage();
        return slicePackage.getSliceContent();
    } else {
        return sliceCreator.getErrorMessage();
    }
}

private List<SliceHit> searchForSlices() {
    SlicepediaQuery sliceQuery = new SlicepediaQuery();


    sliceQuery.paramANNOTATION_READING_DIFFICULTY(new Double(30), "<");
    //Works
//      String dbConcept = "http://dbpedia.org/resource/human_rights";
//      sliceQuery.paramANNOTATION_CONCEPT_FEATURE_HAS_DBPEDIA(dbConcept,0.5, ">");
//      sliceQuery.paramHAS_NBR_OF_PARAGRAPHS(1,">");
//      sliceQuery.paramIsAnOpenSlice(true);
//      sliceQuery.paramHasNumberOfToken(80, ">");

    sliceSearcher.setSliceQuery(sliceQuery);
    if (sliceSearcher.run()) {
        return sliceSearcher.getSliceHits();

    } else {
        return null;

    }
}

}

Collettecolletti answered 5/3, 2012 at 12:10 Comment(0)
U
20

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).

Unity answered 5/3, 2012 at 12:19 Comment(8)
Hi Tomasz First, thanks for your answer. I will have to go with the Ugly way as I'm not near advanced enough for the front controller method, yet. However I am unsure of the exact Syntax of your answer <%= com.example.MyUtility.getSomething() %> My Java file is called "slicer.java" It has one main package called "sliceClient" I want to invoke "sliceCreate" I want to return a string called "sliceHit" The code is located in the Web-INF/clases/src I've tried variations of <%=session.sliceClient.getsliceHit() %> without success As always, any help is appreciated DeependCollettecolletti
@Collettecolletti I am afraid you will have to show us the contents of slicer.java, your naming and vocabulary is a bit confusing in Java world. We don't need method bodies, only signatures (please add it to the question, not as a comment). From what you have said here, maybe try: <%= sliceClient.sliceCreate() %>...Unity
I’ve added the code to the Question now. As I’m new to StackOverFlow I did not know that editing the original question was acceptable. Thanks for your help in advance DeependCollettecolletti
I don't know guice, but I believe this can help you.Unity
Thanks Tomasz My JSP is calling the Java methods. Ive currently got an issue with classpaths but ill hopefully figure that out shortly.Collettecolletti
Just to add. If anyone is choosing the Ugly method of using scriptlets to import Java methods into JSP through Tomcat they also have to modify the "web.xml" file contained in the WEB-INF folder. I had to add <url-pattern>/myprogram.java</url-pattern> to make it work. There is more information about it here coderanch.com/how-to/java/InvokerServlet Good luckCollettecolletti
I'm on the verge of down-voting this answer because of the acerbic comment about how wrong it is to do this. While it might be true, some of us (me and I'm sure others that read this) don't need the overhead of an MVC. I am throwing together two pages that interface with a JAR. To use an MVC for a project like this is like bringing a nuclear bomb to a knife fight -- overkill. This solution works just fine for me and anyone who is "throwing together" a solution for an academic project or a simple interface something useful. An MVC is powerful, but it is not the silver bullet to all problems.Thao
The sriptlet is not a wrong thing. The MVC purists are wrong things. Surely fetching data in views is a bad practice, but - God - why can't we do some view-specific(!) formatting stuff there? Like we apply Django filters.Zacynthus
R
8

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

Reiners answered 5/3, 2012 at 12:20 Comment(1)
When i did this doSomething() is called successfully here why the properties file data are giving nullProtolithic
H
3

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...

Hardej answered 5/3, 2012 at 12:19 Comment(0)
S
1

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.

Siddur answered 5/3, 2012 at 12:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.