Jul 22, 2009
Using hibernate and struts together
(1) Configure the struts configuration in web.xml. If you don't know how to do so then first read a little about struts. At: Struts Action Example
(2) In struts-config.xml define the action and form.
e.g.
<!-- ========== Form Bean Definitions ================= -->
<form-beans>
<form-bean name="User" type="com.persistence.UserVO"/>
</form-beans>
<!-- ========== Action Mapping Definitions ============ -->
<action-mappings>
<action path="/user" type="com.control.UserController" name="User" input="/home.jsp">
<forward name="success" path="/home.jsp"/>
<forward name="failure" path="/room.jsp"/>
</action>
</action-mappings>
(3) Now create bean class as per the requirement the database as well HTML form. E.g.
import org.apache.struts.action.ActionForm;
public class UserVO extends ActionForm {
private int id;
private String userName;
private String userPassword;
private String userFirstName;
private String userLastName;
private String userEmail;
// ----- getter and setter methods for all fields
}
But keep one thing clear that the fields of bean class must have same name as the fields of HTML form you submit from. Here I created this class as my HTML form is as like below.
<form action="user.do" method="post"><br />
Name:<input type="text" name="username" /> <br />
Password:<input type="password" name="userPassword" /> <br />
First name:<input type="text" name="userFirstName" /> <br />
Last name:<input type="text" name="userLastName" /> <br />
E-mail:<input type="text" name="userEmail" />
<input type="submit">
</form>
(4) Now configure hibernate configuration files. First of all create hibernate.cfg.xml file as per your requirements. If you don't know how to create then please read about hibernate first. Hibernate tutorial
Then after create *.hbn.xml file to map bean class with database table (here * in the name means you can give name as per your choice). As below
<hibernate-mapping>
<class name="com.persistence.UserVO" table="contact">
<id column="USER_ID" name="id" type="int">
<generator class="native" />
</id>
<property column="USER_NAME" name="userName" type="java.lang.String" />
<property column="USER_PASSWORD" name="userPassword" type="java.lang.String" />
<property column="USER_FIRST_NAME" name="userFirstName" type="java.lang.String" />
<property column="USER_LAST_NAME" name="userLastName" type="java.lang.String" />
<property column="USER_EMAIL" name="userEmail" type="java.lang.String" />
</class>
</hibernate-mapping>
PLEASE NOTE:
This is main part where you have to take enough care. In class tag value of attribute name must be equal to the value of attribute type in tag form-bean.
As well in id and property tags column name must contain the name of column of your table and name tag must contain the value you define in bean class.
(5) Now define the class extending Action class of struts' action class as below.
public class UserController extends Action {
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
try {
UserVO user = (UserVO)form;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction t = session.beginTransaction();
session.saveOrUpdate(user);
t.commit();
return mapping.findForward("success");
} catch (Exception e) {
return mapping.findForward("failure");
}
}
}
May 25, 2009
Struts – Action – Example
There is a predefined structure to implement struts in our web application.
(1) First of all create web.xml. Declare a servlet as below.
e.g.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
We are not declaring any controller servlet here. As we are going to use struts. In struts controller servlet are being declared in struts-comfig.xml.
(2) Create one file struts-config.xml. place this file in WEB-INF directory.
e.g.
<struts-config>
<!-- Form Bean Definitions -->
<form-beans>
<form-bean name="submitForm" type="com.forms.SubmitForm"/>
</form-beans>
<!-- Action Mapping Definitions -->
<action-mappings>
<action path="/submit" type="com.action.SubmitAction" name="submitForm">
<forward name="success" path="/index.jsp"/>
<forward name="failure" path="/submit.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
</struts-config>
Here we declared one action named submitForm. SubmitForm defines path /submit so whenever server request for /submit.do submitForm action will be called.
forward tag defines that where to forward request after its processing. Here we define submit.jsp for failure. So if request been failed to process then server will forward the request to submit.jsp. As well for success we define index.jsp.
(3) Now define a class SubmitAction extending org.apache.struts.action.Action class.
As in servlet, we defines a method as doPost or doGet to process. Here define a method execute as in example.
e.g.
public class SubmitAction extends Action {
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
/* here we gets object of ActionMapping, ActionForm, HttpServletRequest and HttpResponse.*/
SubmitForm submitForm = (SubmitForm)form;
/* if lastName field left blank then procees will be stoped and control will go to submit form again */
if(submitForm.getLastName()==null)
return mapping.findForward("failure");
String lastName = submitForm.getLastName();
request.setAttribute("lastName", lastName.toUpperCase());
return mapping.findForward("success");
}
}
mapping : this object is used to forward request after processing as in example.
form : explain later in this post.
(4) Now just look at the struts-config.xml, there is tag defined by form-beans. This tag defines the form class. The form class is a simple javabean which contains the fields, we are going to pass through the form from jsp or html. Fields' name must match with the names of the parameter of the request.
e.g.
public class SubmitForm extends ActionForm {
private String lastName = "";
private String address = "";
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Here parameter passed through the /submit.do request must be lastName and address.
Whenever one submit the form from submit.jsp all the fields of form class will be set with the values passed in the request. So the object we are getting in action class as argument have all the field filled by the user.
(5) Now for the testing create one jsp named submit.jsp.
e.g.
<form action="/submit" method="post">
Last name: <input type="text" name="lastName">
address:<br/><textarea name="address" rows="2" cols="30"> address</textarea>
</form>
This is how the whole structure of a struts action implemented. This is a very basic functionality. This may be extend to a large application where more one controller are defined as well as forms.
Mar 6, 2009
Java - Inner Classes - for SCJP
Earlier, Non-static inner classes were not allowed to have static fields at all. This rule is now modified and the new rule says that: 'The third paragraph of the section Members that can be marked static is amended to make an exception and allow inner classes to declare static FIINAL fields that are compile time constants as members.'
Ex.:
public class Outer{
class Inner
{
static final int k = 10;
}
}
(Top level classes mean, classes defined in package scope and STATIC inner classes of classes defined in package scope) Consider the anonymous inner class for catching action events:
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e){
}
};
Here, the anonymous class implicitly extends Object and implements the interface ActionListener. Explicit extends or implements clauses are not allowed for such classes. Other inner class (ie. non anonymous) can have them. Consider the following (although of no use) class:
public class TestClass
{
public TestClass(int i) { }
public void m1()
{
TestClass al = new TestClass(10)
{
public void actionPerformed(ActionEvent e)
{
}
};
}
}
This illustrates 4 points:
- Instance Methods can also have inner classes. (But they cannot have static inner classes).
- Inner class can extend the outer class.
- Anonymous inner class can be created for classes. (Not just for interfaces). They implicitly extend the class.(Here, TestClass)
- Anonymous inner class can have initialization parameter. (If the class they extend has a corresponding constrctor).
Anonymous classes cannot have explict constructors, since they have no names.
A static inner class is also known as A Top Level Nested class. So,there are two types of Top level classes. One, that is a standard class and other an inner class which is static.
Eg.
public class A //This is a standard Top Level class.
{
class X
{
static final int j = 10; //compiles fine!
}
public static class B //This is also a Top Level class (but nested!)
{
}
}
You can create objects of B with having objects of A. Eg. A.B b = new A.B();
Members in outer instances are directly accessible using simple names. There is no restriction that member variables in inner classes must be final.
Nested classes define distinct types from the enclosing class, and the instanceof operator does not take of the outer instance into consideration.
Every non static inner class object has a reference to it's out class object which can be accessed by doing OuterClass.this. So the expression B.this.c will refer to B's c, which is 'a'. Inside a non-static inner class, 'InnerClass.this' is equivalent to 'this'. so 'C.this.c' refers to C's c which is 'c'. The expression super.c will access the variable from A, the superclass of C which is 'd'.
Only classes declared as members of top-level classes can be declared static. Such a member is a top-level nested class if it is declared static, otherwise it is a non-static inner class.
Package member classes, local classes(ie. classes declared in methods) and anonymous classes cannot be declared static.
Feb 27, 2009
Struts - What & Why?
How and where Struts fits in the big picture?
Presentation Tier Strategies Technologies used for the presentation tier can be roughly classified into three categories:
• Markup based Rendering (e.g. JSPs)
• Template based Transformation (e.g. XSLT)
• Rich content (e.g. Macromedia Flash)
We will start by introducing the two modes of designing JSPs - Model 1 and Model 2 architectures in the next two sections and then arrive at Struts as an improvement over the Model 2 architecture.
Model 1 Architecture

Let us illustrate the operation of Model 1 architecture with an example. Consider a HTML page with a hyperlink to a JSP. When user clicks on the hyperlink, the JSP is directly invoked. The servlet container parses the JSP and executes the resulting Java servlet. The JSP contains embedded code and tags to access the Model JavaBeans. The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string. In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page. The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags.
Problems with Model 1 Architecture
• In Model 1 architecture, the presentation logic usually leads to a significant amount of java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers.
• Application control is decentralized in Model 1 architecture since the next page to be displayed is determined by the logic embedded in the current page. Decentralized navigation control can cause headaches.
Model 2 Architecture - MVC

The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a servlet.
Advantages of Model 2 Architecture
• Since there is no presentation logic in JSP, there are no scriptlets. This means lesser nightmares.
• With MVC you can have as many controller servlets in your web application. In fact you can have one Controller Servlet per module.
Why do we need Struts? (Controller gone bad – Fat Controller)
If MVC is all that great, why do we need Struts after all? The answer lies in the difficulties associated in applying bare bone MVC to real world complexities. In medium to large applications, centralized control and processing logic in the servlet – the greatest plus of MVC is also its weakness. Consider a mediocre application with 15 JSPs. Assume that each page has five hyperlinks (or five form submissions). The total number of user requests to be handled in the application is 75. Since we are using MVC framework, a centralized controller servlet handles every user request. For each type of incoming request there is “if” block in the doGet method of the controller Servlet to process the request and dispatch to the next view. For this mediocre application of ours, the controller Servlet has 75 if locks. Even if you assume that each if block delegates the request handling to helper classes it is still no good. You can only imagine how bad it gets for a complex enterprise web application. So, we have a problem at hand. The controller Servlet that started out as the greatest thing next to sliced bread has gone bad. It has put on a lot of weight to become a Fat Controller.
First Look at struts

In Struts, there is only one controller servlet for the entire web application. This controller servlet is called ActionServlet and resides in the package org.apache.struts.action. It intercepts every client request and populates an ActionForm from the HTTP request parameters. ActionForm is a normal JavaBeans class. It has several attributes corresponding to the HTTP request parameters and getter, setter methods for those attributes. You have to create your own ActionForm for every HTTP request handled through the Struts framework by extending the org.apache.struts.action.ActionForm class. Consider the following HTTP request for http://localhost:8080/App1/create.do?firstName=John&lastName=Doe. Suppose class MyForm extends the org.apache.struts.action.ActionForm class and contains two attributes – firstName and lastName. It also has getter and setter methods for these attributes. For the lack of better terminology, let us coin a term to describe the classes such as ActionForm – View Data Transfer Object. View Data Transfer Object is an object that holds the data from html page and transfers it around in the web tier framework and application classes.
The ActionServlet then instantiates a Handler. The Handler class name is obtained from an XML file based on the URL path information. This XML file is referred to as Struts configuration file and by default named as struts-config.xml. The Handler is called Action in the Struts terminology. And you guessed it right! This class is created by extending the Action class in org.apache.struts.action package. The Action class is abstract and defines a single method called execute(). You override this method in your own Actions and invoke the business logic in this method. The execute() method returns the name of next view (JSP) to be shown to the user. The ActionServlet forwards to the selected view.
Jun 13, 2008
Hello World With JNI
Java Native Interface (JNI) can be used to call native code from your Java application. I needed to call a function from a DLL file. Basically JNI addresses interoperability issues and lets your Java code access legacy system. Here I want to share basic “Hello World” application with you which I developed using JNI.
Starting with Java side, all you need to keep in mind while coding is that you have to declare signature of all legacy methods you need to access. All those methods must be declared with native modifier.
Secondly you need to load native library. That you can achieve using System.loadLibrary(). It will try to load library file from basic operating system library location. e.g. WINDOWS\system32 in windows operating system. If you want to provide a specified location, you can use System.load(String filePath) method.
This is how I code HelloWorld.java.
package com.jay.jni;
public class HelloWorld
{
static
{
System.loadLibrary("TestDll");
}
public static void main(String ar[])
{
System.out.println("Hello world from Java");
HelloWorld t=new HelloWorld();
String strFromDLL = t.inDll();
System.out.println(""+strFromDLL);
}
public native String inDll();
}
Next step is to create a header file. For that you need to run following command
javah -jni com.jay.jni.HelloWorld
This will create a header file with name “com_jay_jni_HelloWorld.h”. Generate header file will be as follow.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_jay_jni_HelloWorld */
#ifndef _Included_com_jay_jni_HelloWorld
#define _Included_com_jay_jni_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_jay_jni_HelloWorld
* Method: inDll
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_jay_jni_HelloWorld_inDll
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Note the package name in header file. Most of the time people copies code from internet and tries to run program after modification in package and/or class name. You need to be very careful while dealing with JNI.
Now comes native code portion. I created a MFC DLL project in VC++.
Once you create a simple DLL project, add three header files into your project.
1. com_jay_jni_HelloWorld.h
2. jni.h
3. jni_md.h
Second and third can be found in
For that I created a header file my application TesetDLL with name TestDLL.h. Then I added following code into in it at last.
JNIEXPORT jstring JNICALL Java_com_jay_jni_HelloWorld_inDll (JNIEnv * env, jobject jobj)
{
jstring js = (env)->NewStringUTF("Hello From DLL");
return js;
}
That’s all; I build it and created a DLL. Now all I need to do is put my DLL in system library folder (as I used loadLibrary) and run my program.