Shaun Abram
Java and Technology weblog
Singleton implementations
A singleton is a class that is instantiated exactly once (or at least, once per classloader). It is considered to be an anti-pattern by many (including me!) because it makes unit testing difficult. You can’t substitute a mock implementation for a singleton (unless it happens to implement an interface, which I haven’t seen too often). And singletons also make your APIs into liars.
However, if you do want/have to use singletons, this article discusses the best approach.
Tags: singleton
HelloWorld: JSP -> Servlet
A while ago, I posted a simple HelloWorld Html->Servlet->JSP setup. Even thought the html part is unnecessary (a jsp can obviously handle that alone), I deliberately included it as a template for Html/Servlet/JSP interaction. I have used it a bunch of times to get simple Proof of Concept projects up and running, or as a basis to create a simple browser interface to some server side process.
Most of the more recent projects I have used it on however have used straight JSP->Servlet, with no .html file involved. So I am now posting that setup, including some simple JSTL EL and conditional logic.
Selenium talk at SF JUG
I attended another great San Francisco JUG meeting tonight, this time on How to use Selenium with Maven/Ant to automate testing of web apps.
The talk was given by Chris Bedford, from Build Lackey Labs – “Automating the Monkey Work Out and the Quality In!”. Overall, I thought this was a great talk by Chris. He clearly has a huge amount of experience creating automated tests and integrating them with build tools and he gave a well structured, interesting, well delivered presentation. I have posted a copy of Chris’s slides and I think the video will be posted on the SF JUG site at some point, but I have also posted my notes from the presentation below…
Read more
Tags: JUG, q, selenium, sfjug, Testing, unittesting
Java User Groups and cultivating your career
There is an interesting article here about the importance of User Groups, which links to this one about cultivating your career.
Both definitely worth a read.
Data binding in Spring MVC
Two of the most important tasks carried out by Spring MVC when you submit a form are Data binding and validation.
The following article discusses data binding, including the use of custom PropertyEditors, and some of the options available for registering such editors. Most of the information discussed applies to Spring in general, but its application in Spring MVC is my primary interest.
In a future article I would like to discuss validation including the use of custom error messages.
Note that these notes relate to version 2.5.6 of Spring, the latest production code at time of writing, and depend heavily on the corresponding Spring reference docs.
Data Binding
Spring MVC allows the use of command objects (aka form backing objects, model attributes, domain model objects – basically the objects used to transport data between your view and your controller) using just about any type. However, the Servlet API deals with form parameters as Strings. Spring uses a technique called data binding to covert between the String representation and the real underlying type. This enables user input to be bound to the objects you use to process user input. In other words, the values entered by a user in a form can be used to set the property values on a chosen object.
As well as binding the values, Spring includes support for validation and binding result analysis.
The binding functionality is provided by Spring’s org.springframework.validation.DataBinder class.
And when converting a String to some arbitrary type, DataBinders make use of ProperEditors. PropertyEditors are not Spring specific, but rather part of the JavaBeans API.
Using PropertyEditors
Spring heavily uses the concept of PropertyEditors to effect the conversion between an Object and a String.
Spring has a number of built-in PropertyEditors to make life easy (for a complete list, see here).
If you are using a custom type that Spring is unable to convert to and from a String, you will likely receive a lovely error such as this:
org.springframework.web.bind.ServletRequestBindingException: Errors binding onto object ‘dependsOnExoticType’; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object ‘dependsOnExoticType’ on field ‘type’: rejected value [test]; codes [typeMismatch.dependsOnExoticType.type,typeMismatch.type,typeMismatch.example.ExoticType,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dependsOnExoticType.type,type]; arguments []; default message [type]]; default message [Failed to convert property value of type [java.lang.String] to required type [example.ExoticType] for property ‘type’; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [example.ExoticType] for property ‘type’: no matching editors or conversion strategy found]
The solution is to create your own custom editor.
Creating a custom property editor
A custom property editor should be of type java.beans.PropertyEditor. It tells Spring how to convert to a String and back again. As an example, see the ExoticTypeEditor in the Spring reference docs here.
The question is then how to register the custom editor.
Registering your custom editor
There are several ways to ensure you custom editor gets registered.
1) Put Editor in same package
The simplest way (by far!) is to put the Editor in the same package as the class it handles. This is because the standard JavaBeans infrastructure will automatically discover PropertyEditor classes (without you having to register them explicitly) if they are in the same package as the class they handle, and have the same name as that class, with’Editor’ appended;
However, if putting the Editor in the same package as the class it handlers is not possible (If for example, you are using a custom type from a 3rd party library and hence you don’t have access to the source code), try one of the other options below…
2) CustomEditorConfigurer
Another approach to registering a custom PropertyEditor is to use a special bean factory post-processor called CustomEditorConfigurer.
This is the approach used in the spring reference manual for the ‘ExoticType’ example. Again, see
section 5.4.2.1. Registering additional custom PropertyEditors, here.
The CustomEditorConfigurer is used to register the new PropertyEditor with the ApplicationContext, which will then be able to use it as needed.
Gotchas
The PropertyEditors defined in the ‘customEditorConfigurer’ bean will only be automatically used if you are using an ApplicationContext implementation (i.e. will not work for BeanFactory). This is discussed here.
This approach only works for beans created by the ApplicationContext. The PropertyEditors that are registered via CustomEditorConfigurer are NOT available for use in the data binding infrastructure (this is discussed here and here).
I think this should be made more clear in the spring framework ref docs (although, in fairness, it is covered in the CustomEditorConfigure javadocs).
So, if you are using Spring MVC and dealing with form submission, the next option may be better…
3) Explicitly register your editor in initBinder
So, a better approach, as far as form data binding is concerned, is to explicitly register your editor within initBinder() in the relevant Controller. e.g.
@Controller
@RequestMapping("/exoticView.htm")
public class TestController {
//post and get handling methods etc...
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
}
}
4) Use a WebBindingInitializer
If you find yourself using the above approach (registering your customer editor in initBinder) in many controllers, and you use a annotation based controller (Spring 2.5+), then you can use a WebBindingInitializer to register global property editors.
To do this, create a class that implements the WebBindingInitializer interface, for example
public class GlobalBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
}
}
Then update your web application context file to contain:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="GlobalBindingInitializer"/>
</property>
</bean>
I discovered this approach in a posting on StackOverflow about hidden features of Spring . It means you can register an editor once and use it anywhere. This is now my preferred way to register custom property editors.
5) Use PropertyEditorRegistrar
Another mechanism for registering property editors with the Spring container, and the final one in the Spring reference docs, is to create and use a PropertyEditorRegistrar. See section 5.4.2.1.1 here. The docs say that this is a good approach “when you need to use the same set of property editors in several different situations”. I have used this approach successfully in the past, but to be honest, I don’t quite see the benefits beyond the GlobalBindingInitializer approach above and it seems to require a few more steps. (I also saw some confusing debate on exactly what steps are mandatory here)
6) BeanInfo
There is also a BeanInfo mechanism mentioned in the Spring docs which I admit I have never tried – or fully understood.
HelloWorld: Html -> Servlet -> JSP
A couple of times recently I have had to setup up some very simple code to display on the client side (browser) some values created on the server side based on basic user input.
This has been part of some prototype/proof-of-concept work. I am posting my basic setup as an example in the form of the ubiquitous HelloWorld app. It uses a Html page to receive user input, which is submitted to a Servlet, processed, and the response displayed in a JSP using EL (Expression Language).
Obviously this could be done in various ways, including just JSPs, but this example acts as a template of Html/Servlet/JSP interaction.
1) Create a Html page called HelloWorld.html
<html>
<head>
<title>Greeting Setup - Hello Who?</title>
</head>
<body>
<FORM ACTION="/HelloWorld/HelloWorldServlet">
Enter greeting recipient:
<INPUT TYPE="TEXT" NAME="msg">
<p></p>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</body>
</html>
2) Create a servlet to receive the user input
HelloWorldServlet.java
package com.helloworld;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//get inputs
String msg = req.getParameter("msg");
//any additional processing can be done here
//set outputs
req.setAttribute("msg", msg);
//forward to jsp
req.getRequestDispatcher("/HelloWorld.jsp").forward(req, res);
}
}
3) Create a JSP to display the response
HelloWorld.jsp:
Hello ${msg}
4) Create the web application’s deployment descriptor file:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>HelloWorld.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.helloworld.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
That’s it.
The easiest way I have found for this kind of development is to create in Eclipse as a Dynamic Web Project (available via the Web Tools Platform that comes with the in the “Eclipse IDE for Java EE Developers” package). When you have carried out the above steps, just right click the project -> Run As -> Run on Server (assuming you have a server like Tomcat or GlassFish setup in Eclipse…).
I have attached the source in a war file.
Tags: el, jsp, servlet, webapp
JUG Meetup: Joshua Bloch (Effective Java)
I had the chance tonight to see Joshua Bloch speak at the Silicon Valley Web JUG meetup down at the Googleplex in Mountain View. I have read and blogged about his great book “Effective Java” – probably the single best book I have read on Java – so it was great to hear him in person. The talk covered a couple of examples from his Java Puzzlers book as well as a discussion on some of the items from the Effective Java book. As expected, he was a great presenter, both insightful and funny.
JavaBeans vs Spring beans vs POJOs
The terms JavaBeans, “Spring beans” and POJOs are in widespread use and this article discusses each and the differences between them.
JavaBeans
At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. For example, classes that
- Have a public default (no argument) constructor
- allows access to properties using accessor (getter and setter) methods
- Implement java.io.Serializable
More accurately, JavaBeans are classes that adhere to Sun’s JavaBeans spec, first published way back in 1996. A JavaBean was defined as a “software component model” for Java. The idea was that JavaBeans would be reusable software components that could be manipulated visually in a builder tool and that vendors would create and sell JavaBeans that could be composed together into applications by end users. The three most important features of a Java Bean are
- the set of properties (named attributes) it exposes
- the set of methods it allows other components to call
- the set of events it fires (to notify registered listeners of changes)
POJO
POJO is an acronym for Plain Old Java Object. The term was coined by Martin Fowler et. al., as a ‘fancy’ way to describe ordinary Java Objects that do not require a framework to use, nor need to be run in a application server environment. If is often used to distinguish simpler, lightweight Java objects from ‘heavyweight’ code like EJBs. The use of these kind of lightweight objects in programming is described in books such as “POJOs in Action” and advocated by frameworks like Spring.
Spring beans
A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in a Spring configuration file (or, more recently, by using annotations), instantiated by the Spring container, and then injected into your application.
The reason Spring managed objects are referred to as beans is because in the very early versions, Spring was intended only for use with JavaBeans. That is no longer the case of course: Spring can manage just about any object, even if it doesn’t have JavaBean type characteristics such as default constructors or mutator methods (getters and setters). None the less, the term ‘Spring beans’ has stuck.
Can Spring beans be POJOs? Yes, and they usually are (although they don’t have to be – e.g. Spring can be used with ‘heavyweight’ Java objects, such as EJBs).
Can Spring beans be JavaBeans? As I have said, yes and again they often are but don’t have to be.
Summary
Although it have been well over 10 years since the JavaBeans spec was first published, it still carries weight and has influence the development of modern frameworks such as Spring. But while Java objects that have default constructor and use accessor methods for private fields may legitimately be called JavaBeans, the whole “reusable software component that can be manipulated visually in a builder tool” concept isn’t particularly popular anymore.
POJOs, however, are everywhere and the a backlash against the complexities for EJBs has resulted in widespread use of ‘lightweight’ Java programming.
Spring beans are objects created and managed by the Spring framework.
None of the 3 terms discussed are mutually exclusive. A Java object can be a JavaBean, a POJO and a Spring bean all at the same time.
Tags: JavaBeans, POJO, spring, Sun
Groovy: Cool but slow
I have been learning Groovy recently (as part of Project Euler, a series of Maths programming problems). For the most part, I love it. I particularly like
the easy syntax. Java without the crud!
e.g.
System.out.printlnbecomes simplyprintlnfor (int i-0; i<10; i++)becomesfor ( i in 0..9 )- Accessor methods are autogenerated and used
Sure, the poor IDE support is a little annoying, especially the lack luster code completion and debugging capabilities, but I am sure it will improve soon (especially with SpringSource on the case).
But then I started to notice some slowness when using it. So, I performed a simple performance comparison and the results shocked me.
I wrote an identical loop in both Java and Groovy (see the code below) which simply loops a million times.
- The Java version took ~5ms
- The Groovy version took ~500ms
I was shocked! Could Groovy really be a 100 times slower? I had heard rumors about Groovy being a bit slower than Java, but I hadn’t expected it to be this dramatic. Surely this is drastic enough to stop Groovy being used in serious, production quality projects?
I discussed this with a friend who is a Groovy advocate. He made the following points:
1. I was running with an older, slower version of Groovy
This is true. I ran the tests in Eclipse 3.5, with v1 of the Eclipse Groovy plugin, which uses v1.5.7 of the Groovy compiler.
However, when I downloaded the latest version of Groovy (Version: 1.6.3 with JVM: 1.6.0_13) and ran from the command line, it still took the Groovy code ~200 ms. A huge improvement, but still ~40 times slower than Java.
2. It is an artificial, unrealistic test, as these kind of huge loops are not normal in most programs
This is also true. But although artificial, it is still a straight comparison. Also, these kind of loops aren’t so unusual in Project Euler type problems (at least in my crude brute force solutions!).
There are also some more detailed Java/Groovy performance test results here and here.
So, overall, I think the performance is a big issue. But not enough to stop me using it for pet projects. I am even going to keep trying to use it for Project Euler – it will be more motivation to avoid the brute force solutions. It is however, enough to stop me using it in any serious production apps.
For the record, here is the exact code I ran:
Java version
long max = 1000000;
long start = Calendar.getInstance().getTimeInMillis();
for(int i=0;i<max; i++) {}
long end = Calendar.getInstance().getTimeInMillis();
long duration = end - start;
System.out.println(duration);
Groovy version
long max = 1000000;
long start = Calendar.getInstance().getTimeInMillis();
for(int i=0;i<max; i++) {}
long end = Calendar.getInstance().getTimeInMillis();
long duration = end - start;
println(duration);
It is also worth pointing out that when I changed the Groovy code to use proper Groovy syntax, as in for (i in 1..1000000) is was substantially faster (although still significantly slower than Java), but I have left it as is, for a apples vs apples comparison.
Tags: groovy
Ant build file to redeploy to Tomcat
Here is an example of an ant file that redeploys a web project to tomat. The neat thing is that as well as creating the war file, it also stops and restarts tomcat, all from ant.
I have found myself rewriting variations of this on a couple of projects recently, so I thought it was worth posting…
(Note it doesn’t include a compile target as I am doing it from my IDE)
<project name="{project.name}" basedir="." default="redeploy">
<property file="build.properties"/>
<target name="tomcat-stop">
<java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
<jvmarg value="-Dcatalina.home=${tomcat.home}"/>
<arg line="stop"/>
</java>
</target>
<target name="cleanTomcat" depends="tomcat-stop">
<delete dir="${project.deploydir}"/>
<delete file="${project.deploywar}"/>
</target>
<target name="createWar" depends="cleanTomcat">
<war destfile="${project.deploywar}" webxml="WEB-INF/web.xml">
<lib dir="WEB-INF/lib"/>
<classes dir="WEB-INF/classes"/>
<fileset dir="." includes="*.jsp" />
<fileset dir="WEB-INF"/>
</war>
</target>
<target name="tomcat-start">
<java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
<jvmarg value="-Dcatalina.home=${tomcat.home}"/>
</java>
</target>
<target name="redeploy" depends="createWar,tomcat-start"/>
</project>
And here is an example of the associated build.properties file
tomcat.home=C:/Program Files/Apache/tomcat
project.name=SampleProjectName
project.warfilename={project.name}.war
project.deploywar=${tomcat.home}/webapps/${project.name}.war
project.deploydir=${tomcat.home}/webapps/${project.name}
Subscribe to RSS Feed