Monday, November 21, 2011

JSP - Calling Java class

Reduce your HelloWorld.java class from a Servlet to a POJO.
(POJO = Plain Old Java Object - one which does not extend any other class nor implement any external interface)

Like this:
 package org.confucius;  
   
 public class HelloWorld{  
      public static String getGreeting ()  
      {  
           return "Hello World!";  
      }  
 }  
   


Call this from your HelloWorld.jsp:
 <html>  
      <head>  
           <%@ page import="org.confucius.HelloWorld" %>  
      </head>  
      <body>  
           <p><%= HelloWorld.getGreeting() %></p>  
      </body>  
 </html  


Note that <% .. %> tells JSP that this is Java code.
Between these enclosures, you can write any Java code, just like you would write inside a Foo.java source file.

Cleanup your web.xml - we no longer using HelloWorld as a servlet:
 <web-app>  
 </web-app>  
   


Run Ant:dist target, then deploy HelloWorld.war to Tomcat.

If you point your browser to:
http://localhost:8080/HelloWorld/jsp/HelloWorld.jsp

You will see "Hello World!" - but this time the greeting has come from the HelloWorld.java POJO.

No comments: