Using Spring form to add enum values of JSP page


At times it is required to add Enum values on the jsp page so that its easy to handle on the server side. To display this feature i am using spring 3.0 version.
Lets create a Java Enum Class and override some of its behavior

public enum WorkingDay {</code>

Monday("Monday"),
Tuesday("Tuesday");
Wednesday("Wednesday");
Thursday("Thursday");

private String description;

private WorkingDay(String description) {
this.description = description;
}

public String getValue() {
return name();
}

public void setValue(String value) {}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

}

I just want 4 working days in a week 🙂 .

Now register a binder to the controller.

@InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {</code>

binder.registerCustomEditor(WorkingDay.class, new PropertyEditorSupport() {
@Override
public void setAsText(String value) throws IllegalArgumentException {
if(StringUtils.isBlank(value))
return;

setValue(WorkingDay.valueOf(value));
}

@Override
public String getAsText() {
if(getValue() == null)
return "";

return ((WorkingDay) getValue()).name();
}
});

Set the WorkingDay object to the model object for the view. It should be in the same controller in which the above binder is registered.

@RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("/view_my_jsp");
model.addObject("workingday", WorkingDay.values());
return model;
}

Add the code in “view_my_jsp.jsp”

<form:radiobuttons path="type" items="${workinday}" />

The value of path should match the field name of the property of the command object passed.
The jsp page will contain four radio buttons.

How to configure Hibernate in Spring.


The objective of the tutorial is to understand how the DB can be configured in Spring using Hibernate.
To start with download:
1) spring jars
2) hibernate jars
3) mysql driver

Following is the list of jars I used.

1) create a Db in mysql with name “reco_engine”;
2) Create a table User and add some columns to it.
3) Insert some records into the table using mysql..

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="hibernateDao" class="HibernateAccessDao">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/reco_engine"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>Users.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
</property>
</bean>

<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="mySessionFactory"/>
</property>
</bean>
</beans>

The bean “datasource” is used to configure the properties of the DB.
The bean “mySessionFactory” is used to maintain the session of hibernate. This is taken care by the spring container now.
The property “mappingResources” takes the list of hbm files which will be mapped to this session. Also the datasource property is set in this bean.

The bean hibernateTemplate is the one used to interact with the DB. The Spring application context will manage its lifecycle, initializing and shutting down the factory as part of the application. LocalSessionFactoryBean is the preferred way of obtaining a reference to a specific Hibernate SessionFactory, at least in a non-EJB environment.

The bean “hibernateDao” is the java class and the hibernateTemplate property is set.

The Users table has to be mapped in Hibernate. To map it , Users.java and Users.hbm.xml need to be created . I have used the Hibernate plugin for eclipse provided by JBoss to generate the files automatically. http://jboss.org/tools

The files will be as follows:


public class Users  implements java.io.Serializable {


    // Fields    

     private int id;
     private String firstname;
     private String lastname;
    
    // Constructors

    /** default constructor */
    public Users() {
    }

	/** minimal constructor */
    public Users(int id) {
        this.id = id;
    }
    
  
    // Property accessors

    public int getId() {
        return this.id;
    }
    
    public void setId(int id) {
        this.id = id;
    }

      public String getFirstname() {
        return this.firstname;
    }
    
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return this.lastname;
    }
    
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

The Users.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 3, 2010 9:15:59 PM by Hibernate Tools 3.1.0.beta4 -->
<hibernate-mapping>
    <class name="Users" table="users" catalog="reco_engine">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="firstname" type="string">
            <column name="firstname" length="45" />
        </property>
        <property name="lastname" type="string">
            <column name="lastname" length="45" />
        </property>
        <property name="designation" type="string">
            <column name="designation" length="45" />
        </property>
        <property name="department" type="string">
            <column name="department" length="45" />
        </property>
    </class>
</hibernate-mapping>

The Dao class to interact with the database:


public class HibernateAccessDao {

	HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context =   new ClassPathXmlApplicationContext("spring.xml");
		HibernateAccessDao dao =(HibernateAccessDao) context.getBean("hibernateDao");
		dao.getRecords();
	}
	
// This method retrieves the record with id =1
	private void getRecords(){
		
		Session session = hibernateTemplate.getSessionFactory().openSession();
		Users user = (Users) session.load(Users.class, 1);
		System.out.println(user.getFirstname());
	}

}

The session.load(User.class,1) will load the record of the user with id =1

Connecting database using Spring JdbcTemplate


Another salient feature of Spring is to connect and work with database at great ease which is what I am going to demonstrate.
This article is the basic to load and configure beans to interact with DB and aims to help people who are trying to user the spring ‘JdbcTemplate’ for the first time.

Configurations:
1) Download Spring 3.0.zip from http://www.springframework.org and extract it.
2) Create a normal Java project using ecplise.
3) Database I am using in MySQL so download Mysql driver class

There are several ways in which DB can be access.
JdbcTemplate is the classic Spring JDBC approach and the most popular. This “lowest level” approach and all others use a JdbcTemplate under the covers, and all are updated with Java 5 support such as generics and varargs.
NamedParameterJdbcTemplate wraps a JdbcTemplate to provide named parameters instead of the traditional JDBC “?” placeholders. This approach provides better documentation and ease of use when you have multiple parameters for an SQL statement.
SimpleJdbcTemplate combines the most frequently used operations of JdbcTemplate and NamedParameterJdbcTemplate.
SimpleJdbcInsert and SimpleJdbcCall optimize database metadata to limit the amount of necessary configuration. This approach simplifies coding so that you only need to provide the name of the table or procedure and provide a map of parameters matching the column names. This only works if the database provides adequate metadata. If the database doesn’t provide this metadata, you will have to provide explicit configuration of the parameters.
• RDBMS Objects including MappingSqlQuery, SqlUpdate and StoredProcedure requires you to create reusable and thread-safe objects during initialization of your data access layer. This approach is modeled after JDO Query wherein you define your query string, declare parameters, and compile the query. Once you do that, execute methods can be called multiple times with various parameter values passed in.

Extracted from Spring jdbc docs

The demo is done using JdbcTemplate.

1) Configure the Datasource in the “spring.xml”. One needs to configure the connection properties in the spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="jdbcDao" class="JDBC_Acess">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/reco_engine"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    

</beans>

2) Create a Dao class and configure the bean in the “spring.xml”. Here the class is “JDBCDao.java”. The datasource property created in step 1 is configured for the Dao class.
3) In JDBCDao class the object of JdbcTemplate is created with the constructor argument as Datasource configured in step 1.

public class JDBCDao {

	 private JdbcTemplate jdbcTemplate;

	    private void getUser(){
	    	String sql = "select * from users";
	    	try{
	    	List list = jdbcTemplate.query(sql, new UserMapper());
	    	System.out.println("Total Records "+ list.size());
	    	}catch(DataAccessException e){
	    		e.printStackTrace();
	    	}
	    }
	    private void insertUser(){
	    	String sql = "insert into users values ('21','spring,java,perl,oracle','golf,cooking,music,cricket','3','embedded','7','victor','mathews','team lead','NULL')";
	    	try{
	    	 jdbcTemplate.update(sql);
	    	 System.out.println("record inserted succesffuly");
	    	}catch(DataAccessException e){
	    		e.printStackTrace();
	    	}
	    }
	public static void main(String[] args) {
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
		JDBCDao dao = (JDBCDao)context.getBean("jdbcDao");
		dao.getUser();
		dao.insertUser();
	}
	
	
	public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

}
class UserMapper implements RowMapper{

	@Override
	public User mapRow(ResultSet rs, int arg1) throws SQLException {

		User user = new User();
		user.setFirstName(rs.getString("firstName"));
		user.setLastName(rs.getString("lastName"));
		return user;
	}
	
}

Spring AOP :Pointcut in details


Pointcuts determine join points of interest, and thus enable us to control when advice executes. Spring AOP only supports method execution join points for Spring beans.
A pointcut declaration has two parts: a signature comprising a name and any parameters, and a pointcut expression that determines exactly which method executions we are interested in.

execution – for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
within – limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
this – limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
target – limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
args – limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types

Pointcut expressions can also be combined using ‘&&’, ‘||’ and ‘!’. It is also possible to refer to pointcut expressions by name.

The following example shows three pointcut expressions:
anyPublicOperation (which matches if a method execution join point represents the execution of any public method); inTrading and tradingOperation :

execution(public * *(..))
private void anyPublicOperation() {}

within(com.xyz.someapp.trading..*
private void inTrading() {}

anyPublicOperation() && inTrading()
private void tradingOperation() {}

Following are the examples showing different manner in which a pointcut can be declared:

the execution of any public method:
execution(public * *(..))

the execution of any method with a name beginning with “set”:
execution(* set*(..))

the execution of any method defined by the MyService interface
execution(* com.xyz.service.MyService.*(..))

the execution of any method defined in the service package:
execution(* com.xyz.service.*.*(..))

the execution of any method defined in the service package or a sub-package:
execution(* com.xyz.service..*.*(..))

any join point (method execution only in Spring AOP) within the service package:
within(com.xyz.service.*)

any join point (method execution only in Spring AOP) within the service package or a sub-package:
within(com.xyz.service..*)

any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:
this(com.xyz.service.AccountService)

any join point (method execution only in Spring AOP) where the target object implements the AccountService interface:
target(com.xyz.service.AccountService)

any join point (method execution only in Spring AOP) which takes a single parameter, and where the argument passed at runtime is Serializable:
args(java.io.Serializable)
To know how to use pontCut in sprion AOP follow up previous post Spring AOP

The content is referred from Spring Doc

Spring AOP tutorial -I



Delicious

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.

AOP concepts:

Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in J2EE applications. In my words: a trigger which can affect the multiple classes a one point….
Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. In my words: a locus of points where execution will happen.
Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. (Advice types are discussed below.) In my words : the action to be taken at the point.
Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default. In my words a criteria used to locate point.
Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Consider the example:

Lets declare an interface:

public interface Foo {

Foo getFoo(String fooName,int age);

void getAfter();

void getBefore(String myName);

}

A class implementing the interface:

public class DefaultFooService implements FooService {

public Foo getFoo(String name, int age) {

return new Foo(name, age);

}

public void getAfter() {}

public void getBefore(String myName) {}

}

Till here we have simple java implementation.
Now let see come AOP concepts in picture.
Before – Now I want that before the getBefore() method is called I want to log message saying what is the parameter passed.
After – Also I want that once any method in the interface is called a message should be logged after it.
I have a class which will be called to satisfy the above criteria.

public class SimpleProfiler {

public void afterMethod() throws Throwable {

System.out.println(“After the method call”);

}

public void beforeMethod(String myName){

System.out.println(“My name is “+myName);

}

}

The afterMethod() will log message after any method is called and beforeMethod() will log message before getBefore() is called.
To configure this we will used xmlThis is how I configure my spring.xml.

<beans xmlns=http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

xmlns:aop=http://www.springframework.org/schema/aop&#8221;

xsi:schemaLocation=http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&#8221;>

<!– this is the object that will be proxied by Spring’s AOP infrastructure –>

1 <bean id=“fooService” class=“DefaultFooService”/>

2

3 <!– this is the actual advice itself –>

4 <bean id=“profiler” class=“SimpleProfiler”/>

5

6 <aop:config>

7                <aop:aspect ref=”profiler”>

14 <aop:pointcut id=“aopafterMethod”

expression=“execution(* FooService.*(..))”/>

15 <aop:after pointcut-ref=“aopafterMethod”

method=“afterMethod”/>

16 <aop:pointcut id=“aopBefore”

expression=“execution(* FooService.getBefore(String)) and args(myName)”/>

17 <aop:before pointcut-ref=“aopBefore”

method=“beforeMethod”/>

</aop:aspect>

</aop:config>

</beans>

Let see how we have configure the AOP .

  • Line 1 is used to create a proxy AOP object..
  • Line 7 we define the aspect “SimpleProfiler” class which will come into picture at different point-cuts.
  • Line 6 is used to configure the AOP.
  • Line 14 defines a pointcut in which an expression needs to mention. In this case the expressions say that “call afterMethod of SimpleProfiler class for any method declared inside the FooService interface.
  • Note Line 14 doesn’t define when to call afterMethod().This is done in line 15
  • Line 15 states that call afterMethod() for id aopAfterMethod
  • Similarly for beforeMethod we define in Line 16,17.

    In above example we have

    Aspect – SimpleProfiler.class
    Point-cut – aopafterMethod,aopBefore
    Advice <aop:before> <aop:after>

    Now I am ready to run my main class and class methods of FooService.

    public class Boo {
    public static void main(final String[] args) throws Exception {
    BeanFactory ctx = new ClassPathXmlApplicationContext("spring.xml");
    FooService foo = (FooService) ctx.getBean("fooService");
    foo.getFoo("Pengo", 12);
    foo.getAfter();
    foo.getBefore("Harshit");
    }
    }


    OutPut is
    After the method call ( log messagefor getAfter method )
    My name is Harshit (log message for getBefore)
    After the method call (log message for getAfter method)

    How to build various pointcut expression.