Archive

Archive for the ‘Java and Web’ Category

Struts2 CRUD Tutorial

May 8, 2017 Leave a comment

In this tutorial I will show you how to perform create, retrieve, update and delete operation using struts2 framework. In this tutorial I have used Spring as DI, Hibernate as ORM and Maven as build tool also. Below are tutorial screen shoot,

Add View

 

Update View

 

 

Lets get started,

Structure Directory Project

  • Entity class (Student.java)
package strutshelloworld.net.ren.struts2.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

// TODO: Auto-generated Javadoc
/**
 * The Class Student.
 */
@Entity
@Table(name="student")
public class Student {
    
    /** The id. */
	@Id
	@GeneratedValue
	@Column(name="id")
    private int id;
    
    /** The first name. */
	@Column(name="first_name")
    private String firstName;
    
    /** The last name. */
	@Column(name="last_name")
    private String lastName;
    
    /**
     * Instantiates a new student.
     */
    public Student() {
	
    }
    
    /**
     * Instantiates a new student.
     *
     * @param id the id
     * @param firstName the first name
     * @param lastName the last name
     */
    public Student(int id, String firstName, String lastName) {
	super();
	this.id = id;
	this.firstName = firstName;
	this.lastName = lastName;
    }
    
    /**
     * Gets the id.
     *
     * @return the id
     */
    public int getId() {
	return id;
    }
    
    /**
     * Sets the id.
     *
     * @param id the new id
     */
    public void setId(int id) {
	this.id = id;
    }
    
    /**
     * Gets the first name.
     *
     * @return the first name
     */
    public String getFirstName() {
	return firstName;
    }
    
    /**
     * Sets the first name.
     *
     * @param firstName the new first name
     */
    public void setFirstName(String firstName) {
	this.firstName = firstName;
    }
    
    /**
     * Gets the last name.
     *
     * @return the last name
     */
    public String getLastName() {
	return lastName;
    }
    
    /**
     * Sets the last name.
     *
     * @param lastName the new last name
     */
    public void setLastName(String lastName) {
	this.lastName = lastName;
    }
    
}
  • Repository class (AbstractBaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Class AbstractBaseRepository.
 *
 * @param <T>
 *            the generic type
 */
public abstract class AbstractBaseRepository<T> implements BaseRepository<T> {

	/** The entity class. */
	private Class<T> entityClass;

	/** The session factory. */
	@Autowired
	private SessionFactory sessionFactory;

	/** The hql. */
	private String hql;

	/** The entities. */
	private List<T> entities;
	/**
	 * Instantiates a new abstract base repository.
	 */
	public AbstractBaseRepository() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		entityClass = (Class) pt.getActualTypeArguments()[0];
	}

	/**
	 * Sets the session factory.
	 *
	 * @param sessionFactory
	 *            the new session factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Gets the current session.
	 *
	 * @return the current session
	 */
	protected Session getCurrentSession() {
		try {
			return sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			return sessionFactory.openSession();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#add(java.lang.
	 * Object)
	 */
	public void add(T entity) {
		getCurrentSession().saveOrUpdate(entity); // .save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#deleteById(
	 * int)
	 */
	@SuppressWarnings("unchecked")
	public void deleteById(int id) {
		hql = "delete " + entityClass.getName() + " where id = :id";
		Query q = getCurrentSession().createQuery(hql).setParameter("id", id);
		q.executeUpdate();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#getById(int)
	 */
	@SuppressWarnings("unchecked")
	public T getById(int id) {
		return (T) getCurrentSession().get(entityClass.getName(), id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.repository.BaseRepository#getAll()
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<T> getAll() {
		return getCurrentSession().createCriteria(entityClass).list();
	}
	
	/**
	 * Delete all.
	 */
	public void deleteAll(){
		entities = getAll();
		for(T entity : entities){
			getCurrentSession().delete(entity);
		}
	}
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity){
		getCurrentSession().delete(entity);
	}
}
  • Repository interface (BaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.util.List;


/**
 * The Interface BaseRepository.
 *
 * @param <T> the generic type
 */
public interface BaseRepository<T> {

	/**
	 * Adds the.
	 *
	 * @param entity the entity
	 */
	public  void add(T entity);

	/**
	 * Delete by id.
	 *
	 * @param id the id
	 */
	public void deleteById(int id);

	/**
	 * Gets the by id.
	 *
	 * @param id the id
	 * @return the by id
	 */
	public  T getById(int id);

	/**
	 * Gets the all.
	 *
	 * @return the all
	 */
	public  List<T> getAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity);

}
  • Repository interface(StudentRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import strutshelloworld.net.ren.struts2.domain.Student;

/**
 * The Interface StudentRepository.
 */
public interface StudentRepository extends BaseRepository<Student> {

}
  • Repository class (StudentRepositoryImpl.java)
package strutshelloworld.net.ren.struts2.repository.impl;

import org.springframework.stereotype.Repository;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.AbstractBaseRepository;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;

/**
 * The Class StudentRepositoryImpl.
 */
@Repository("studentRepository")
public class StudentRepositoryImpl extends AbstractBaseRepository<Student> implements StudentRepository {

}
  • Service Interface (StudentService.java)
package strutshelloworld.net.ren.struts2.service;

import java.util.List;

import strutshelloworld.net.ren.struts2.domain.Student;

// TODO: Auto-generated Javadoc
/**
 * The Interface StudentService.
 */
public interface StudentService {

	/**
	 * Adds the student.
	 *
	 * @param student
	 *            the student
	 */
	public void addStudent(Student student);

	/**
	 * Delete student by id.
	 *
	 * @param id
	 *            the id
	 */
	public void deleteStudentById(int id);

	/**
	 * Find student by id.
	 *
	 * @param id
	 *            the id
	 * @return the student
	 */
	public Student findStudentById(int id);

	/**
	 * Find all.
	 *
	 * @return the list
	 */
	public List<Student> findAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(Student entity);
}
  • Service class (StudentServiceImpl.java)
package strutshelloworld.net.ren.struts2.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentServiceImpl.
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

	/** The student repository. */
	@Autowired
	private StudentRepository studentRepository;

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#addStudent(
	 * strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void addStudent(Student student) {
		studentRepository.add(student);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#deleteStudentById
	 * (int)
	 */
	public void deleteStudentById(int id) {
		studentRepository.deleteById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#findStudentById(
	 * int)
	 */
	public Student findStudentById(int id) {
		return studentRepository.getById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#findAll()
	 */
	public List<Student> findAll() {
		return studentRepository.getAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#deleteAll()
	 */
	public void deleteAll() {
		studentRepository.deleteAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#delete(strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void delete(Student entity) {
		studentRepository.delete(entity);
	}
}
  • Action class (StudentAction.java)
package strutshelloworld.net.ren.struts2.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentAction.
 */
public class StudentAction extends ActionSupport implements ModelDriven, Preparable {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 3064301885095539523L;

	/** The student service. */
	@Autowired
	private StudentService studentService;

	/** The list student. */
	private List<Student> listStudent = new ArrayList<Student>();

	/** The student. */
	private Student student = new Student();
	
	/** The request. */
	private HttpServletRequest request;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ModelDriven#getModel()
	 */
	public Object getModel() {
		return student;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	public void prepare() throws Exception {
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		return SUCCESS;
	}

	/**
	 * Adds the student.
	 *
	 * @return the string
	 */
	public String addStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}
	
	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String updateStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}

	/**
	 * Delete student.
	 *
	 * @return the string
	 */
	public String deleteStudent() {
        request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		studentService.deleteStudentById((Integer.parseInt(request. getParameter("id"))));
		return SUCCESS;
	}

	/**
	 * Gets the all student.
	 *
	 * @return the all student
	 */
	public String getAllStudent() {
		listStudent = studentService.findAll();
		return SUCCESS;
	}

	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String getStudentById(){
		request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		student = studentService.findStudentById(Integer.parseInt(request. getParameter("id")));
		return SUCCESS;
	}
	
	/**
	 * Delete all.
	 *
	 * @return the string
	 */
	public String deleteAll(){
		studentService.deleteAll();
		return SUCCESS;
	}
	
	/**
	 * Gets the list student.
	 *
	 * @return the list student
	 */
	public List<Student> getListStudent() {
		return listStudent;
	}

}
  • struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="false" />
	<constant name="struts.custom.i18n.resources" value="app-resources" />
	<constant name="struts.action.extension" value="html" />
    <constant name="struts.mapper.action.prefix.enabled" value="true"/>

	<package name="default" namespace="/" extends="struts-default">

		<action name="index">
			<result type="redirect">/login.html</result>
		</action>

	  <action name="showAddStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="execute">
			<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action>

		<action name="addStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="addStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="updateStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="updateStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="deleteStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action> 
        
        <action name="deleteAll" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteAll">
              <result name="success" type="redirect">listStudent.html</result>
        </action>
	
		<action name="getStudentById" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getStudentById">
				<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action> 
		  
	   <action name="listStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getAllStudent">
			<result name="success">/WEB-INF/jsp/ListStudent.jsp</result>
		</action>
		
		<action name="login" class="strutshelloworld.net.ren.struts2.actions.LoginAction">
			<result name="success">/WEB-INF/jsp/Welcome.jsp</result>
			<result name="error">/WEB-INF/jsp/Login.jsp</result>
			<result name="input">/WEB-INF/jsp/Login.jsp</result>
		</action>
	</package>

</struts>
  • application-context.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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<context:property-placeholder location="classpath:hibernate.properties" />
	
    <context:annotation-config/>
    
    <context:component-scan base-package="strutshelloworld.net.ren.struts2"></context:component-scan>
    
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="strutshelloworld.net.ren.struts2.domain" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
		
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
  • application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>Struts Blank</display-name>
  
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
     
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
      org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
  • AddStudent.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
	<h1>Struts 2 ModelDriven example</h1>
	<s:if test="%{model.id == 0}">
		<h2>Add Student</h2>
	</s:if>
	<s:else>
		<h2>Update Student</h2>
	</s:else>
	<s:form action="addStudent">
		<s:if test="%{model.id != 0}">
            <s:textfield name="id" key="label.id" value="%{model.id}" />
	   </s:if>
		<s:textfield name="firstName" key="label.fname"
			value="%{model.firstName}" />
		<s:textfield name="lastName" key="label.lname"
			value="%{model.lastName}" />
		<s:if test="%{model.id == 0}">
			<s:submit key="label.submit" align="center"/>
		</s:if>
		<s:else>
			<s:submit key="label.update" align="center" action="updateStudent"/>
		</s:else>
	</s:form>
	
</body>
</html>
  • ListStudent.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>List of Student</title>
</head>
<body>
     <table cellpadding="5px">
		<tr class="even">
			<th>Id</th>
			<th>Fist Name</th>
			<th>Last Name</th>
			<th>Edit </th>
			<th>Delete </th>
		</tr>
        <c:forEach items="${listStudent}" var="student">
			<tr>
				<td><c:out value="${student.id}"/></td>
				<td><c:out value="${student.firstName}"/></td>
				<td><c:out value="${student.lastName}"/></td>
		    	<td>
               <s:url var="updateUrl" action="getStudentById">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
				<s:a href="%{updateUrl}">Update</s:a>
                </td>
				<td>
                <s:url var="deleteUrl" action="deleteStudent">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
                <s:a href="%{deleteUrl}">Delete</s:a>
                </td> 
			</tr>
		</c:forEach> 
	</table>
	<s:url var="deleteAllUrl" action="deleteAll"/>
	<s:a href="%{deleteAllUrl}">Delete All</s:a>
</body>
</html>

You can get project in here via Github
Thank you.

PS.
Before running this code, you must edit hibernate.properties file to adjust your local and create database with “hibernate” name in mysql.

Advertisements

java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener

March 16, 2017 Leave a comment

How to solve java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener.

Firstly we must know root cause :
This error because using Spring MVC framework in Java Web application and configured org.springframework.web.context.ContextLoaderListener as a listener in your deployment descriptor also known as web.xml, but the JAR which contains this class is not available in web application’s classpath. This jar appears in spring-web.jar, if you use maven as build tool so make sure that spring-web dependency exist in pom file.


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>

Second, right click web project -> Select “Deployment Assembly” -> Click the “Add..” button on the right -> Select “Java Build Path Entries” from the menu of Directive Type and click “Next” -> Select “Maven Dependencies” from the Java Build Path Entries menu -> Click finish.

Please see picture below.

Build path

Thank you.

Categories: Java, Java and Web Tags: , ,

Struts2 Interceptor Example

February 12, 2017 Leave a comment

In Struts2 interceptor are called one after other one in a configured order for each invocation of an action class. So with interceptor we can do some perform task like logging, validation before action is called.
In this tutorial it shows how to create an own interceptor in Struts2 (Login and Loggin Interceptor). Sumary steps below.

  • Create a class that implements com.opensymphony.xwork2.interceptor.Interceptor interface and override the intercept(ActionInvocation invocation), init, destroy method.

Interceptor class (AuthInterceptor.java)

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
* The Class AuthInterceptor.
*/
public class AuthInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
SessionMap sessionMap = (SessionMap) ActionContext.getContext().getSession();
if(sessionMap.get("user") == null){
return Action.LOGIN;
} else {
return invoke.invoke();
}
}
}

Interceptor class (LogInterceptor.java)

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* The Class LogInterceptor.
*/
public class LogInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
String className = invoke.getAction().getClass().getName();
long startTime = System.currentTimeMillis();
System.out.println("Before calling action: " + className);

String result = invoke.invoke();

long endTime = System.currentTimeMillis();
System.out.println("After calling action: " + className + " Time taken: " + (endTime - startTime) + " ms");
return result;
}
}

If any intercept method in interceptor class decides action should not executed,
it can return a string value and response will be created from global result that same name in struts config file.

  • Configure the interceptor in the struts.xml.
<interceptors>
<interceptor name="authentication" class="strutshelloworld.net.ren.struts2.interceptors.AuthInterceptor">
</interceptor>

<interceptor name="logging" class="strutshelloworld.net.ren.struts2.interceptors.LogInterceptor">
</interceptor>

<interceptor-stack name="authStack">
<interceptor-ref name="authentication" />
<interceptor-ref name="logging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="defaultStack"></default-interceptor-ref>
  • Add global result
<action name="index">
<interceptor-ref name="authStack"></interceptor-ref>
<result type="redirect">/home.html</result>
</action>
  • Add interceptor in action
<action name="home" class="strutshelloworld.net.ren.struts2.actions.UserAction">
<interceptor-ref name="authStack"></interceptor-ref>
<result name="success">/WEB-INF/jsp/Welcome.jsp</result>
</action>

For complete code, you can get it in here.
Fyi, I used project in this post as basis.

Thank you. 🙂

RESTful Web Services Hello World Example

August 17, 2014 Leave a comment

Pada tutorial ini berisi cara membuat services “hello world” dengan menggunakan lib Jersey 2.0.

Tool yang digunakan adalah :

  • Eclipse Juno
  • Tomcat 7.0
  • Lib Jersey 2.0

Langkah 1 : Buat Dynamic Web Project

Langkah 2 : Copy semua .jar dari Jersey 2.o lib ke WebContent→WEB-INF→lib folder

Langkah 3 : Buat package untuk directory services class yang dibuat. Dalam tutorial ini com.services

Langkah 4 : Buat services REST class

Nama file : HelloWorldServices.java

package com.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloWorldServices {

@GET
@Path("/{param}")
public Response getMessage(@PathParam("param") String msg) {

String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();

}
}

Langkah 5 : Tambahkan snippet code berikut ke web.xml file

.....

<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

.....

Langkah 6 : Run project dan hit url http://localhost:8085/RESTJersey/rest/hello/Hello%20World pada browser untuk men-check services REST berfungsi.

 

HelloWorld Services

HelloWorld Services

Referensi : Dari berbagai sumber.

Semoga bermanfaat. 🙂

Spring MVC Single File Upload

May 27, 2014 Leave a comment

Goal dari post ini adalah men-handle file upload pada aplikasi web Spring MVC.

Langkah 1 : Buat model class / form backing object ( UploadedFile.java )

import org.springframework.web.multipart.MultipartFile;

public class UploadedFile {

private MultipartFile file;

public void setFile(MultipartFile file) {
this.file = file;
}

public MultipartFile getFile() {
return file;
}
}

Langkah 2 : Buat controller class ( UploadController.java )

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UploadController {

@Autowired
UploadValidator uploadValidator;

@RequestMapping(value = "/showFormUpload.do", method = RequestMethod.GET)
public ModelAndView showFormUpload() {
ModelAndView mav = new ModelAndView("SingleFileUploadForm");
return mav;
}

@RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST)
public ModelAndView uploadedFile(
@ModelAttribute("fileUploaded") UploadedFile uploadedFile,
BindingResult result) {

InputStream inputStream = null;
OutputStream outputStream = null;

MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();

uploadValidator.validate(uploadedFile, result);
if (result.hasErrors()) {
return new ModelAndView("SingleFileUploadForm");
}
try {
inputStream = file.getInputStream();
File newFile = new File("C:/File Upload/" + fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException ex) {
ex.printStackTrace();
}

return new ModelAndView("FileUploadSuccess", "fileNames", fileName);
}
}

Langkah 3 : Buat validator class ( UploadValidator.java )

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.mvc.model.UploadedFile;

@Component
public class UploadValidator implements Validator {

@Override
public boolean supports(Class clazz) {

return UploadedFile.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object uploadedFile, Errors error) {
UploadedFile file = (UploadedFile) uploadedFile;

if (file.getFile().getSize() == 0) {
error.rejectValue("file", "required");
}
}
}

Buat file message.properties di direktori /WEB-INF/resources  untuk error message di JSP view

required = Select file first.

Buat file Error.css  di folder  di direktori /WEB-INF/css untuk memberi warna text error

.error {
color: #ff0000;
}

Langkah 4: Buat JSP view form  upload

SingleFileUploadForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link href="<c:url value="/css/Error.css" />" rel="stylesheet">
<!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>Single File Upload</title>

</head>
<body>
<form:form method="POST" commandName="fileUploaded" enctype="multipart/form-data" action="uploadFile.do">
Please select a file to upload : <input type="file" name="file" />
<form:errors path="file" cssClass="error"></form:errors>
<br>
<input type="submit" value="upload" />
</form:form>
</body>
</html>

FileUploadSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Insert title here</title>
</head>
<body>
<h2>Spring MVC file upload example</h2>
FileName below - Uploaded Successful.<br>
<c:forEach items="${fileNames}" var="file">
* ${file} <br>
</c:forEach>

</body>
</html>

Langkah 5 : Spring configuration file ( dispatcherServlet-servlet.xml )

<?xml version="1.0" encoding="UTF-8"?>

<beans ... >

<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/" mapping="/**" />
<context:annotation-config />
<context:component-scan base-package="{package to be scanned }"></context:component-scan>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="/WEB-INF/resources/messages" />

</beans>

Screen shoot

File Upload Form

File Upload Form

File Upload Fail

File Upload Fail

File Upload Success

File Upload Success

Referensi : dari berbagai sumber.

Semoga bermanfaat

Spring MVC Form Validation Dengan Annotation

May 5, 2014 Leave a comment

Goal dari post ini membuat simple form validation menggunakan Spring Validator. Untuk melakukan validasi domain model, Spring menyediakan Validator inteface. Untuk menggunakan Validator ini, setidaknya ada tiga langkah yang harus dilakukan.

  • Buat class validator untuk domain model dan impelement Validator interface.
  • Override supports(Class clazz) method.
  • Override alidate(Object target, Errors errors) method.

Mari kita mulai.. 🙂

Langkah 1: Buat model class  yang akan divalidasi ( Product.java )


import java.util.Date;

public class Product {
private int id;
private String name;
private int price;
private Date expired;

public Integer getPrice() {
return price;
}

public void setPrice(Integer price) {
this.price = price;
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void setExpired(Date expired) {
this.expired = expired;
}

public Date getExpired() {
return expired;
}
}

Langkah 2: Buat validator class yang men-implements Validator interface ( ProductValidator.java )

import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;

@Component
public class ProductValidator implements Validator {

@Override
public boolean supports(Class clazz) {
return Product.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object target, Errors errors) {

ValidationUtils.rejectIfEmpty(errors, "id", "product.id.empty");
ValidationUtils.rejectIfEmpty(errors, "name", "product.name.empty");
ValidationUtils.rejectIfEmpty(errors, "price", "product.price.empty");

Product product = (Product) target;
Integer id = product.getId();
if (id <= 0 && id != null) {
errors.rejectValue("id", "product.id.less");
}

String name = product.getName();
if (name.length() < 5) {
errors.rejectValue("name", "product.name.less");
}
Integer price = product.getPrice();
if (price <= 0) {
errors.rejectValue("price", "product.price.less");
}

Date expired = product.getExpired();
if (expired.before(new Date())) {
errors.rejectValue("expired", "product.expired.less");
}
}
}

Rule validasi yang dibuat :

  • Field tidak boleh kosong
  • Field name minimal 5 karakter
  • Field id dan price tidak boleh lebih kecil dari 0
  • Field expired date tidak boleh kurang dari date hari ini

Buat file message.properties dan letakkan dibawah folder /WEB-INF ( di-example ini saya letakkan di  /WEB-INF/resource)

product.id.empty = Id tidak bisa kosong
product.id.less = Id tidak bisa <= 0
product.name.less = Name product tidak bisa kurang dari 5 karakter
product.name.empty = Name product tidak bisa kosong
product.price.less = Price product <= 0
product.price.empty = Price product tidak bisa kosong
product.expired.less = Product expired tidak bisa kurang dari hari ini

Tambahkan kode berikut ini pada dispatcherServlet.xml


<bean id="messageSource"
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
     p:basename="/WEB-INF/resource/messages" />

Langkah 3 : Buat custom date editor (DateEditor.java) untuk format expired date dan product editor (ProductEditor.java) untuk cast id dan price field dari empty / null menjadi 0

DateEditor.java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;

public class DateEditor extends CustomDateEditor {

public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
super(dateFormat, allowEmpty);
}

@Override
public void setAsText(String text) {
System.out.println("setAsText Method Date Editor");
try {
setValue(new SimpleDateFormat("dd/MM/yyyy").parse(text));
} catch (ParseException e) {
setValue(new Date());
}
}

@Override
public String getAsText() {
String s = "";
if (getValue() != null) {
System.out.println("getAsText Method Date Editor");
s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
}
return s;
}
}

ProductEditor.java

import java.beans.PropertyEditorSupport;
import org.springframework.stereotype.Component;

@Component
public class ProductEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) {
System.out.println("setAsText method" + text);
Integer id;
if (text == null || text.equals("")) {
id = 0;
setValue(id);
} else {
id = Integer.parseInt(text);
setValue(id);
}
}

@Override
public String getAsText() {
System.out.println("getAsText method" + getValue().toString());
return this.getValue().toString();
}
}

Buat class binding (GlobalBindingInitializer.java) untuk meregister kedua custom editor tersebut.

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

@ControllerAdvice
public class GlobalBindingInitializer {

@Autowired
ProductEditor customEditor;

@InitBinder
public void binder(WebDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
DateEditor editor = new DateEditor(dateFormat, false);
binder.registerCustomEditor(Date.class, editor);

binder.registerCustomEditor(Integer.class, customEditor);

}
}

Langkah 4: Buat controller class (ProductController.java)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;

@Controller
public class ProductController {

@Autowired
ProductValidator customValidator;

@RequestMapping(value = "/showProductForm.do", method = RequestMethod.GET)
public ModelAndView showFormProduct() {

ModelAndView mav = new ModelAndView("ProductForm", "product",
new Product());
return mav;
}

@RequestMapping(value = "/addProduct.do", method = RequestMethod.POST)
public ModelAndView addProduct(@Valid Product product, BindingResult result) {

customValidator.validate(product, result);

if (result.hasErrors()) {

ModelAndView mav = new ModelAndView("ProductForm", "product",
product);
return mav;
} else {

ModelAndView mav = new ModelAndView("ProductDetail", "product",
product);
return mav;
}
}
}

Langkah 5: Buat JSP view

ProductForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Product Form</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
<form:form action="addProduct.do" method="post" commandName="product">
<table>
<tr>
<td>Id Product</td>
<td><form:input path="id"></form:input></td>
<td><form:errors path="id" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>Product Name</td>
<td><form:input path="name"></form:input></td>
<td><form:errors path="name" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>Product Price</td>
<td><form:input path="price"></form:input></td>
<td><form:errors path="price" cssClass="error"></form:errors></td>
</tr>

<tr>
<td>Expired Date(dd/MM/yyyy)</td>
<td><form:input path="expired"></form:input></td>
<td><form:errors path="expired" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>

</table>
</form:form>
</body>
</html>

ProductDetail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>Detail Product</title>
</head>
<body>
Detail Product <br>
Product Id      : ${product.id} <br>
Product Name    : ${product.name} <br>
Product Price   : ${product.price} <br>
Product Expired : <fmt:formatDate pattern="yyyy-MM-dd" value="${product.expired}" />
<br>
</body>
</html>

Result example :

Spring MVC Form Validation (1/3)

Spring MVC Form Validation (1/3)

Spring MVC Form  Validation (2/3)

Spring MVC Form Validation (2/3)

Form Validation (3/3)

Form Validation (3/3)

Referensi : dari berbagai sumber.

Semoga bermanfaat.

Spring MVC Form Handling

April 18, 2014 Leave a comment

Goal post ini membuat form untuk mengambil data user detail dan mem-print data user detail tersebut di page view.

User Form

User Form

User View

User View

Langkah 1 : Buat user form ( RegistrationForm.jsp ) dan user view ( SuccessRegistration.jsp )

RegistrationForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Registration Form</title>
</head>
<body>
<div align="center">
<form:form action="SuccessRegistration.do" method="post" commandName="userForm" >
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>

<tr>
<td>Position:</td>
<td><form:select path="position" items="${positionList}" /></td>
</tr>
<tr>
<td>Programming Language:</td>
<td><form:checkboxes path="programmingLanguage" items="${programmingLanguageList}"></form:checkboxes></td>
</tr>
<tr>
<td>Avaiable:</td>
<tr>
<td>Yes</td>
<td><form:radiobutton path="avaiable" value="Yes"></form:radiobutton></td>
</tr>
<tr>
<td>No</td>
<td><form:radiobutton path="avaiable" value="No"></form:radiobutton></td>
</tr>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

SuccessRegistration.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Registration Form</title>
</head>
<body>
<div align="center">
<form:form action="SuccessRegistration.do" method="post" commandName="userForm" >
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>

<tr>
<td>Position:</td>
<td><form:select path="position" items="${positionList}" /></td>
</tr>
<tr>
<td>Programming Language:</td>
<td><form:checkboxes path="programmingLanguage" items="${programmingLanguageList}"></form:checkboxes></td>
</tr>
<tr>
<td>Avaiable:</td>
<tr>
<td>Yes</td>
<td><form:radiobutton path="avaiable" value="Yes"></form:radiobutton></td>
</tr>
<tr>
<td>No</td>
<td><form:radiobutton path="avaiable" value="No"></form:radiobutton></td>
</tr>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

Langkah 2 : Buat model class / form backing object ( User.java )

package com.mvc.model;

import java.util.List;

public class User {
private String username;
private String password;
private String email;
private String position;
private List<String> programmingLanguage;
private String avaiable;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public List<String> getProgrammingLanguage() {
return programmingLanguage;
}
public void setProgrammingLanguage(List<String> programmingLanguage) {
this.programmingLanguage = programmingLanguage;
}
public String getAvaiable() {
return avaiable;
}
public void setAvaiable(String avaiable) {
this.avaiable = avaiable;
}

}

Langkah 3 : Buat controller class ( RegistrationController.java )

package com.mvc.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mvc.model.User;

@Controller
public class RegistrationController {

@RequestMapping(value="FormRegistration.do", method=RequestMethod.GET)
public String showFormRegistration(ModelMap model){
User userForm = new User();

model.addAttribute("userForm", userForm);

List<String> positionList = new ArrayList<String>();
positionList.add("Team Leader");
positionList.add("System Analysis");
positionList.add("Programmer");
positionList.add("Designer");
model.addAttribute("positionList", positionList);

List<String> programmingLanguageList = new ArrayList<String>();
programmingLanguageList.add("Java");
programmingLanguageList.add("C#");
programmingLanguageList.add("PHP");
programmingLanguageList.add("C++");
model.addAttribute("programmingLanguageList", programmingLanguageList);

return "RegistrationForm";
}

@RequestMapping(value="SuccessRegistration.do",method=RequestMethod.POST)
public String showSuccessRegistration(@ModelAttribute("userForm")User user, ModelMap model){
model.addAttribute("userForm", user);
return "SuccessRegistration";
}

}

Referensi : dari berbagai sumber.
Semoga bermanfaat