Bootstrap FreeKB - Java - Return a string value from a class to a JSP page
Java - Return a string value from a class to a JSP page

Updated:   |  Java articles

Create a Dynamic Web Project in Eclipse. Let's say the name of the project is demo. 

In the left panel of Eclipse, at the name of your project (demo in this example) > Java Resources > src, create a new package. For the sake of this tutorial, let's name the package com.demo.

In the package, create a class called myClass.java.

In return.java, add the following markup.

package com.demo;

public class myClass {
	public String myMethod() throws Exception {
		return "Hello World";
	}
}

 

In the left panel of Eclipse, right click on the name of your project (demo in this example) and select New JSP File. Select the WebContent folder, give the file a name such as index.jsp, and select Finish.

Add the following to line 1 of the JSP file. This is the combination of the package (com.demo) and the class (myClass.java).

<%@page import="com.demo.myClass"%>

 

Add the following inside the <body> tags.

  • In this example, "myClass" must be used because the name of the class in myClass.java is myClass.
  • In this example, "myMethod" must be cause because the name of the method in myClass.java is myMethod.
<body>
<%
  myClass foo = new myClass();
  out.println(foo.myMethod());
%>
</body>

 

Select the green play button in Eclipse, and hopefully something like this is returned.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 26e47f in the box below so that we can be sure you are a human.