Monday, May 9, 2011

Write a simple Java Bean

1. Startup your apache tomcat from command line - Navigate to the bin folder and run the startup.bat. Make sure Apache tomcat webserver is running by bringing up the browser and running http://localhost:8080

Note:-The configured HTTP port can be found by viewing the server.xml file in the conf directory.

2.We first need to write a Java code and then compile the java code and place the generated .class file in the appropriate package directory.

For example: - In our test example here - MyCalendar.java is placed under webapps/begjsp-ch02 directory of the apache tomcat installation.

package dates;
import java.util.*;
import java.text.SimpleDateFormat;
public class MyCalendar
{
private Date curDate;
private SimpleDateFormat sf;
private GregorianCalendar gf;


public String getCurrentDate()
{
gf = new GregorianCalendar();
curDate=gf.getTime();
sf = new SimpleDateFormat("EEE, HH:MM:SS");
return ((String) sf.format(curDate));
}
/*
public static void main (String args[])
{
MyCalendar mc = new MyCalendar();
System.out.println("SimpleFormatDate" + mc.getCurrentDate());

}
*/
}

If you notice this java code belongs to "dates" package.

3.Therefore after you have compiled the .java file, place the generated .class file under
webapps/begjsp-ch02/WEB-INF/classes/dates/ folder path.

4.Place the calling jsp code under begjsp-ch02 folder


In order to call the function getCurrentDate in the java class, it is accessed through the java bean as currentDate. Notice we removed the "get" and converted the property into first letter in "CurrentDate" as lowercase to follow the bean naming standards.

No comments: