About nicogiangregorio

I am an italian Software Engineer and Developer, graduated in Computer Engineering (Thesis on Semantic-based Bluetooth with Java for mobile devices). Currently, I work as Java Consultant with a consulting company and for several financial services' projects. Linux and Unix-like operating systems are my companions for almost ten years. I am fallen in love with most beautiful girl in the world. I love to play my Fender Telecaster

Javabeans: an anti-pattern or not?

What a strong title!

There is a lot of misconceptions about javabeans. Current trend is: javabeans are an anti-pattern. And this is in part true. But I prefer to analyze all the issues related to them, so  anyone can have an overall knowledge of what javabeans are and what are not.

First of all let’s see what is a Javabean:

Javabean is onlyspecification, quoting wikipedia:

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are as follows:

  • The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using getsetis (used for boolean properties instead of get) and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters must receive only one argument.
  • The class should be serializable. It allows applications and frameworks to reliably save, store, and restore the bean’s state in a fashion independent of the VM and of the platform.

Now let’s see a classical example of a java bean:


package it.nicogiangregorio.reactor;

import java.io.Serializable;

public class Employee implements Serializable {
 private String firstName;
 private String lastName;
 private String employeeId;
 private boolean isManager;

public Employee() {}

public String getFirstName() {
 return firstName;
 }

public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

public String getLastName() {
 return lastName;
 }

public void setLastName(String lastName) {
 this.lastName = lastName;
 }

public String getEmployeeId() {
 return employeeId;
 }

public void setEmployeeId(String employeeId) {
 this.employeeId = employeeId;
 }

public boolean isManager() {
 return isManager;
 }

public void setManager(boolean isManager) {
 this.isManager = isManager;
 }
}

This is a very simple class, representing an Employee with 4 very basic properties:

  • first name;
  • last name;
  • employee identifier;
  • isManager: whether the employee is a manager or not;

Criticism to Java beans

While Java beans are very common and omnipresent in java code base, there is a bunch of aspects to take into consideration about them.

Most of the OOP purists consider them very harmful to source code of any application and claim that Java beans violate some of basic principles of Object Oriented Programming. So nowday it is very common to listen to “java beans is an anti-pattern”.

Ok, but why? What are the principles java beans violate?

This little snippet of code:


Employee employee = new Employee();

Instantiate a new object called employee with the base constructor from java-bean previously defined.

While this is very common, this creates an empty object, with an inconsistent state.

OOP principles assert that every object must own a valid state, but in our case what does employee represent?

It is an empty employee with no properties, so the answer is: NOTHING.

An employee object has a sense only if there is an associated employeeId or with the pair firstName – lastName.

So a valid constructor may be:


Employee employee = new Employee(employeeId)

Or


Employee employee = new Employee(firstName, lastName)

Furthermore, the constaints of define an accessor and mutator method for each property creates a lot of boilerplate.

And the last, but not the least: Javabeans make a class mutable even if it is not strictly necessary. So javabeans require an extra effort in handling thread-safety (an immutable class is always thread safety!).

Advantages of Javabeans

There is a very simple and valuable advantage of javabeans: is a convention.

While it may seem very poor motivation, this is, imho, very important. Many people complain about Java fragmentation, and they are right:

too many frameworks, too many ways of doing the same thing, too many parties. Javabeans seem to accord everyone and represent a common feature all over the java world.

Here a very incomplete list of java frameworks\API, adopting java beans:

– JSF;

– Jersey;

– Jaxb;

– Struts;

– DWR;

– JSP;

– JAX-WS;

..and many other.

Conclusion

In my opinion, while Javabeans are very controversial and violate some common and widely adopted design principles, they are a very useful convention between java frameworks. So my suggestion is use them judiciously:

if a framework requires Javabeans, don’t be scared to use them, but don’t abuse it, don’t create a class with multiple responsibility and mask it as a javabean, that is only a lie.

Don’t call extra business logic within javabean and restrict their adoption only as a mutable representation of an entity in your domain.

Breaking singleton pattern

All over the web you can find several articles describing and motivating the “evilness” beyond singletons.

A brief recap.

Singleton is one of the most used and abused design pattern available from GoF. While it is everywhere, it is now considered an anti-pattern, for a bunch of good reasons:

Difficult to test: It is quite difficult to isolate code inside a singleton without starting a real istance of it. Just imagine if your singleton starts a server… the test becomes very painful, hard to start, long to run and impossible to mock.

Thread safety: it is very easy to forget even the most basic thread safety rule when implementing the singleton pattern.

Global State: singletons instroduce global state into a program and this generates a tie between classes. It is widely accepted that code loosely coupled is easier to maintain, extend, use, fix.

The focus of this article is on thread safety and I want to demonstrate how to break a singleton bad coded..and how to avoid it.

Let’s start to code:

Here a bad implemented singleton:


package it.nicogiangregorio;

public class WorstSingleton {
   private static WorstSingleton oldSingleton;

   public static WorstSingleton getInstance() {

   if (oldSingleton == null) {
     oldSingleton = new WorstSingleton();
   }
   return oldSingleton;
  }

 private WorstSingleton() {

   try {
      Thread.sleep(5000);
   } catch (InterruptedException e) {
   // TODO Auto-generated catch block
      e.printStackTrace();
   }
 }
}

Inside the constructor the code: Thread.sleep(5000); helps simulate a computational expensive operation, such as a DB connection creation or other resource acquisition.

Then we need a starter class that is used to instantiate the singleton and prints the hashcode of the object.


package it.nicogiangregorio;

public class SingletonStarter implements Runnable {

@Override
 public void run() {
 System.out.println(WorstSingleton.getInstance().hashCode());
}
}

And now we write a Client class that will start N-threads of SingletonStarter that will run concurrently.


package it.nicogiangregorio;

public class Client {
 public static void main(String[] args) {
 for (int ii = 0; ii < 10; ii++) {
 new Thread(new SingletonStarter()).start();
 }
 }
}

In the main it starts 10 thread each one trying to instantiate a new instance of our ugly singleton. Run and see the output!!

14978587
14978587
14978587
14978587
25669322
25669322
3195425
25669322
14978587
18426253

Argh!! How many instances!!!! Awful! We want one and only one object and the result is a resource leak.

Now let’s see a solution hugely adopted in the java version pre Java 1.5:


package it.nicogiangregorio;

public class FixedSingleton {
 private final static FixedSingleton fixedSingleton = new FixedSingleton();

public static FixedSingleton getInstance() {

return fixedSingleton;
 }

private FixedSingleton() {

try {
 Thread.sleep(5000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
}

The subtle technique to obtain thread safety is to create a final static field. The JVM specification guarantees initialiser will be executed only once, at class load time, via:

new FixedSingleton();

Re-write the starter class:


package it.nicogiangregorio;

public class SingletonStarter implements Runnable {

@Override
 public void run() {

 System.out.println(FixedSingleton.getInstance().hashCode());

 }
}

The Client class remains the same.

Output now is:

25669322
25669322
25669322
25669322
25669322
25669322
25669322
25669322
25669322
25669322

Wonderful!!! It works!!!

Wait..wait.. This solution works, yes, but still there are some issues to take into consideration.

1. If there are more then one Classloader, you are in trouble. It might happen that a singleton is started from two different classloader and you have two isntances. But it is very rare. The real problem is that your code is still vulnerable to reflection attacks!

Reflection can exploit these kind of issues to generate more than one instance of our singleton.

2. Serialization, you have to implement serialization policy if it is needed by your singleton.

Starting from Java 1.5 you have one more solution, more elegant, fully working, without drawbacks (as far as I know).

Singleton code:


package it.nicogiangregorio;

public enum OptimalSingleton {
 INSTANCE;

OptimalSingleton() {
 try {
 Thread.sleep(5000);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
}

Thread starter:


package it.nicogiangregorio;

public class SingletonStarter implements Runnable {

@Override
 public void run() {

System.out.println(OptimalSingleton.INSTANCE.getClass().hashCode());

}
}

And the client remains the same.

The output will be:

19770577
19770577
19770577
19770577
19770577
19770577
19770577
19770577
19770577
19770577

Even this time we obtain a correct result, but the difference with the previous one is that now we have serialization and the enum is not vulnerable to Reflection attacks.

Special thanks to Francesco Fontana (maybe the link is to an empty page..there is one developer lazier than me!).

Feel free to leave a comment:

AJAX captcha – with jQuery and Java

Hi all,

In this article I show how to develop a jQuery captcha for your forms,
using Java and servlets, fully ajaxified.

The result will be:

You can download the source code from here.

These kind of topics, typically are posted by php and web developers, who have to face with a common problem: spammers.

Well, don’t forget that this matter is for Java developers, too.

Captchas let to stop spammers from automatically and repeatidly registering to your site through forms and invading your database of contacts with fake registrations.

I admit that rarely I needed this kind of protection and this is not so very simple to enable with Java.

Furthermore, there is not a wide documentation available on the web and googling leads to several, different solutions.

Maybe jCaptcha is what you are looking for, but googling I found a wonderful jQuery plugin, very user-friendly:
sexy-captcha.

It is a drag and drop captcha, full-ajaxified, and very user-friendly (read as “idiot proof”).

For a demo, please visit this page from the plugin’s author: DEMO

Let’s start with code!!!!

The most significant work for me about this was to adapt PHP code to Java code, then I clean code using some design pattern more adequate for this application.

Technologies involved:

  • JSP;
  • Servlet;
  • JSTL;
  • JRE6;
  • Apache Tomcat 7 (but any java application server could be used);
  • jquery and sexy-captcha plugin.

In this case I prefer to use simple and plain Java solution, avoiding frameworks, in order to show only how to perform an AJAX call to check and refresh captcha submission.
Anyway, it is simple to adapt this code to whatever java frameworks you prefer.

As IDE for development I used Eclipse.
First of all create a new Web Dynamic Project, as usual, within Eclipse. Call it: captcha.

I use default configurations, so jsp will be by default under WebContent folder.

Then we need to import JSTL library that will perform JSP dynamic renderization

You can download them from here.

The configuration is quite stright-forward:

  • Import them by right clicking on project –> properties –> Java build path –> tab: Libraries –> Add External Jars.
  • Additional, mandatory step: copy the jars into /WEB-INF/lib

Now we have the Eclipse project set up and ready to code.

Let’s begin from JSP.

Under WebContent, create a new jsp called index.jsp (that by default is the welcome-file in the WEB.xml).

index.jsp:


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Captcha</title>
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/sexy-captcha/styles.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.sexy-captcha-0.1.js"></script>
<script>
 $("document").ready(function() {
 $('.myCaptcha').sexyCaptcha('CaptchaServlet');

});
</script>
</head>
<body>
 <form id="test-form" action="">
 <div class="myCaptcha"></div>
 </form>
</body>
</html>

As you can see there are some javascript libraries imported. I suggest to download the pack from sexy-captcha blog.

Then unpack it and copy the folders and files under WebContent folder of our Eclipse project.

Servlet.

Add a new servlet to project:
right click on project → new →  Servlet → package name: it.nicogiangregorio.servlets and servlet name: CaptchaServlet.java

Then type the following code:
——-


package it.nicogiangregorio.servlets;

import it.nicogiangregorio.core.CaptchaContext;
import it.nicogiangregorio.core.impl.CaptchaRefreshAction;
import it.nicogiangregorio.core.impl.CaptchaVerifyAction;
import it.nicogiangregorio.utils.WebConstants;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CaptchaServlet
 */
@WebServlet("/CaptchaServlet")
public class CaptchaServlet extends HttpServlet {

/**
 *
 */
 private static final long serialVersionUID = -243950967076586170L;

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 */
 protected void doPost(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException {

String forwardJsp = null;
 String action = request.getParameter(WebConstants.PARAM_ACTION);

CaptchaContext captchaCtx = new CaptchaContext();

if (WebConstants.ACTION_VERIFY.equals(action)) {

captchaCtx.setCaptchaAction(new CaptchaVerifyAction());

} else if (WebConstants.ACTION_REFRESH.equals(action)) {

captchaCtx.setCaptchaAction(new CaptchaRefreshAction());

} else {
 System.out.println("Undefined behaviour due to unexpected action.");
 }

forwardJsp = captchaCtx.processCaptcha(request, response);
 getServletContext().getRequestDispatcher(forwardJsp).forward(request,
 response);
 }
}

The doPost() method let to perform to actions:

  • VERIFY action, to check captcha submitted by user;
  • REFRESH action, to refresh captcha question;

Elaboration is done by classes with some business logic. I’ll show them in a while, again.
And finally redirects output to returned jsp.

I use a bunch of constants all stored into a Java class.

WebConstants.java
——-


package it.nicogiangregorio.utils;

/**
 *
 * Constants class
 *
 * @author Nico Giangregorio
 *
 */
public class WebConstants {
 public static final String NICK_DEMO = "nick_demo";
 public static final String PARAM_ACTION = "action";
 public static final String ACTION_VERIFY = "verify";
 public static final String ACTION_REFRESH = "refresh";
 public static final String ATTR_CAPTCHA_ANSWER = "captchaAnswer";
 public static final String ATTR_CAPTCHA_CODES = "captchaCodes";
 public static final String VERIFY_RESULT = "VerifyResult";
 public static final String PARAM_CAPTCHA = "captcha";
 public static final String PARAM_CAPTCHA_SUBSTR = "draggable_";
 public static final String VERIFY_RESULT_SUCCESS = "success";
 public static final String VERIFY_RESULT_FAILED = "failed";
 public static final String VERIFY_FORWARD_JSP = "/verify.jsp";
 public static final String REFRESH_FORWARD_JSP = "/refresh.jsp";
 public static final String ERROR_FORWARD_JSP = "/error.jsp";
 public static final String ATTR_CAPTCHA_IMAGES = "captchaImages";
 public static final String ATTR_RIGHT_ANSWER = "rightAnswer";

// Enforce non-istantiability
 private WebConstants() {
 }
}

Note:
you can use static import, here I avoided it due to readability.

Now let’s what business logic does.
First of all, the application can do 2 simple things:

  • Verify the captcha;
  • Refresh the captcha;

So, our CaptchaServlet can perform two different actions, depending on what the user wants and finally forwarding the result of this computation to two different JSP, rendering result that will be the AJAX response.

In order to achieve this goal, I think it is better to implement the Strategy design pattern.
With this pattern, the application choose at runtime which algorithm adopt to provide computation required by user.

The strategy interface, package it.nicogiangregorio.core and interface ICaptchaAction.java:


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CaptchaContext {
 private ICaptchaAction captchaAction;

public void setCaptchaAction(ICaptchaAction captchaAction) {
 this.captchaAction = captchaAction;
 }

public String processCaptcha(HttpServletRequest request,
 HttpServletResponse response) {
 return captchaAction.process(request, response);
 }
}

The two possible strategies for captcha app are two implementation of this interface.
Let’s start with strategy related to refresh action.

REFRESH.

Refreshing allows to user, to generate a new question for him.
CaptchaRefreshAction.java


package it.nicogiangregorio.core.impl;

import it.nicogiangregorio.core.ICaptchaAction;
import it.nicogiangregorio.utils.CaptchaEnum;
import it.nicogiangregorio.utils.CaptchaGenerator;
import it.nicogiangregorio.utils.WebConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Strategy for Refreshing action: Reset captcha order and right answer to
 * captcha question, then forward to correct jsp otherwise forward to a courtesy
 * jsp
 *
 * @author Nico Giangregorio
 *
 */
public class CaptchaRefreshAction implements ICaptchaAction {

@Override
 public String process(HttpServletRequest request,
 HttpServletResponse response) {

Map<CaptchaEnum, String> captchaCodes = new HashMap<CaptchaEnum, String>();

try {
 captchaCodes.put(CaptchaEnum.STAR,
 CaptchaGenerator.createCaptchaCodes());
 captchaCodes.put(CaptchaEnum.HEART,
 CaptchaGenerator.createCaptchaCodes());
 captchaCodes.put(CaptchaEnum.BWM,
 CaptchaGenerator.createCaptchaCodes());
 captchaCodes.put(CaptchaEnum.DIAMOND,
 CaptchaGenerator.createCaptchaCodes());

} catch (IllegalStateException e) {
 return WebConstants.ERROR_FORWARD_JSP;
 }

int index = new Random().nextInt(captchaCodes.size());
 CaptchaEnum rightAnswer = CaptchaEnum.values()[index];

request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_ANSWER,
 captchaCodes.get(rightAnswer));

request.getSession().setAttribute(WebConstants.ATTR_RIGHT_ANSWER,
 rightAnswer);

request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_CODES,
 captchaCodes);

return WebConstants.REFRESH_FORWARD_JSP;
 }
}

It simply creates a map of images available for captchas and associates for each image a random generated identifier.

The list of images and other CSS data associated with each of them is stored into CaptchaEnum.

Then it elects one the 4 captcha available that will be the “right answer”.

At the end it sends the attributes with results of elaboration to HTTP session.

Please, before writing your own custom implementation remember that object in HttpSession should be serializable as servlet specification requires.

In our case, the enum is CaptchaEnum.java:


package it.nicogiangregorio.utils;

/**
 * Associate CSS info to a given image and enumerate them. This is immutable
 * andserializable. It strongly replaces a bean
 *
 * @author Nico Giangregorio
 *
 */
public enum CaptchaEnum {
 STAR("-120px", "-3px", "-120px", "-66px"), HEART("0", "-3px", "0px",
 "-66px"), BWM("-56px", "-3px", "-56px", "-66px"), DIAMOND("-185px",
 "-3px", "-185px", "-66px");

private final String onTop;
 private final String onLeft;
 private final String offTop;
 private final String offLeft;

CaptchaEnum(String onTop, String onLeft, String offTop, String offLeft) {
 this.onTop = onTop;
 this.onLeft = onLeft;
 this.offTop = offTop;
 this.offLeft = offLeft;
 }

public String getOnTop() {
 return onTop;
 }

public String getOnLeft() {
 return onLeft;
 }

public String getOffTop() {
 return offTop;
 }

public String getOffLeft() {
 return offLeft;
 }

}

As every enum it is serializable and immutable, so we don’t have to be worried about concurrency and serialization.

The classes that generates this random identifiers is:
package:
it.nicogiangregorio.utils

class:
CaptchaGenerator.java
———-


package it.nicogiangregorio.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import sun.misc.BASE64Encoder;

/**
 * Helper class to generate random code to associate with captcha
 *
 * @author Nico Giangregorio
 *
 */
public class CaptchaGenerator {

private CaptchaGenerator() {
 }

public static String createCaptchaCodes() {

MessageDigest digest = null;
 byte[] result = {};

SecureRandom rand = new SecureRandom();
 BASE64Encoder encoderToBase64 = new BASE64Encoder();

try {

digest = MessageDigest.getInstance("SHA-256");
 digest.update(WebConstants.NICK_DEMO.getBytes());

} catch (NoSuchAlgorithmException e) {
 throw new IllegalStateException(e);
 }

String randString = "" + rand.nextDouble();
 result = digest.digest(randString.getBytes());

return encoderToBase64.encode(result);
 }
}

starting from a random generated number from SecureRandom and with a Salt it creates an hashed string, using SHA-256.

It is a singleton..

And now..

VERIFY

The verify strategy checks if user submitted the correct captcha answer.

package:
it.nicogiangregorio.core.impl

class:
CaptchaVerifyAction.java

—–


package it.nicogiangregorio.core.impl;

import it.nicogiangregorio.core.ICaptchaAction;
import it.nicogiangregorio.utils.WebConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CaptchaVerifyAction implements ICaptchaAction, WebConstants {

@Override
 public String process(HttpServletRequest request,
 HttpServletResponse response) {
 String hashCaptcha = request.getParameter(PARAM_CAPTCHA).substring(
 PARAM_CAPTCHA_SUBSTR.length());
 String captchaAnswer = (String) request.getSession().getAttribute(
 ATTR_CAPTCHA_ANSWER);
 String result;

if (captchaAnswer.equals(hashCaptcha))

 result = VERIFY_RESULT_SUCCESS;
 else {

 request.getSession().setAttribute(ATTR_CAPTCHA_CODES, null);
 request.getSession().setAttribute(ATTR_CAPTCHA_ANSWER, null);
 result = VERIFY_RESULT_FAILED;
 }

request.getSession().setAttribute(VERIFY_RESULT, result);
 return VERIFY_FORWARD_JSP;
 }
}

Very simple and straight-forward.

Next we need to manage the correct strategy, with a context class:

package:
it.nicogiangregorio.core

class:
CaptchaContext
——-


package it.nicogiangregorio.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CaptchaContext {
 private ICaptchaAction captchaAction;

public void setCaptchaAction(ICaptchaAction captchaAction) {
 this.captchaAction = captchaAction;
 }

public String processCaptcha(HttpServletRequest request,
 HttpServletResponse response) {
 return captchaAction.process(request, response);
 }
}

It lets the application to select which strategy to use and finally performs processing.
Note: it returns what single strategies return, i.e. the right JSP to forward.

Each strategy and\or action, need to forward results of elaboration to one dedicated JSP, so create two new jsp:

verify.jsp
refresh.jsp

The names are self-explanatory.

This time we begin with (under WebContent)

verify.jsp:
—–


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" import="it.nicogiangregorio.utils.WebConstants"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="VERIFY_RESULT"
 value="<%=request.getSession().getAttribute(WebConstants.VERIFY_RESULT) %>"></c:set>
 <c:set var="VERIFY_SUCCESS"
 value="success"></c:set>
<c:choose>
<c:when test="${VERIFY_RESULT eq VERIFY_SUCCESS }">
 {'status': 'success'}
</c:when>
<c:otherwise>
 {'status': 'error'}
</c:otherwise>
</c:choose>

We generate a JSON output that is the response to JQuery sexy-captcha plugin. Next the jsp returning the updated html frame with captcha:

refresh.jsp

—-


<%@page import="it.nicogiangregorio.utils.CaptchaEnum"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" import="it.nicogiangregorio.utils.WebConstants"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

&nbsp;

&nbsp;
<c:set value="<%=request.getSession().getAttribute(WebConstants.ATTR_CAPTCHA_CODES) %>" var="ATTR_CAPTCHA_CODES"></c:set>
<c:set value="<%=request.getSession().getAttribute(WebConstants.ATTR_CAPTCHA_ANSWER) %>" var="ATTR_CAPTCHA_ANSWER"></c:set>
<c:set value="<%=request.getSession().getAttribute(WebConstants.ATTR_RIGHT_ANSWER) %>" var="ATTR_RIGHT_ANSWER"></c:set>

<div class="captchaWrapper" id="captchaWrapper"><c:foreach items="<%=it.nicogiangregorio.utils.CaptchaEnum.values() %>" var="captchaImage" varstatus="status">
 <a class="captchaRefresh" href="http://www.blogger.com/blogger.g?blogID=9091569893597347511#"></a>
 </c:foreach>

<div class="draggable" id="draggable_${ATTR_CAPTCHA_CODES[captchaImage]}" style="background-position: ${captchaImage.onTop} ${captchaImage.onLeft}; left: ${ ((status.count - 1) * 68) + 15 }px;"></div><div class="targetWrapper"><div class="target" style="background-position: ${ATTR_RIGHT_ANSWER.offTop } ${ATTR_RIGHT_ANSWER.offLeft };"></div></div><input class="captchaAnswer" name="captcha" type="hidden" value="">
</div>

It takes attributes from session and uses them to render a new snippet of HTML with refreshed captcha values.

That’s all.

Here our amazing captcha:

Download source code from github.

UPDATE: I edited some code on github and consequently this post. Now everything looks better and the app is 1.5+ compliant.

References:

Fresh new articles…coming soon

It’s been a long time since I published last article on this blog.But..As soon as possible I’ll be back!I don’t know yet what to focus on: I recently studied a lot of technologies on several IT areas, Android, C++, Python, Ruby on Rails, Design Patterns, Performance tweaking, Linux.May be the newxt article will be about design patterns…may be not.Stay tuned!

Java Proxy Pattern – Caching proxy

Proxy pattern applied to enable caching – a very simple Web Application

Recently I switched to work for another customer (Bank\Trading) and one of the first activities, in order to offer a more structured and well-designed product to users, was to reduce the overhead and the Database accesses.Considering that I am working on a web portal with 2 millions of contacts per month and hundreds of user accounts, designed and developed more than 10 years ago, it is very difficult to adopt any Java Framework and, in general, to implement whatever big modification.I studied several solutions to optimize the system’s performances.One of the pattern that comes to help in my work is the Proxy Pattern.I’m going to show you some aspects of this pattern, related to caching objects and data.This article is divided into two parts, one for each solution that I found to this issue.We’ll go into a very simple web application: NO dependency injection this time, NO Spring, NO Frameworks, only very simple code.We’ll create a simple web app that on home page will print the timestamp of last created instance of cached object.Consider that this object may be a complex data structure from a database, or a big image or something very painful for server.For our purpose, things are simplified.Well, we can summarize:1. user requires an object2. system check: an instance of this object already is created?3. If no, it create a new instance, otherwise it give back the already made instance.4. The user, transparently, receives the object.Let’s go!Configure Eclipse.Just create a New Dynamic Web Project, I called proxycacheapp.I used this project for both solutions that I’m going to implement.UML Class Diagram of a classical Proxy pattern from original GoF book, is:



And, briefly: the JSP contains the code for execute the request,that is wrapped by Servlet Filter (declared in web.xml as I hope you already know),Servlet Filter calls our ProxyService to achieve what user wants.ProxyService is only a surrogate, if the object required is ready and already created, it give back to user the cached instance, otherwise Proxy calls concrete RealService and require to create a new one.Object (either brand new or cached) is sent to output of ServletFilter, that incapsulate it into HttpRequest and, later Jsp prints it on Web page.Simple.This is a general scenario, but pragmatic implementation, can be made using two different solutions.Solution 1Plain, classical, proxy pattern applied.This solution uses only diagrams and the previous explanation, no more complication.Domain ObjectIt is very useless here, but I want to show you that it is possible to use any custom Object in this approach.Let’s create a new object, a POJO, with an ID and a timestamp..later we’ll print timestamp on JSP.Create new Java Class on Eclipse and write th wolling code (I use it.nickg.utils package):


package it.nickg.utils;

public class Timestamp {
 private long id;
 private String timestamp;

public long getId() {
 return id;
 }

public void setId(long id) {
 this.id = id;
 }

public String getTimestamp() {
 return timestamp;
 }

public void setTimestamp(String timestamp) {
 this.timestamp = timestamp;
 }
}

This is our Domain object.Now let’s implement the Proxy Pattern, first create a new interface (package is it.nickg.services):

package it.nickg.services;

import it.nickg.utils.Timestamp;

public interface TimestampService {

/**
 * retrieve an istance of Timestamp object
 *
 * @return Timestamp object
 */
 public Timestamp getTimestamp();

}

Then let’s write the Real implementationof Service, that creates instance of our Domain Object, it implements our previously created interface:

package it.nickg.services;

import it.nickg.utils.Timestamp;

import java.util.Date;

public class TimestampServiceReal implements TimestampService {

@Override
 public Timestamp getTimestamp() {

Date time = new Date();
 Timestamp timestamp = new Timestamp();

timestamp.setId(time.getTime());
 timestamp.setTimestamp(time.toString());

return timestamp;
 }

}

Not best solution for getting a timestamp,I know, but it is only for a learning purpose. Look at the concept.

package it.nickg.services;

import it.nickg.utils.Timestamp;

public class TimestampServiceProxy implements TimestampService {

private TimestampServiceReal timestampServiceReal;
 public Timestamp timestamp;

@Override
 public Timestamp getTimestamp() {

// Proxy checks if a real instance of service (and of timestamp object)
 // already is created
 if (timestampServiceReal == null) {
 timestampServiceReal = new TimestampServiceReal();
 timestamp = timestampServiceReal.getTimestamp();
 }

// return required object
 return timestamp;
 }
}

Now, It’s time to code our front-end!
Most of the work is done through a ServletFilter that wraps request, calls our services and sets a parameter inHttpResponse, with results.

Servlet Filter must be declared inweb.xml:
(complete web.xml code)


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <filter>
 <filter-name>TimestampFilter</filter-name>
 <filter-class>it.nickg.servlets.TimestampFilter</filter-class>
 </filter>

<filter-mapping>
 <filter-name>TimestampFilter</filter-name>
 <url-pattern>/index.jsp</url-pattern>
 </filter-mapping>

<welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Here Servlet Filter code:


package it.nickg.servlets;

import it.nickg.services.TimestampService;
import it.nickg.services.TimestampServiceProxy;
import it.nickg.utils.Timestamp;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TimestampFilter implements Filter {
 TimestampService tsService = new TimestampServiceProxy();

public TimestampFilter() {
 // TODO Auto-generated constructor stub
 }

@Override
 public void destroy() {
 // TODO Auto-generated method stub

}

@Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
 ServletException {

Timestamp timestamp = null;

// retrieve a timestamp from service
 timestamp = tsService.getTimestamp();
 request.setAttribute("timestamp", timestamp);

// forward output
 chain.doFilter(request, response);
 }

@Override
 public void init(FilterConfig filterConfig) throws ServletException {
 // TODO Auto-generated method stub

}

}

Last step is about editing index.jsp, andlet display the creation’s timestamp of Domain Object:


<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="it.nickg.utils.Timestamp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>">

 <title>Proxy Pattern Example</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 </head>

 <body>
 <h3>Domain object is created:</h3>

<%
 Timestamp timestamp = (Timestamp)request.getAttribute("timestamp");
 out.print(timestamp.getTimestamp());
 %>
 </body>
</html>

I HATE to use scriplet and Java code inJSPs, use jstl, struts taglib, any other technology. Especially in productioncode.

That’s all, now run our server insideEclipse (I use tomcat)
Right click on project -> Run as  -> Server Application.

Now on welcome page, it displays firstcreation timestamp of the object and if you refresh the page, the timestampdoesn’t change:
It is cached!!

Simple, isn’t?

Well, It’s time for more complicatedissues.

Solution 2

A more experienced reader can found myprevious solution a bit like “reinventing the wheel” and it’s in part true,because java offers a Proxy class:

java.lang.reflect.Proxy

Using Java reflection it is possible to implement a more elegant representation of Proxy Pattern.
For a cleaner implementation, we define a TimestampServiceFactory:


package it.nickg.services;

import java.lang.reflect.Proxy;

public class TimestampServiceFactory {
 public TimestampService createService() {
 return (TimestampService) Proxy.newProxyInstance(
 TimestampService.class.getClassLoader(),
 new Class[] { TimestampService.class },
 new TimestampReflectProxy(new TimestampServiceReal()));
 }
}

Here we use Proxy.newProxyInstance() tocall a proxy. It returns an instance of a proxy class for the specifiedinterfaces that dispatches method invocations to the specified invocationhandler(TimestampReflectProxy).
And an interface CacheIFace:


package it.nickg.services;

public interface CacheIFace {

/**
 * Retrieve object from cache
 *
 * @param key
 * @return cached object
 */
 public Object getCache(Object key);

/**
 * Put a new object in cache
 *
 * @param key
 * @param value
 */
 public void putCache(Object key, Object value);
}

and an implementation class Cache:


package it.nickg.services;

import java.util.HashMap;
import java.util.Map;

public class Cache implements CacheIFace {
 private Map<Object, Object> values;

public Cache() {
 this.values = new HashMap<Object, Object>(8);
 }

public Object getCache(Object key) {
 return values.get(key);
 }

public void putCache(Object key, Object value) {
 values.put(key, value);
 }
}

These comes to let us perform cachingfeature through an HashMap:
HashMap IS the cache.
Create a new Java Class named TimestampReflectProxy that implements InvocationHandler:


package it.nickg.services;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

public class TimestampReflectProxy implements InvocationHandler {

private final Object obj;
 private CacheIFace caches;
 private static final Object NullKey = new Object();

public TimestampReflectProxy(Object toProxy) {
 this.obj = toProxy;
 this.caches = new Cache();
 }

@Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

CacheIFace cache = (CacheIFace) caches.getCache(method);

if (cache == null) {
 caches.putCache(method, cache = new Cache());
 }

Object argsList = args != null ? Arrays.asList(args) : NullKey;
 Object cacheValue = cache.getCache(argsList);

if (cacheValue == null) {
 cache.putCache(argsList, cacheValue = method.invoke(obj, args));
 }
 return cacheValue;
 }
}

And, finally, here is the ServletFilter modified:


package it.nickg.servlets;

import it.nickg.services.TimestampService;
import it.nickg.services.TimestampServiceFactory;
import it.nickg.utils.Timestamp;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TimestampFilter implements Filter {
 // TimestampService tsService = new TimestampServiceProxy();
 TimestampServiceFactory tsFactory = new TimestampServiceFactory();
 TimestampService tsService = tsFactory.createService();

public TimestampFilter() {
 // TODO Auto-generated constructor stub
 }

@Override
 public void destroy() {
 // TODO Auto-generated method stub

}

@Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
 ServletException {

Timestamp timestamp = null;

// retrieve a timestamp from service
 timestamp = tsService.getTimestamp();
 request.setAttribute("timestamp", timestamp);

// forward output
 chain.doFilter(request, response);
 }

@Override
 public void init(FilterConfig filterConfig) throws ServletException {
 // TODO Auto-generated method stub

}
}

I try to explain this magic trick.
Our TimestampReflectProxy class has two private attributes, obj and caches.
When user requires the page, theTimestampFilter acts as wrapper, it catches the request and callsTimestampServiceFactory and TimestampService that requires to create theservice.

First time, it passes TimestampServiceRealas Object to  TimestampReflectProxy ‘sconstructor, so:
– obj is an instance ofTimestampServiceReal;
– a new instance of Cache is created;

Then the filter calls getTimestamp()method and this call is caught with reflection:
– it enters in invoke() method,
– it checks if an occurrence of method isalready present in caches,
– there isn’t the required occurrence andso cache is null,
– it puts a new entry in cache;
– then retrieve the args list and checksif there is an entry in cache with given key;
– if not, it create a new one invokingmethod;

From this time, every time the userrefreshs the web page, the application using reflection, finds existing entriesin cache, skips checks, and gives back to him.

Here the results, if you try to refreshthe page, display doesn’t change:

While this second solution seems veryinteresting, advanced, elegant and cool..there are several drawbacks:
(cut and paste from Sun)
Performance Overhead
Because reflection involves types that are dynamically resolved, certainJava virtual machine optimizations can not be performed. Consequently,reflective operations have slower performance than their non-reflectivecounterparts, and should be avoided in sections of code which are calledfrequently in performance-sensitive applications.
Security Restrictions
Reflection requires a runtime permission which may not be present whenrunning under a security manager. This is in an important consideration forcode which has to run in a restricted security context, such as in an Applet.
Exposure of Internals
Since reflection allows code to perform operations that would be illegalin non-reflective code, such as accessing private fields and methods, the useof reflection can result in unexpected side-effects, which may render codedysfunctional and may destroy portability. Reflective code breaks abstractionsand therefore may change behavior with upgrades of the platform.
Some interesting discussions are linkedabove between references.
Enough to avoid it in my particular usecase.
Last thing I want to show.
Perhaps more careful of you have observedthat when an instance of an object is created, it can live forever!
(Well, I know, it’s impossible, but “undefined”and “forever” are both unacceptable in my opinion).
Best way to give the capability ofperiodical refresh of object, is implementing a TimeToLive Strategy. (Otherpossible solutions are LRU and LFU).
I’ll not describe here now, but give yousome input:
Into our Cache class, it is necessary tocode a thread that periodically cleans the cache and you can use whateverpolicy you want.
That’s all folks!
Please, feel free to add comment andcritics to my article, they are very useful.
References:
http://java.dzone.com/articles/design-patterns-proxy
http://java.sys-con.com/node/171489
About Reflection:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
About reflection performances:
http://stackoverflow.com/questions/435553/java-reflection-performance
http://www.jguru.com/faq/view.jsp?EID=246569

Busy!!

Hi there,
I wish to publish some new articles here, but, believe, it is a bad period for me.. a lot of troubles that have the ability to come always together prevent me from post new stuff.
BUT..
Don’t worry! I’m spoilt for choice about arguments.
As soon as possible, new comings! 😉

Spring, Struts 2 – part 2

Adding database management.

According to previous article, now I am going to show how to manage a database within our previous created web application.
The result is a very simple application, but I hope it will be useful to understand the way to perform similar tasks.

For this purpose, I will use:

* HSQLDB, a data leading SQL relational database engine written in Java, I think I’ll write an article about it as soon as possible..It is very interesting and powerful.
* Hibernate, ORM that no needs presentations!
* Spring Framework, especcialy Transaction Manager, I think that it is an underestimated feature of framework.

Our application will retrieve from database some records containing strings that will be printed in a jsp (they will print a classical Hello World message).

First Step: configuring HSQLDB database

Download latest version of hsqldb database, currently is 2.0.0 (rc9). Then I follow instructions from website and report here:

depending on platform you use (Windows or Linux or whatever you prefer) the procedure to be followed is almost the same.

* uncompress the zip folder downloaded from website;
* start HSQLDB server: under installation folder type ‘cd data’ and then ‘@java -classpath ../lib/hsqldb.jar org.hsqldb.server.Server %1 %2 %3 %4 %5 %6 %7 %8 %9’ (wait for completion of boot process);
* run an SQL client to connect to database server. I use MyEclipse IDE, but anyone can be used, the default connection parameters (if you just downloaded hsqldb package) are: connection URL jdbc:hsqldb:hsql://localhost/ , username SA , password ; for further configuration issues, I suggest to read HSQLDB wiki, it is very helpful and quick.
* Create new table with name HELLO, columns are: ID, PHRASE (ID must be set as numeric primary key, not nullable and incrementable, while PHRASE is a VARCHAR(15));
* Insert new records in that table (follow my same order): ID:1 – PHRASE:’Hello ‘, ID:2 – PHRASE:’World! ‘, ID:3 – PHRASE:’This data ‘, ID:4 – PHRASE:’is stored ‘, ID:5 – PHRASE:’in database ‘;

Second Step: configuring Hibernate project

This step is simple for me, making use of MyEclipse and I hope also for you, guessing the procedure to follow is similar.

First of all I create an external (referred in main one) project that will be used as Hibernate’s project, from my IDE I click on “Create new Java Project” and once it is created, I right-click on it and then “Add Hibernate Capability”. I give it the name: “hibernate-mapping”.

Libraries:

Typically, in creation window, the IDE ask to user for innformation about database, here you have to put connection url, username etc etc. Let to create SessionFactory.
Now is time to create mapping between database and POJO. With MyEclipse this thing is very simple:
Just, right-click on table you want to map (in our case is HELLO) -> Hibernate Reverse Engineering ->
In popup window select previously created project’s source folder (Hibernate project), select only “Create POJO”, select “Java Data Object” -> Finish.

Now you should have something similar to this:

Now we create a new Web Application (it is the same used in previous posted article, with a few of modifies) and import the hibernate project as dependency of this project.
This is our main project.
Main project integrates Struts2 and Spring and for this reason I suggest to read this to full understand the code shown below.
Action code:


package it.nickg.webapp.web.actions;

import it.nickg.webapp.services.HelloService;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {

private HelloService helloService;
private List words;

public List getWords() {
return words;
}

public void setWords(List words) {
this.words = words;
}

public HelloService getHelloService() {
return helloService;
}

public void setHelloService(HelloService helloService) {
this.helloService = helloService;
}

@Override
public String execute() throws Exception {

words = helloService.getWords();
return SUCCESS;
}
}

Business service interface:


package it.nickg.webapp.services;

import java.util.List;

public interface HelloService {

public abstract List getWords();
}

Business service implementation:


package it.nickg.webapp.services.impl;

import it.nickg.hibernate.mapping.Hello;
import it.nickg.webapp.DAO.HelloDAO;
import it.nickg.webapp.services.HelloService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class HelloServiceImpl implements Serializable, HelloService {

private HelloDAO helloDao;

public void setHelloDao(HelloDAO helloDao) {
this.helloDao = helloDao;
}

public List<string> getWords() {

List<Object><p>

phrases = (List) helloDao.getPhrases();

List<string> words = new ArrayList<string>();

for (Iterator<Object> iterator = phrases.iterator(); iterator.hasNext();){

String word = ((Hello) iterator.next()).getPhrase();

words.add(word);

}

return words; }

}

DAO Interface:


package it.nickg.webapp.DAO;

import java.util.Collection;

import org.hibernate.SessionFactory;

public interface HelloDAO {

public abstract void setSessionFactory(SessionFactory sessionFactory);

public abstract Collection<object> getPhrases();

}

DAO Implementation:


package it.nickg.webapp.DAO.impl;

import it.nickg.hibernate.mapping.Hello;
import it.nickg.webapp.DAO.HelloDAO;

import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HelloDaoImpl implements HelloDAO {
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public Collection<Object> getPhrases() {

Collection phrases;

Session session = this.sessionFactory.getCurrentSession();

phrases = session.createCriteria(Hello.class).list();

return phrases;

}

}

At this point, the essential point of integration, applicationContext.xml file. Adding this lines lets Spring to manage datasource:


&nbsp;

<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"></property>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"></property>
<property name="username" value="sa"></property>
<property name="password" value=""></property>
</bean>

Then define Hibernate’s SessionFactory, within Spring management:


<bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="myDataSource"></property>
<property name="mappingResources">
<list>
<value>it/nickg/hibernate/mapping/Hello.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
</property>
</bean>

Now, let’s define Dependency Injection, briefly: inject SessionFactory into DAO, DAO into Service, Service into Action and applicationContext.xml will look as shown below:


<beans xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"></property>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"></property>
<property name="username" value="sa"></property>
<property name="password" value=""></property>
</bean>

<bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="myDataSource"></property>
<property name="mappingResources">
<list><value>it/nickg/hibernate/mapping/Hello.hbm.xml</value></list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
</property>

</bean>

<bean class="it.nickg.webapp.DAO.impl.HelloDaoImpl" id="helloDao">
<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

<bean class="it.nickg.webapp.services.impl.HelloServiceImpl" id="helloService">
<property name="helloDao" ref="helloDao"></property>

</bean>

<bean class="it.nickg.webapp.web.actions.HelloAction" id="helloAction">
<property name="helloService" ref="helloService"></property>
</bean>
</beans>

BUT, if you try to run application an Hibernate exception will prevent it from working, because Transaction Management misses. There are many choices for Transaction management, I prefer to use the annotation-base approach, which requires to add this lines at applicationContext.xml:


<tx:annotation-driven transaction-manager="txManager">
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="txManager">
<property name="dataSource" ref="myDataSource"></property>
</bean>

</tx:annotation-driven>

Final applicationContext.xml will be:

and to add @Transactional over each (concrete) classes that make use of transaction; in our case these are the services’ ones. NOTE: at this point hibernate.cfg.xml can be deleted! Datasource definition and links are defined and handled through Spring configuration file, there is no more need of another external xml file. Add ‘@Transactional’ on top of HelloServiceImpl:


@Transactional
public class HelloServiceImpl implements Serializable, HelloService {

private HelloDAO helloDao;

public void setHelloDao(HelloDAO helloDao) {
this.helloDao = helloDao;
}

public List<string> getWords() {

List<object><p>

phrases = (List) helloDao.getPhrases();

List<string> words = new ArrayList<string>();

for (Iterator<Object> iterator = phrases.iterator(); iterator.hasNext();) {

String word = ((Hello) iterator.next()).getPhrase();

words.add(word); } return words;

}

}

JSPs, as explained in previous posted article, work in this way: index.jsp redirects to hellopage.action that, in turn, redirects to success.jsp. index.jsp:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:redirect url="hellopage.action">
</c:redirect>

success.jsp:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<s:iterator value="words"><s:property></s:property>
</s:iterator>

Result shown on web page is this:

I hope this article will be useful to someone, feel free to leave a feedback here.