JSP Tutorial a Baby Step to Server Pages

JSP Tutorial a Baby Step to Server Pages

In this tutorial we will teach you how to use Java Server Pages to develop your web applications in simple and easy steps.

JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.

JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to the servlet because it provides more functionality than servlet.

JSP Tutorial

A JSP page contains HTML code and JSP tags. The jsp pages are easier to maintain than servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tag etc.

JSP-Java Server Pages

JSP Contents:
Life Cycle of JSP
Create JSP & set up Environment
JSP Scripting Elements
JSP Directive
JSP Page Directive
JSP Taglib Directives
JSP Include Directives
JSP Forward Example
JSP Redirect Example
JSP Redirect Vs Forward
JSP Include Tag Example
JSP UseBean Tag Example
JSP SetProperty Tag
JSP GetProperty Tag
JSP Implicit Objects
JSP Client Request
JSP Server Response
JSP Out Object
JSP Session Object
JSP application Object
JSP exception Object
JSP confg Object
JSP Scopes Example
JSP – Form Processing
JSP – Session Tracking
JSP – Auto Refresh
JSTL

Struts 2 And JSON Example

In this tutorial we will see that how to display result as JSON format instead of HTML view, JSON(Java Script Object Notation) is light weighted object very use full in mobile technology. It took a decent amount of time to figure out how to set up struts 2 with JSON.

There are a few things that need to be done in order to use JSON with struts 2. Basically, struts provides you with a few result types. For JSON, you will require a new Result Type, because, obviously, since the response is a JSON response, you dont have a page to redirect to.

So, first you need to download the JSON plugin, if you already dont have it in your struts download. As usual, keep it in the lib folder of your application.

The struts 2 JSON plugin allows you to create an action that can be serialized into a JSON object. Ok, what that means in basic terms is that in the response that is sent back to the client, the response is the Javascript object that represents the Action class, and the attributes of the javascipt object are actually named after the public getter methods of the action. If the value of any getter method returns a null, the value of the javascript attribute will be null and vice versa.

The plugin not only handles basic types but also complex types like lists and arrays. We will see a code snippet shortly.
First things first. Lets see what needs to be done for setting up our action for JSON.

Keep the json plugin jar in your lib directory.In struts.xml, create a new package that extends json-default. If you want to use an existing package, you can simply use a comma separated value for the package names as the value of the extends parameter of the package tag. That is what I will be doing here. (TIP : json-default package extends struts-default.)Specify the result type of your action class to be ‘json’

That is pretty much all you need to do to get things going from the struts configuration perspective.
The json-default package contains an interceptor and the result type configuration for JSON requests and responses.
Now lets get to the code.

Create Action Class
JSONAction.java

package com.dineshonjava.struts2.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;

/**
 * @author Dinesh Rajput
 *
 */
public class JSONAction{

 private static final long serialVersionUID = 1L;
 
 private String name = "Dinesh";
 private String[] cityArray = {"Noida","Delhi", "Mumbai"};
 private int age = 27;
 private int[] pincodeArray = {20301,110006,210081};
 private List<String> lists = new ArrayList<String>();
 private Map<String, String> maps = new HashMap<String, String>();
 
 //no getter method, will not include in the JSON
 private String otherName = "Other";
 
 public JSONAction(){
  lists.add("list1");
  lists.add("list2");
  lists.add("list3");
  lists.add("list4");
  lists.add("list5");
 
  maps.put("key1", "value1");
  maps.put("key2", "value2");
  maps.put("key3", "value3");
  maps.put("key4", "value4");
  maps.put("key5", "value5");
 }
 
 public String execute() {
  return Action.SUCCESS;
    }
 
 public String getName() {
  return name;
 }

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

 public String[] getCityArray() {
  return cityArray;
 }

 public void setCityArray(String[] cityArray) {
  this.cityArray = cityArray;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public int[] getPincodeArray() {
  return pincodeArray;
 }

 public void setPincodeArray(int[] pincodeArray) {
  this.pincodeArray = pincodeArray;
 }

 public List<String> getLists() {
  return lists;
 }
 
 public void setLists(List<String> lists) {
  this.lists = lists;
 }
 
 public Map<String, String> getMaps() {
  return maps;
 }
 
 public void setMaps(Map<String, String> maps) {
  this.maps = maps;
 }
 
}

Create Configuration file:
struts.xml
To output the JSON data, you need to declared a package which extends the “json-default“, and result type as “json“.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.devMode" value="true" />
  
  <package name="default" extends="json-default" namespace="/">
        <action name="getjson" class="com.dineshonjava.struts2.action.JSONAction">
            <result type="json"/>
        </action>
    </package>
   
</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2JsonIntegration</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>json.action</welcome-file>
    </welcome-file-list>
</web-app>

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/getjson.

This will give you following screen:

Struts 2 And JSON Example

Download Source Code + Libs
Struts2JSONIntegration.zip

<<Previous <<   || Index ||   >>Next >>

Spring CRUD Example using Many to One Mapping

In this example show how to write a simple web based application with CRUD operation using Spring3 MVC Framwork with Hibernate3 using Annotation handling more than two database tables many to one relationship, which can handle CRUD inside its controllers. To start with it, let us have working STS IDE in place and follow the following steps to develop a Dynamic Form based Web Application using Spring Web Framework:

spring certification

Step 1: Create a Database DOJDB on MySql Database and also we create Survey, Question and Answer tables on this database.
 
Survey Table

CREATE TABLE `survey` (
  `SURVEY_ID` int(11) NOT NULL AUTO_INCREMENT,
  `END_DATE` datetime DEFAULT NULL,
  `START_DATE` datetime DEFAULT NULL,
  `STATUS` varchar(255) DEFAULT NULL,
  `SURVEY_NAME` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`SURVEY_ID`)
)

  Question Table

CREATE TABLE `questions` (
  `QUESTION_ID` int(11) NOT NULL AUTO_INCREMENT,
  `QUESTION` varchar(255) DEFAULT NULL,
  `SURVEY_ID` int(11) DEFAULT NULL,
  PRIMARY KEY (`QUESTION_ID`),
  KEY `FK95C5414DD76DB9F3` (`SURVEY_ID`),
  CONSTRAINT `FK95C5414DD76DB9F3` FOREIGN KEY (`SURVEY_ID`) REFERENCES `survey` (`SURVEY_ID`)
)

Answer Table

CREATE TABLE `answer` (
  `Answer_ID` int(11) NOT NULL AUTO_INCREMENT,
  `Answer` varchar(255) DEFAULT NULL,
  `Question_ID` int(11) DEFAULT NULL,
  PRIMARY KEY (`Answer_ID`),
  KEY `FKABCA3FBEE2FF2433` (`Question_ID`),
  CONSTRAINT `FKABCA3FBEE2FF2433` FOREIGN KEY (`Question_ID`) REFERENCES `questions` (`QUESTION_ID`)
)

Step 2: Create a config.properties for database configuration information in the resources folder under src folder in the created project.

# database properties
#app.jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#app.jdbc.url=jdbc:oracle:thin:@192.168.2.104:1521:orcl
#app.jdbc.username=hyundaisrv
#app.jdbc.password=hyundaisrv

#hibernate properties
#hibernate.config=/WEB-INF/hibernate.cfg.xml


################### JDBC Configuration ##########################
#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/DOJDB
jdbc.username=root
jdbc.password=root

#jdbc.driverClassName=org.hsqldb.jdbcDriver
#jdbc.url=jdbc:hsqldb:file:db/SivaLabsDB;shutdown=true
#jdbc.username=sa
#jdbc.password=

################### Hibernate Configuration #########################
#hibernate.dialect=org.hibernate.dialect.OracleDialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true

Step 3: Create a Dynamic Web Project with a name “Survey Status” and create packages com.dineshonjava.survey.bean, com.dineshonjava.survey.Controller, com.dineshonjava.survey.dao, com.dineshonjava.survey.service, com.dineshonjava.survey.utils under the src folder in the created project.

Step 4: Add below mentioned Spring 3.0 and Hibernate 3.0 related libraries and other libraries into the folder WebRoot/WEB-INF/lib.
Spring CRUD Example using Many to One Mapping
Step 5: Create a Java class SurveyController, Survey, Question, Answer, SurveyDao, SurveyDaoImpl, QuestionDao, QuestionDaoImpl, AnswerDao, AnswerDaoImpl under the respective packages..

Step 6: Create Spring configuration files web.xml and doj-servlet.xml under the WebRoot/WEB-INF/ and WebRoot/WEB-INF/config folders.

Step 7: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file editSurvey.jsp
home.jsp,newSurvey.jsp,showSurvey.jsp,SurveyHomeScreen.jsp,taglib_includes.jsp,viewSurvey.jsp under this sub-folder.

Step 8: The final step is to create the content of all the source and configuration files name doj-servlet.xml under the sub-folder /WebRoot/WEB-INF/config and export the application as explained below.

Many to One Mapping Spring

Survey.java

package com.dineshonjava.survey.bean;

/**
 * @author Dinesh Rajput
 *
 */
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.SequenceGenerator;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@Table(name="Survey")
public class Survey
{
 
 @Id
 @SequenceGenerator(name = "seq_contacts", sequenceName = "seq_contacts")
 @GeneratedValue(strategy = GenerationType.AUTO, generator = "seq_contacts")
 
 private int SURVEY_ID; 
 @Column 
 private String SURVEY_NAME;
 @Column 
 private Date START_DATE; 
 @Column 
 private Date END_DATE;
 @Column 
 private String STATUS;
 
 @Transient
 private List<String> QUESTION;
 @Transient
 private List<String> Answer;
 
 public Survey()
 {}
 public Survey(int SURVEY_ID, String SURVEY_NAME, Date START_DATE, Date END_DATE, String STATUS)
 {
  super();
  this.SURVEY_ID = SURVEY_ID;
  this.SURVEY_NAME = SURVEY_NAME;
  this.START_DATE = START_DATE;
  this.END_DATE = END_DATE;
  this.STATUS = STATUS;
  
 }
 @Override
 public String toString()
 {
  return ToStringBuilder.reflectionToString(this);
 }

 public int getSURVEY_ID() {
  return SURVEY_ID;
 }

 public void setSURVEY_ID(int sURVEY_ID) {
  SURVEY_ID = sURVEY_ID;
 }

 public String getSURVEY_NAME() {
  return SURVEY_NAME;
 }

 public void setSURVEY_NAME(String sURVEY_NAME) {
  SURVEY_NAME = sURVEY_NAME;
 }

 public Date getSTART_DATE() {
  return START_DATE;
 }

 public void setSTART_DATE(Date sTART_DATE) {
  START_DATE = sTART_DATE;
 }

 public Date getEND_DATE() {
  return END_DATE;
 }

 public void setEND_DATE(Date eND_DATE) {
  END_DATE = eND_DATE;
 }

 public String getSTATUS() {
  return STATUS;
 }

 public void setSTATUS(String sTATUS) {
  STATUS = sTATUS;
 }
 public List<String> getQUESTION() {
  return QUESTION;
 }
 public void setQUESTION(List<String> qUESTION) {
  QUESTION = qUESTION;
 }
 public List<String> getAnswer() {
  return Answer;
 }
 public void setAnswer(List<String> answer) {
  Answer = answer;
 }
 
}

Question.java

package com.dineshonjava.survey.bean;

/**
 * @author Dinesh Rajput
 *
 */
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;


@Entity
@Table(name="questions")

public class Question {

 @Id
 @SequenceGenerator(name = "seq_contacts", sequenceName = "seq_contacts")
 @GeneratedValue(strategy = GenerationType.AUTO, generator = "seq_contacts")
 
 private int QUESTION_ID; 
 @Column private String QUESTION;
 
 @Transient
 private List<String> answers;
 
 @ManyToOne
 @JoinColumn(name ="SURVEY_ID")
 private Survey survey;
 
 public Question()
 {
 }
 
 public Question(int QUESTION_ID, String QUESTION, Survey survey )
 {
  super();
  this.QUESTION_ID = QUESTION_ID;
  this.QUESTION = QUESTION;
  this.survey = survey;
 }
  
  @Override
  public String toString()
  {
   return ToStringBuilder.reflectionToString(this);
  }

  public int getQUESTION_ID() {
   return QUESTION_ID;
  }

  public void setQUESTION_ID(int QUESTION_ID) {
   this.QUESTION_ID = QUESTION_ID;
  }

  public String getQUESTION() {
   return QUESTION;
  }

  public void setQUESTION(String QUESTION) {
   this.QUESTION = QUESTION;
  }
  
  public Survey getSurvey() {
   return survey;
  }

  public void setSurvey(Survey survey) {
   this.survey = survey;
  }

  public List<String> getAnswers() {
   return answers;
  }

  public void setAnswers(List<String> answers) {
   this.answers = answers;
  }
  
}

The above class show the Many to One relationship between Survey table and Question table.
Answer.java

package com.dineshonjava.survey.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * @author Dinesh Rajput
 *Question_ID | Answer_ID | Answer
 */

@Entity
@Table(name="answer")
public class Answer {

 @Id
 @SequenceGenerator(name = "seq_contacts", sequenceName = "seq_contacts")
 @GeneratedValue(strategy = GenerationType.AUTO, generator = "seq_contacts")
 private int Answer_ID;
 
 @Column 
 private String Answer;
 
 @ManyToOne
 @JoinColumn(name ="Question_ID")
 private Question question;
 
 public Answer(){
  
 }
 
 public Answer(int Answer_ID, String Answer, Question question )
 {
  super();
  this.Answer_ID = Answer_ID;
  this.Answer = Answer;
  this.question = question;
 }
 
 public int getAnswer_ID() {
  return Answer_ID;
 }
 public void setAnswer_ID(int answer_ID) {
  Answer_ID = answer_ID;
 }
 public String getAnswer() {
  return Answer;
 }
 public void setAnswer(String answer) {
  Answer = answer;
 }

 public Question getQuestion() {
  return question;
 }

 public void setQuestion(Question question) {
  this.question = question;
 }
 
}

The above class show the Many to One relationship between Question table and Answer table.
SurveyDao.java

package com.dineshonjava.survey.dao;

import java.util.List;

import com.dineshonjava.survey.bean.Survey;

public interface SurveyDAO {
 
 Survey getBySURVEY_ID(int SURVEY_ID);
 
 List<Survey> getAllSurvey();
 
 int save(Survey survey);
 
 void update(Survey survey);
 
 void view(Survey survey);
 
 void delete(int SURVEY_ID);
}

SurveyDaoImpl.java

package com.dineshonjava.survey.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dineshonjava.survey.bean.Survey;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
@Transactional
public class SurveyDAOImpl implements SurveyDAO {
 @Autowired
 private SessionFactory sessionFactory;
 
 public Survey getBySURVEY_ID(int SURVEY_ID)
 {
  return (Survey) sessionFactory.getCurrentSession().get(Survey.class, SURVEY_ID);
 }
 
 @SuppressWarnings("unchecked")
 public List<Survey> getAllSurvey()
 {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Survey.class);
  return criteria.list();
 }
  
 public int save(Survey survey)
 {
  return (Integer) sessionFactory.getCurrentSession().save(survey);
 }
 
 public void update(Survey survey)
 {
  sessionFactory.getCurrentSession().merge(survey);
 }
 
  
 public void view(Survey survey)
 {
  sessionFactory.getCurrentSession().merge(survey);
 }
 
 public void delete(int SURVEY_ID)
 {
  Survey s = getBySURVEY_ID(SURVEY_ID);
  sessionFactory.getCurrentSession().delete(s);
 }
}

QuestionDao.java

package com.dineshonjava.survey.dao;

import java.util.List;

import com.dineshonjava.survey.bean.Question;

/**
 * @author Dinesh Rajput
 *
 */
public interface QuestionDAO {
 Question getByQuestion_ID(int Question_ID);
 
 List<Question> getAllQuestion();
 
 int save(Question question);
 
 void update(Question question);
 
 void view(Question question);
 
 void delete(int Question_ID);
}

QuestionDaoImpl.java

package com.dineshonjava.survey.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dineshonjava.survey.bean.Question;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
@Transactional
public class QuestionDAOImpl implements QuestionDAO {

 @Autowired
 private SessionFactory sessionFactory;
 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#getByQuestion_ID(int)
  */
 @Override
 public Question getByQuestion_ID(int Question_ID) {
  return (Question) sessionFactory.getCurrentSession().get(Question.class, Question_ID);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#getAllQuestion()
  */
 @Override
 public List<Question> getAllQuestion() {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Question.class);
  return criteria.list();
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#save(com.dineshonjava.survey.bean.Question)
  */
 @Override
 public int save(Question question) {
  return (Integer) sessionFactory.getCurrentSession().save(question);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#update(com.dineshonjava.survey.bean.Question)
  */
 @Override
 public void update(Question question) {
  sessionFactory.getCurrentSession().merge(question);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#view(com.dineshonjava.survey.bean.Question)
  */
 @Override
 public void view(Question question) {
  sessionFactory.getCurrentSession().merge(question);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.QuestionDAO#delete(int)
  */
 @Override
 public void delete(int Question_ID) {
  Question s = getByQuestion_ID(Question_ID);
  sessionFactory.getCurrentSession().delete(s);
 }

}

AnswerDao.java

package com.dineshonjava.survey.dao;

import java.util.List;

import com.dineshonjava.survey.bean.Answer;

/**
 * @author Dinesh Rajput
 *
 */
public interface AnswerDAO {
 Answer getByAnswer_ID(int Answer_ID);
 
 List<Answer> getAllAnswer();
 
 int save(Answer answer);
 
 void update(Answer answer);
 
 void view(Answer answer);
 
 void delete(int Answer_ID);
}

AnswerDaoImpl.java

package com.dineshonjava.survey.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dineshonjava.survey.bean.Answer;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
@Transactional
public class AnswerDAOImpl implements AnswerDAO {

 @Autowired
 private SessionFactory sessionFactory;
 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#getByAnswer_ID(int)
  */
 @Override
 public Answer getByAnswer_ID(int Answer_ID) {
  return (Answer) sessionFactory.getCurrentSession().get(Answer.class, Answer_ID);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#getAllAnswer()
  */
 @Override
 public List<Answer> getAllAnswer() {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Answer.class);
  return criteria.list();
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#save(com.dineshonjava.survey.bean.Answer)
  */
 @Override
 public int save(Answer answer) {
  return (Integer) sessionFactory.getCurrentSession().save(answer);
 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#update(com.dineshonjava.survey.bean.Answer)
  */
 @Override
 public void update(Answer answer) {
  sessionFactory.getCurrentSession().merge(answer);

 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#view(com.dineshonjava.survey.bean.Answer)
  */
 @Override
 public void view(Answer answer) {
  sessionFactory.getCurrentSession().merge(answer);

 }

 /* (non-Javadoc)
  * @see com.dineshonjava.survey.dao.AnswerDAO#delete(int)
  */
 @Override
 public void delete(int Answer_ID) {
  Answer s = getByAnswer_ID(Answer_ID);
  sessionFactory.getCurrentSession().delete(s);
 }

}

SurveyController.java

package com.dineshonjava.survey.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.dineshonjava.survey.bean.Answer;
import com.dineshonjava.survey.bean.Question;
import com.dineshonjava.survey.bean.Survey;
import com.dineshonjava.survey.dao.AnswerDAO;
import com.dineshonjava.survey.dao.QuestionDAO;
import com.dineshonjava.survey.dao.SurveyDAO;
import com.dineshonjava.survey.utils.SurveyFormValidator;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class SurveyController {
 @Autowired
 private SurveyDAO surveyDAO;
 
 @Autowired
 private AnswerDAO answerDAO;
 
 @Autowired
 private QuestionDAO questionDAO;
 
 @Autowired
 private SurveyFormValidator validator;
 
 @RequestMapping("/home")
 public String home()
 {
  return "home";
 }
 
 @InitBinder
 public void initBinder(WebDataBinder binder) 
 {
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
 }
 
 @RequestMapping("/viewAllSurvey")
 public ModelAndView getAllSurvey()
 {
  ModelAndView mav = new ModelAndView("showSurvey");
  List<Survey> survey = surveyDAO.getAllSurvey();
  mav.addObject("SEARCH_SURVEY_RESULTS_KEY", survey);
  return mav;
 }
 
 @RequestMapping(value="/saveSurvey", method=RequestMethod.GET)
 public ModelAndView newuserForm()
 {
  ModelAndView mav = new ModelAndView("newSurvey");
  Survey survey = new Survey();
  mav.getModelMap().put("newSurvey", survey);
  
  return mav;
 }
 
 @RequestMapping(value="/saveSurvey", method=RequestMethod.POST)
 public String create(@ModelAttribute("newSurvey")Survey survey, BindingResult result, SessionStatus status)
 {
  validator.validate(survey, result);
  if (result.hasErrors()) 
  {    
   return "newSurvey";
  }
  
  int surveyId = surveyDAO.save(survey);
  List<String> questions = survey.getQUESTION();
  Question ques = null;
  if(questions != null){
   for(String question : questions){
    ques = new Question();
    ques.setQUESTION(question);
    ques.setSurvey(survey);
    int quesId = questionDAO.save(ques);
    List<String> answers = survey.getAnswer();
    Answer answer = null;
    if(answers != null){
     for(String ans : answers){
      answer = new Answer();
      answer.setAnswer(ans);
      answer.setQuestion(ques);
      answerDAO.save(answer);
     }
    }
    
   }
  }
  status.setComplete();
  return "redirect:viewAllSurvey.do";
 }
 
 @RequestMapping(value="/updateSurvey", method=RequestMethod.GET)
 public ModelAndView edit(@RequestParam("SURVEY_ID")Integer SURVEY_ID)
 {
  ModelAndView mav = new ModelAndView("editSurvey");
  Survey survey = surveyDAO.getBySURVEY_ID(SURVEY_ID);
  mav.addObject("editSurvey", survey);
  return mav;
 }
 
 @RequestMapping(value="/updateSurvey", method=RequestMethod.POST)
 public String update(@ModelAttribute("editSurvey") Survey survey, BindingResult result, SessionStatus status)
 {
  validator.validate(survey, result);
  if (result.hasErrors()) {
   return "editSurvey";
  }
  surveyDAO.update(survey);
  status.setComplete();
  return "redirect:viewAllSurvey.do";
 }
 
 @RequestMapping(value="/viewSurvey", method=RequestMethod.GET)
 public ModelAndView view(@RequestParam("SURVEY_ID")Integer SURVEY_ID)
 {
  ModelAndView mav = new ModelAndView("viewSurvey");
  Survey survey = surveyDAO.getBySURVEY_ID(SURVEY_ID);
  mav.addObject("viewSurvey", survey);
  return mav;
 }
}


Using Spring Validator for Survey Question Answer form.
SurveyFormValidator.java

package com.dineshonjava.survey.utils;

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

import com.dineshonjava.survey.bean.Survey;

/**
 * @author Dinesh Rajput
 *
 */
@Component("surveyFormValidator")
public class SurveyFormValidator implements Validator
{
 private static final String START_DATE = null;

 @SuppressWarnings("unchecked")
 @Override
 public boolean supports(Class clazz)
 {
  return Survey.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object model, Errors errors)
 {
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "SURVEY_NAME","required.SURVEY_NAME", "survey name is required.");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "START_DATE","required.START_DATE", "Start Date is required.");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "END_DATE","required.END_DATE", "End Date is required.");
  //ValidationUtils.rejectIfEmptyOrWhitespace(errors, "QUESTION","required.QUESTION", "can not be blank.");
  
  /*ValidationUtils.rejectIfEmpty(errors, "START_DATE","required.SURVEY_NAME", "Enter date");*/
 }

}


Spring Web configuration file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Survey Status</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  <servlet-name>doj</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>doj</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
</web-app>

Spring Web configuration file doj-servlet.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:p="http://www.springframework.org/schema/p" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 
    <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/views/" />
  <property name="suffix" value=".jsp" />
 </bean>
</beans>

Spring Web configuration file applicatonContext.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:p="http://www.springframework.org/schema/p" 
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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
      http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
 <context:annotation-config />
 
 <context:component-scan base-package="com.dineshonjava.survey" />
 
 <mvc:annotation-driven /> 
 
 <context:property-placeholder location="classpath:config.properties" />
 
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="Messages"/>
     
 <tx:annotation-driven transaction-manager="transactionManager" />
    
    <bean  id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"  p:sessionFactory-ref="sessionFactory" />
 
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
     <property name="dataSource" ref="dataSource"/>
     <property name="hibernateProperties">
       <props>        
             <prop key="hibernate.dialect">${hibernate.dialect}</prop>          
             <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
             <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> 
        </props>
     </property>
  <property name="annotatedClasses">
   <list>
    <value>com.dineshonjava.survey.bean.Survey</value>
    <value>com.dineshonjava.survey.bean.Question</value>
    <value>com.dineshonjava.survey.bean.Answer</value>
   </list>
  </property>
 </bean>
  
 
  
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
   p:driverClassName="${jdbc.driverClassName}"
   p:url="${jdbc.url}"
   p:username="${jdbc.username}"
   p:password="${jdbc.password}"/>
  
</beans>

viewSurvey.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>
 <script type="text/javascript" src="js/survey.js"></script>
 
 <title><spring:message code="App.Title"></spring:message> </title>
</head>
<body style="font-family: Arial; font-size:smaller;">

<table  bgcolor="lightblue" width="750" height="500" align="center" style="border-collapse: collapse;" border="1" bordercolor="#006699" >
 <tr>
  <td align="center"><h3>survey detail</h3></td>
 </tr>
  <tr valign="top" align="center">
    <td align="center">
   <form:form action="viewSurvey.do" method="post" commandName="viewSurvey">
    <table width="500" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="2" cellpadding="2">     
     <tr>
      <td width="100" align="right">SURVEY_ID</td>
      <td width="150">
      <form:input path="SURVEY_ID" readonly="true"/></td>
      <td align="left">
      <form:errors path="SURVEY_ID" cssStyle="color:red"></form:errors>  </td>
     </tr>
     <tr>
      <td width="100" align="right">SURVEY_NAME</td>
      <td>
      <form:input path="SURVEY_NAME" readonly="true"/></td>
      <td align="left">
      <form:errors path="SURVEY_NAME" cssStyle="color:red"></form:errors> 
      </td>
     </tr>
     
     <tr>
      <td width="100" align="right">START_DATE</td>
      <td><form:input path="START_DATE" readonly="true"/></td>
      <td align="left"><form:errors path="START_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr>
     
     <tr>
      <td width="100" align="right">END_DATE</td>
      <td><form:input path="END_DATE" readonly="true"/></td>
      <td align="left"><form:errors path="END_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr>
      <%-- <tr>
      <td width="100" align="right">STATUS</td>
      <td>      
       <form:select path="STATUS" readonly="true">
       
                 <form:option value="C" label="Completed"/>
                 <form:option value="NC" label="Incomplete"/>
             </form:select>      
      </td>
      <td>
      </td>      
     </tr>  --%>    
     <tr valign="bottom">
      <td colspan="1" align="center">     
      <input type="button"  value="Back" onclick="javascript:go('viewAllSurvey.do');">
      </td>
     </tr>    
    </table>    
  </form:form>
    </td>    
  </tr>
</table>
</body>
</html>

showSurvey.jsp

<%@include file="taglib_includes.jsp"%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><spring:message code="App.Title"></spring:message></title>
<script type="text/javascript" src="js/survey.js"></script>



</head>
<body style="font-family: Arial; font-size: smaller;">
 
  <h3><center>Survey page Details</center></h3>
 
 
 <center>
  
  <table style="border-collapse: collapse;" border="1"
   bordercolor="#006699" width="500">
   <tr bgcolor="lightblue">
    <th>Survey Id</th>
    <th>Survey Name</th>
    <th>Survey Start Date</th>
    <th>Survey End date</th>
    <th>Status</th>
    <th>Action</th>
    
    <th></th>
   </tr>
   <c:if test="${empty SEARCH_SURVEY_RESULTS_KEY}">
    <tr>
     <td colspan="4">No Results found</td>
    </tr>
   </c:if>
   <c:if test="${! empty SEARCH_SURVEY_RESULTS_KEY}">
    <c:forEach var="survey" items="${SEARCH_SURVEY_RESULTS_KEY}">
     <tr>
      <td><c:out value="${survey.SURVEY_ID}"></c:out></td>
      <td><c:out value="${survey.SURVEY_NAME}"></c:out></td>
      <td><fmt:formatDate value="${survey.START_DATE}" pattern="dd-MM-yyyy" /></td>
      <td><fmt:formatDate value="${survey.END_DATE}" pattern="dd-MM-yyyy" /></td>
      
      <%-- <td><c:out value="${survey.START_DATE}"></c:out></td>
      <td><c:out value="${survey.END_DATE}"></c:out></td> --%>
      
      <td><c:out value="${survey.STATUS}"></c:out></td>
      
      <td>&nbsp;<a href="updateSurvey.do?SURVEY_ID=${survey.SURVEY_ID}">Edit</a>
       &nbsp;&nbsp;
          <a href="viewSurvey.do?SURVEY_ID=${survey.SURVEY_ID}">View</a>
       </td>
       
       <td>
      <a href="saveQuestion.do?SURVEY_ID=${survey.SURVEY_ID}">Question</a>
      </td> 
     </tr>
    </c:forEach>
   </c:if>
  </table>
 </center>
 <br><br><br>
<input type="button" value="add new survey" onclick="javascript:go('saveSurvey.do');" />
</body>
</html>

newSurvey.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>
 <script type="text/javascript" src="js/survey.js"></script>
 <script type="text/javascript" src="js/jquery-1.9.1.js"></script> 
 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript" src="js/datetimepicker.js"></script>

 <title><spring:message code="App.Title"></spring:message> </title>
 </head>

<body style="font-family: Arial; font-size:smaller;">

<table  bgcolor="#F1D4B8" width="1000" height="600" align="center" style="border-collapse: collapse;" border="1" bordercolor="#006699" >
 <tr>
  <td align="center"><h3>Adding new Survey</h3></td>
 </tr>
 <tr valign="top" align="center">
    <td align="center">
   <form:form action="saveSurvey.do" method="post" commandName="newSurvey">
      
    <table width="700" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="2" cellpadding="2"> 
     <tr>
      <td width="50" align="right">SURVEY_NAME</td>
      <td width="50">
      <form:input path="SURVEY_NAME"/></td>
      <td align="left">
      <form:errors path="SURVEY_NAME" cssStyle="color:red"></form:errors> 
      </td> 
     </tr>
       
      <tr>
      <td width="75" align="right">START_DATE</td>
      <td><form:input path="START_DATE" id="demo1" type="text" size="25"/><a href="javascript:NewCal('demo1','ddmmyyyy')"><img src="image/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
           
      <td align="left"><form:errors path="START_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr> 
     <tr>
      <td width="50" align="right">END_DATE</td>
        <td><form:input path="END_DATE" id="demo2" type="text" size="25"/><a href="javascript:NewCal('demo2','ddmmyyyy')"><img src="image/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
         
      <td align="left"><form:errors path="END_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr> 
     
     <tr>
      <td width="50" align="right">STATUS</td>
      <td>      
       <form:select path="STATUS">
       
                 <form:option value="Completed" label="Completed"/>
                 <form:option value="Incomplete" label="Incomplete"/>
             </form:select>      
      </td>     
     </tr>

<table width="700" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="2" cellpadding="2">      
<tr>   
<td>    
 <div id='TextBoxesGroup'>
 <div id="TextBoxDiv1">
  Question #1 :
<form:textarea cols="29" rows="3" path="QUESTION" />
<br><br>
Answer #1 : &nbsp; 
<form:input path="Answer" id='textbox1' size="50"/>
<br><br>
Answer #2 : &nbsp; 
<form:input path="Answer" id='textbox2' size="50"/>
<br><br>
Answer #3 : &nbsp; 
<form:input path="Answer" id='textbox3' size="50"/>
<br><br>
Answer #4 : &nbsp; 
<form:input path="Answer" id='textbox4' size="50"/>

</div></div>

</tr>
<tr><td colspan="5" align=""><br>
<input type='button' value='Add Question' id='addButton'>&nbsp;&nbsp;
<input type='button' value='Remove Question' id='removeButton'></td></tr>
   
     <tr>
      <td colspan="3" align="center">
      <input type="submit" name="" value="Save">
      &nbsp;&nbsp;
      <input type="reset" name="" value="Reset">
      &nbsp;&nbsp;
      <input type="button"  value="Back" onclick="javascript:go('viewAllSurvey.do');">
      </td>
     </tr>     
     </table>   
  </form:form>
    </td>    
  </tr>
</table>
</body>
</html>

editSurvey.jsp

<%@include file="taglib_includes.jsp" %>

<html>
<head>
 <script type="text/javascript" src="js/survey.js"></script>
 <script type="text/javascript" src="js/datetimepicker.js"></script>
 
 
 <title><spring:message code="App.Title"></spring:message> </title>
</head>
<body style="font-family: Arial; font-size:smaller;">

<table  bgcolor="lightblue" width="750" height="500" align="center" style="border-collapse: collapse;" border="1" bordercolor="#006699" >
 <tr>
  <td align="center"><h3>Edit survey detail</h3></td>
 </tr>
  <tr valign="top" align="center">
    <td align="center">
   <form:form action="updateSurvey.do" method="post" commandName="editSurvey">
    <table width="500" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="2" cellpadding="2">     
     <tr>
      <td width="100" align="right">SURVEY_ID</td>
      <td width="150">
      <form:input path="SURVEY_ID" readonly="true"/></td>
      <td align="left">
      <form:errors path="SURVEY_ID" cssStyle="color:red"></form:errors>  </td>
     </tr>
     <tr>
      <td width="100" align="right">SURVEY_NAME</td>
      <td>
      <form:input path="SURVEY_NAME"/></td>
      <td align="left">
      <form:errors path="SURVEY_NAME" cssStyle="color:red"></form:errors> 
      </td>
     </tr>
     
     <tr>
      <td width="100" align="right">START_DATE</td>
      <td><form:input path="START_DATE" id="demo1" type="text" size="25"/><a href="javascript:NewCal('demo1','ddmmyyyy')"><img src="image/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
      
      <%-- <td><form:input path="START_DATE"/></td>
       --%>
      <td align="left"><form:errors path="START_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr>
     
     <tr>
      <td width="100" align="right">END_DATE</td>
      <td><form:input path="END_DATE" id="demo2" type="text" size="25"/><a href="javascript:NewCal('demo2','ddmmyyyy')"><img src="image/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
       
      
      <%-- <td><form:input path="END_DATE"/></td> --%>
      <td align="left"><form:errors path="END_DATE" cssStyle="color:red"></form:errors>  </td>
     </tr>
     <tr>
      <td width="100" align="right">STATUS</td>
      <td>      
       <form:select path="STATUS">
       
                 <form:option value="Completed" label="Completed"/>
                 <form:option value="Incomplete" label="Incomplete"/>
             </form:select>      
      </td>     
     </tr>
     
     <%-- <tr>
      <td width="100" align="right">SURVEY_DESCRIPTION</td>
      <td>
      <form:input path="SURVEY_DESCRIPTION"/></td>
      <td align="left">
      <form:errors path="SURVEY_DESCRIPTION" cssStyle="color:red"></form:errors> 
      </td>
     </tr> --%>
     
    
     
     <tr valign="bottom">
      <td colspan="2" align="center">
      <%-- <input type="button"  value="Delete" onclick="javascript:deleteContact('deleteContact.do?SURVEY_ID=${editContact.SURVEY_ID}');">
      &nbsp;&nbsp; --%>
      <input type="submit" name="" value="Save">      
      &nbsp;&nbsp;
      <input type="button"  value="Back" onclick="javascript:go('viewAllSurvey.do');">
      </td>
     </tr>
     
    </table>    
  </form:form>
    </td>    
  </tr>
</table>
</body>
</html>

home.jsp

<%@include file="taglib_includes.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">
<html>
<head>
<script type="text/javascript" src="js/survey.js"></script>
<title><spring:message code="App.Title"></spring:message> </title>
</head>

<body>
<center>Survey page Details</center>
<br>
<br>
<br>
<br>
 <a href="viewAllSurvey.do">Show Survey List</a>   
</body>
</html>

index.jsp

<%-- <%
response.sendRedirect("viewAllSurvey.do");
%>

 --%>
 
 <%@include file="/views/taglib_includes.jsp" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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">
<html>
<head>
<script type="text/javascript" src="js/survey.js"></script>
<title>Survey-Status </title>
</head>

<body>
<h2><center>Survey page Details</center></h2>
<br>
<br>
<br>
<br>
 <a href="viewAllSurvey.do">Show Survey List</a>   
</body>
</html>

Once you are done with creating source and configuration files, export your application. Right click on your application and use Export-> WAR File option and save your survey status.war file in Tomcat’s webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try a URL http://localhost:8181/doj/ and you should see the following result if everything is fine with your Spring Web Application:

output


show
survey: click on show survey list..
http://localhost:8080/doj/viewAllSurvey.do

output

Click on “Add new Survey” button then you will get the following screen.
http://localhost:8080/doj/saveSurvey.do

output

Download Source code
survey status.zip

  <<Spring Web MVC Framework |index| Spring Many to One>>

Struts 2 Hibernate 3 Integration Example with Spring 3

In this example we will describe the integration of Struts2 with Hibernate3 as well as using Spring 3 and Tiles2 in this example. We recommend firstly you have a look to previous examples Struts2 with Spring3 Integration Example and  Struts2 with Tiles2 Integration Example.

Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. If you are not familiar with Hibernate then you can check our Hibernate tutorial. And if you are not familiar with Spring then you can check our Spring tutorial.

Step 1: Create a Database DOJDB on MySQL Database and also we create User table on this database.

CREATE TABLE User(
   ID   BIGINT NOT NULL AUTO_INCREMENT,
   USERNAME VARCHAR(20) NOT NULL,
   AGE  BIGINT NOT NULL,
   GENDER VARCHAR(20) NOT NULL,
   JOBTYPE VARCHAR(20) NOT NULL
   HOBBIES VARCHAR(20) NOT NULL
   PRIMARY KEY (ID)
);

Step 2: Create a database.properties for database configuration information in the resources folder under src folder in the created project.

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/DOJDB
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

Step 3: Create a Dynamic Web Project with a name Struts2Hibernate3Spring3Tile2Integration and create packages com.dineshonjava.struts2.action, com.dineshonjava.struts2.bean, com.dineshonjava.struts2.dao, com.dineshonjava.struts2.service, com.dineshonjava.struts2.model, com.dineshonjava.struts2.utils under the src folder in the created project.

Step 4: Add below mentioned Struts 2, Hibernate 3 and Spring 3 related libraries and other libraries into the folder WebRoot/WEB-INF/lib.

Struts 2 Hibernate 3 Integration Example with Spring 3

Step 5: Create a Java class UserAction, UserBean, User, UserDao, UserDaoImpl, UserService, UserServiceImpl, CommonUtility under the respective packages.

Step 6: Create Spring configuration files web.xml, applicationContext.xml, tiles-def.xml under the WebRoot/WEB-INF/ and struts.xml under src/resources folders.

Step 7: Create View files under the /WebRoot/ folder. Create a view file mainTemplate.jsp, users.jsp, body.jsp, menu.jsp, haeder.jsp, footer.jsp etc.

Step 8: Project Structure

Struts Hibernate Integration Example with Spring

APPLICATION ARCHITECTURE
We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called UserService.

Struts 2 Hibernate 3 Integration Example

Step 9: Hibernate Configuration file with Spring Dependencies 
applicationContext.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
 <context:component-scan base-package="com.dineshonjava.struts2" />
 
 <!-- Database Configuration Start here-->
 <context:property-placeholder location="classpath:database.properties"/>
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
   <property name="driverClassName" value="${database.driver}"></property>
   <property name="url" value="${database.url}"></property>
   <property name="username" value="${database.user}"></property>
   <property name="password" value="${database.password}"></property>
 </bean>
 <bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
   <property name="dataSource" ref="dataSource"></property>
   <property name="annotatedClasses">
     <list>
       <value>com.dineshonjava.struts2.model.User</value>
     </list>
   </property>
   <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
      <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
      <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>    
         </props>
       </property>
 </bean>
 
  <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager" id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
 <!-- Database Configuration End Here-->
 
 
 <bean id="user" class="com.dineshonjava.struts2.action.UserAction"/>
    <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean"/>
</beans>

Let us go through the hibernate configuration only because rest is Spring dependency already know in spring tutorial. First, we declared that we are using MySQL driver. Then we declared the jdbc url for connecting to the database. Then we declared the connection’s username, password and pool size. We also indicated that we would like to see the SQL in the log file by turning on “show_sql” to true. Please go through the hibernate tutorial to understand what these properties mean. Finally, we set the mapping class to com.dineshonjava.struts2.model.User which we will create in this chapter.

Step 10: Create Action class and Other classes related to Application.
 UserBean.java

package com.dineshonjava.struts2.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class UserBean {
 private String userName;
 private Long userAge;
 private String userGender;
 private String userJob;
 private String []userHobbies;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public Long getUserAge() {
  return userAge;
 }
 public void setUserAge(Long userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJob() {
  return userJob;
 }
 public void setUserJob(String userJob) {
  this.userJob = userJob;
 }
 public String[] getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String[] userHobbies) {
  this.userHobbies = userHobbies;
 }
}

User.java

package com.dineshonjava.struts2.model;

import java.io.Serializable;

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

/**
 * @author Dinesh Rajput
 *
 */
@Entity
@Table(name="User")
public class User implements Serializable {

 private static final long serialVersionUID = 1L;
 
 @Id  
 @GeneratedValue(strategy=GenerationType.AUTO)  
 @Column(name = "id")
 private Long userId;
 @Column(name="username")
 private String userName;
 @Column(name="age")
 private Long userAge;
 @Column(name="gender")
 private String userGender;
 @Column(name="jobtype")
 private String userJobType;
 @Column(name="Hobbies")
 private String userHobbies;
 public Long getUserId() {
  return userId;
 }
 public void setUserId(Long userId) {
  this.userId = userId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public Long getUserAge() {
  return userAge;
 }
 public void setUserAge(Long userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJobType() {
  return userJobType;
 }
 public void setUserJobType(String userJobType) {
  this.userJobType = userJobType;
 }
 public String getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String userHobbies) {
  this.userHobbies = userHobbies;
 }
}

UserDao.java

package com.dineshonjava.struts2.dao;

import java.util.List;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public interface UserDao {
 void saveUser(User user);
 
 List<User> getUserList(); 
}

UserDaoImpl.java

package com.dineshonjava.struts2.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
@Repository("userDao")  
public class UserDaoImpl implements UserDao {

 @Autowired  
 private SessionFactory sessionFactory;  
 
 @Override
 public void saveUser(User user) {
  sessionFactory.getCurrentSession().saveOrUpdate(user);
 }

 @SuppressWarnings("unchecked")
 @Override
 public List<User> getUserList() {
  return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
 }
}

UserService.java

package com.dineshonjava.struts2.service;

import java.util.List;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public interface UserService {
 void saveUser(User user);
 
 List<User> getUserList(); 
}

UserServiceImpl.java

package com.dineshonjava.struts2.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dineshonjava.struts2.dao.UserDao;
import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) 
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao userDao;
 
 @Override
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
 public void saveUser(User user) {
  userDao.saveUser(user);
 }

 @Override
 public List<User> getUserList() {
  return userDao.getUserList();
 }
}

CommonUtility.java

package com.dineshonjava.struts2.utils;

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

import com.dineshonjava.struts2.bean.UserBean;
import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public class CommonUtility {
 public static User createModel(UserBean userBean){
  User user = new User();
  user.setUserName(userBean.getUserName());
  user.setUserAge(userBean.getUserAge());
  user.setUserGender(userBean.getUserGender());
  user.setUserJobType(userBean.getUserJob());
  user.setUserHobbies(convertArrayToCsv(userBean.getUserHobbies()));
  return user;
 }
 
 public static List<UserBean> createUserBeanList(List<User> users){
  List<UserBean> beans = new ArrayList<UserBean>();
  UserBean userBean = null;
  for(User user : users){
   userBean = new UserBean();
   userBean.setUserName(user.getUserName());
   userBean.setUserAge(user.getUserAge());
   userBean.setUserGender(user.getUserGender());
   userBean.setUserJob(user.getUserJobType());
   userBean.setUserHobbies(convertCsvToArr(user.getUserHobbies()));
   beans.add(userBean);
  }
  return beans;
  
 }
 public static String convertArrayToCsv(String [] arr){
  String csv = "";
  for(String value : arr){
   csv += value+",";
  }
  return csv;
 }
 public static String[] convertCsvToArr(String csv){
  String [] values = csv.split(",");
  return values;
 }
}

UserAction.java

package com.dineshonjava.struts2.action;

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

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

import com.dineshonjava.struts2.bean.UserBean;
import com.dineshonjava.struts2.model.User;
import com.dineshonjava.struts2.service.UserService;
import com.dineshonjava.struts2.utils.CommonUtility;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Dinesh Rajput
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<UserBean>{

 private static final long serialVersionUID = 1L;
 
 @Autowired
 private UserBean userBean;
 @Autowired
 private UserService userService;
 private List<UserBean> users;

 public String execute() {
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "user";
 }
 
 public String addUser(){
  userService.saveUser(CommonUtility.createModel(userBean));
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "addUser";
 }
 public String listUser(){
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "users";
 }
 
 @Override
 public UserBean getModel() {
  return userBean;
 }
 public String alia() { 
  return "alia";
 }
 public String madhuri() { 
  return "madhuri"; 
 }
 public String user() { 
  return "user"; 
 }

 public List<UserBean> getUsers() {
  return users;
 }

 public void setUsers(List<UserBean> users) {
  this.users = users;
 }
 
}

Create view files:
Let us now create the mainTemplate.jsp view file with the following content:

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!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=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute>
</title>
</head>

<body>
  <table border="1">
   <tr>
    <td colspan="2"><tiles:insertAttribute name="header"></tiles:insertAttribute><br/></td>
   </tr>
   <tr>
    <td><tiles:insertAttribute name="menu" /></td>
    <td><tiles:insertAttribute name="body" /></td>
   </tr>
   <tr>
    <td colspan="2"><tiles:insertAttribute name="footer" /></td>
   </tr>
  </table>
</body>
</html>

body.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style type="text/css">
b{color:navy; background-color: orange;}  
</style>
<title>Struts2-Spring-Tiles integration | dineshonjava.com</title>
</head>
<body>

 <h2>Add User</h2><b>
    <s:form  action="addUsermenu">
    <s:textfield name="userName" key="user.name" />
    <s:textfield name="userAge" key="user.age" value=""/>
    <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" />
    <s:select name="userJob"  key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/>  
    <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" />  
    <s:submit key="submit" align="center"/>
 </s:form>
 </b>
 <s:if test="%{users.isEmpty()}"> 
 </s:if>
 <s:else>
  <b>List of Users</b>
   <table border="1">
       <tr>
          <td><b>Name</b></td>
          <td><b>Age</b></td>
          <td><b>Gender</b></td>
          <td><b>Job Type</b></td>
          <td><b>Hobbies</b></td>
       </tr>
   <s:iterator value="users"> 
          <tr>
             <td><s:property value="userName"/></td>
             <td><s:property value="userAge"/></td>
             <td><s:property value="userGender"/></td>
              <td><s:property value="userJob"/></td>
              <td><s:property value="userHobbies"/></td>
            </tr>
       </s:iterator>
       </table>
       </s:else>
 </body>
</html>

menu.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 <a href="<s:url action="usermenu"/>"> <h2>Add User</h2></a><br>
 <a href="<s:url action="aliamenu"/>"><h2>Alia Bhatt</h2></a><br>
    <a href="<s:url action="madhurimenu"/>"><h2>Madhuri Dixit</h2></a><br>

footer.jsp

<center><p><h2>Copyright &copy; 2013 dineshonjava.com</h2></p> </center>

header.jsp

<table>
  <tr>
   <td><img src="http://2.bp.blogspot.com/-rBLnvKuVDO0/UWBnJJ4n1yI/AAAAAAAADCQ/Vh_cVJ34JFw/s1600/new-logo.png" /></td>
    <td><h1><span style="background-color: #FFFFcc">Struts2-Hibernate3-Tiles2-Spring3 integration</span></h1></td>
  </tr>
</table>

users.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <a href="user">Struts2Spring3Hibernate3Tiles Example</a>
</body>
</html>

madhuri.jsp

<img src="http://www.topnews.in/files/Madhuri-Dixit_10.jpg" height="430" width="500" alt="Madhuri Dixit"/>

alia.jsp

<img src="http://cdntopics.onepakistan.com/wp-content/uploads/2012/10/Alia-Bhatt1.jpg" alt="Alia Bhatt"/>

Struts Configuration:
Let us put it all together using struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="user" extends="struts-default" namespace="/">
        <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
       </result-types>
        <action name="user" class="user" method="execute">
            <result name="user" type="tiles">mainTemplate</result>
        </action>
        <action name="*menu" class="user" method="{1}">
            <result name="user" type="tiles">mainTemplate</result>
            <result name="madhuri" type="tiles">madhuri</result>
            <result name="alia" type="tiles">alia</result>
            <result name="addUser" type="tiles">mainTemplate</result>
        </action>
    </package>
 </struts>

myapp.properties

user.name=User Name
user.age=User Age
user.gender=Gender
user.job=Job Type
user.hobby=Hobbies
submit=Add User

Tiles Configuration file-
tiles-def.xml

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

<!DOCTYPE tiles-definitions PUBLIC
   "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
   "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

   <definition name="mainTemplate" template="/mainTemplate.jsp">
      <put-attribute name="title"  value="User Registration Form"/>
      <put-attribute name="header" value="/header.jsp"/>
      <put-attribute name="menu"   value="/menu.jsp"/>
      <put-attribute name="body"   value="/body.jsp"/>
      <put-attribute name="footer"   value="/footer.jsp"/>
   </definition>

   <definition name="alia" extends="mainTemplate">
      <put-attribute name="title"  value="Alia Bhatt"/>
      <put-attribute name="body"   value="/alia.jsp"/>      
   </definition>

   <definition name="madhuri" extends="mainTemplate">
      <put-attribute name="title"  value="Madhuri Dixit"/>
      <put-attribute name="body"   value="/madhuri.jsp"/>      
   </definition>
   
   <definition name="success" extends="mainTemplate">
      <put-attribute name="title"  value="User Added Successfully"/>
      <put-attribute name="body"   value="/success.jsp"/>      
   </definition>
  
</tiles-definitions>

create deployment descriptor
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Hibernate3Spring3Tile2Integration</display-name>
  <welcome-file-list>
        <welcome-file>users.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
    <param-name>
       org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
    </param-name>
    <param-value>
       /WEB-INF/tiles-def.xml
    </param-value>
   </context-param>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <listener>
       <listener-class>
        org.apache.struts2.tiles.StrutsTilesListener
       </listener-class>
   </listener>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
           org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/user

This will give you following screen:

output

Fill data of user form and submit let see following screen we will get.

http://localhost:8080/doj/addUsermenu.action

output

http://localhost:8080/doj/madhurimenu.action

output

Download Source Code + Libs
Struts2Hibernate3Spring3Tile2Integration.zip

<<Previous <<   || Index ||   >>Next >>

Struts2 Integration with Tiles2 & Spring3

In this tutorial we will discuss about Tiles Framework and its Integration with Struts2. We will add Tiles support to our previous Struts application with Spring 3 that we created in previous parts. I strongly recommend you to go through previous articles and download the source code of our sample application.

Introduction to Tiles 2:
Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel. It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page.

Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you
define parts of page (a “Tile”) that you assemble to build another part or a full page. A part can
take parameters, allowing dynamic content, and can be seen as a method in JAVA language. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.

A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application.
Our Application Layout
Our goal is to add Header, Footer, Menu and Body to our Struts2TilesIntegration application. Following will be the layout of the same.

Struts2 Integration with Tiles2 & Spring3

There are following tool we need to create this application.
1. Strus2
2. Spring3
3. STS or Eclipse
4. Tiles 2

In this example we will using the three frameworks Struts2, Spring3 and Tiles2 with Internationalization in one application.
Step 1: Project Structure-

Struts Integration with Tiles & Spring

Step 2: There are following jars file need to be add
commons-beanutils-1.8.0.jar
commons-digester-2.0.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
freemarker-2.3.18.jar
javassist-3.0.jar
ognl-3.0.4.jar
spring-asm-3.0.1.RELEASE.jar
spring-beans-3.0.1.RELEASE.jar
spring-context-3.0.1.RELEASE.jar
spring-core-3.0.1.RELEASE.jar
spring-expression-3.0.1.RELEASE.jar
spring-jdbc-3.0.1.RELEASE.jar
spring-orm-3.0.1.RELEASE.jar
spring-tx-3.0.1.RELEASE.jar
spring-web-3.0.1.RELEASE.jar
spring-webmvc-3.0.1.RELEASE.jar
struts2-core-2.3.1.2.jar
struts2-dojo-plugin-2.3.15.jar
struts2-spring-plugin-2.3.15.jar
struts2-tiles-plugin-2.3.15.jar
tiles-api-2.0.6.jar
tiles-compat-3.0.1.jar
tiles-core-2.0.6.jar
tiles-jsp-2.0.6.jar
tiles-servlet-3.0.1.jar
xwork-core-2.3.1.2.jar

Step 3: Struts 2 + Spring 3+ Tiles Plugin
To integrate Struts 2 and Spring, get and include the “struts2-spring-plugin-xxx.jar” and “struts2-tiles-plugin-xxx.jar” library into your project classpath. As already added above struts2-spring-plugin-2.3.15.jar and struts2-tiles-plugin-2.3.15.jar.

Step 4: Tiles Listener and Spring Listener
Configure the Spring listener “org.springframework.web.context.ContextLoaderListener” and Tiles Listener “org.apache.struts2.tiles.StrutsTilesListener” in web.xml file.

Configuring Tiles in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2TilesIntegration</display-name>
  <welcome-file-list>
        <welcome-file>user</welcome-file>
    </welcome-file-list>
    <context-param>
    <param-name>
       org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
    </param-name>
    <param-value>
       /WEB-INF/tiles-def.xml
    </param-value>
   </context-param>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <listener>
       <listener-class>
        org.apache.struts2.tiles.StrutsTilesListener
       </listener-class>
   </listener>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
           org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

The above code configure Tiles listener in web.xml. An input configuration file /WEB-INF/tiles-def.xml is passed as argument. This file contains the Tiles definition for our web application.
Step 4: Create a file tiles-def.xml in WEB-INF folder and copy following code into it.

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

<!DOCTYPE tiles-definitions PUBLIC
   "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
   "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

   <definition name="mainTemplate" template="/mainTemplate.jsp">
      <put-attribute name="title"  value="User Registration Form"/>
      <put-attribute name="header" value="/header.jsp"/>
      <put-attribute name="menu"   value="/menu.jsp"/>
      <put-attribute name="body"   value="/body.jsp"/>
      <put-attribute name="footer"   value="/footer.jsp"/>
   </definition>

   <definition name="alia" extends="mainTemplate">
      <put-attribute name="title"  value="Alia Bhatt"/>
      <put-attribute name="body"   value="/alia.jsp"/>      
   </definition>

   <definition name="madhuri" extends="mainTemplate">
      <put-attribute name="title"  value="Madhuri Dixit"/>
      <put-attribute name="body"   value="/madhuri.jsp"/>      
   </definition>
   
   <definition name="success" extends="mainTemplate">
      <put-attribute name="title"  value="User Added Successfully"/>
      <put-attribute name="body"   value="/success.jsp"/>      
   </definition>
  
</tiles-definitions>

Here in tiles-def.xml we have define a template mainTemplate. This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for alia, madhuri and success page is defined. We have override the default layout and changed the content for Body and Title.
Step 5:  Creating JSPs
We will define the template for our web application in a JSP file called mainTemplate.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files mainTemplate.jsp, header.jsp, menu.jsp, body.jsp, madhuri.jsp, alia.jsp, success.jsp and footer.jsp and copy following content in each of them.
mainTemplate.jsp

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!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=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute>
</title>
</head>

<body>
  <table border="1">
   <tr>
    <td colspan="2"><tiles:insertAttribute name="header"></tiles:insertAttribute><br/></td>
   </tr>
   <tr>
    <td><tiles:insertAttribute name="menu" /></td>
    <td><tiles:insertAttribute name="body" /></td>
   </tr>
   <tr>
    <td colspan="2"><tiles:insertAttribute name="footer" /></td>
   </tr>
  </table>
</body>
</html>

body.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style type="text/css">
b{color:navy; background-color: orange;}  
</style>
<title>Struts2-Spring-Tiles integration | dineshonjava.com</title>
</head>
<body>

 <h2>Add User</h2><b>
    <s:form  action="addUsermenu">
    <s:textfield name="userName" key="user.name" />
    <s:textfield name="userAge" key="user.age" value=""/>
    <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" />
    <s:select name="userJob"  key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/>  
    <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" />  
    <s:submit key="submit" align="center"/>
 </s:form>
 </b>
</body>
</html>

header.jsp

<table>
  <tr>
   <td><img src="http://2.bp.blogspot.com/-rBLnvKuVDO0/UWBnJJ4n1yI/AAAAAAAADCQ/Vh_cVJ34JFw/s1600/new-logo.png" /></td>
    <td><h1><span style="background-color: #FFFFcc">Struts2-Tiles-Spring integration</span></h1></td>
  </tr>
</table>

footer.jsp

<center><p><h2>Copyright &copy; 2013 dineshonjava.com</h2></p> </center>

menu.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 <a href="<s:url action="usermenu"/>"> <h2>Add User</h2></a><br>
 <a href="<s:url action="aliamenu"/>"><h2>Alia Bhatt</h2></a><br>
    <a href="<s:url action="madhurimenu"/>"><h2>Madhuri Dixit</h2></a><br>

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Struts2-Spring-Tiles integration | dineshonjava.com</title>
</head>
<body>

 <h2>List of User</h2>
    <ul>
   <li>User Name : <s:property value="userName" /></li>
   <li>User Age : <s:property value="userAge" /></li>
   <li>User Gender : <s:property value="userGender" /></li>
   <li>User Jobs : <s:property value="userJob" /></li>
   <li>User Hobbies : <s:property value="userHobbies" /></li>
 </ul> 
</body>
</html>

madhuri.jsp

<img src="http://www.topnews.in/files/Madhuri-Dixit_10.jpg" height="430" width="500" alt="Madhuri Dixit"/>

alia.jsp

<img src="http://cdntopics.onepakistan.com/wp-content/uploads/2012/10/Alia-Bhatt1.jpg" alt="Alia Bhatt"/>

Step 6: Register Spring Bean
Register all the Spring’s Beans in the applicationContext.xml file, the Spring listener will locate this xml file automatically.
applicationContext.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <context:component-scan base-package="com.dineshonjava.struts2.bean" />
 <bean id="user" class="com.dineshonjava.struts2.action.UserAction">
   </bean>
   <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean">
   </bean>
</beans>

Step 7: Create Action class and User bean.
UserAction.java

package com.dineshonjava.struts2.action;

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

import com.dineshonjava.struts2.bean.UserBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Dinesh Rajput
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<UserBean>{

 private static final long serialVersionUID = 1L;
 
 @Autowired
 private UserBean userBean;

 public String execute()
 {
  return "user";
 }
 
 public String addUser()
 {
  return "addUser";
 }
 
 @Override
 public UserBean getModel() {
  return userBean;
 }
 public String alia() { 
  return "alia";
 }
 public String madhuri() { 
  return "madhuri"; 
 }
 public String user() { 
  return "user"; 
 }
}

Here userBean property autowired with action class UserAction java it is also powerfull feature of Spring framework.
UserBean.java

package com.dineshonjava.struts2.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class UserBean {
 private String userName;
 private int userAge;
 private String userGender;
 private String userJob;
 private String []userHobbies;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public int getUserAge() {
  return userAge;
 }
 public void setUserAge(int userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJob() {
  return userJob;
 }
 public void setUserJob(String userJob) {
  this.userJob = userJob;
 }
 public String[] getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String[] userHobbies) {
  this.userHobbies = userHobbies;
 }
 
}

Step 8: Modifications in Struts.xml
In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="user" extends="struts-default" namespace="/">
        <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
       </result-types>
        <action name="user" class="user" method="execute">
            <result name="user" type="tiles">mainTemplate</result>
        </action>
        <action name="*menu" class="user" method="{1}">
            <result name="user" type="tiles">mainTemplate</result>
            <result name="madhuri" type="tiles">madhuri</result>
            <result name="alia" type="tiles">alia</result>
            <result name="addUser" type="tiles">success</result>
        </action>
    </package>
 </struts>

Let us check what we did in above file. First of all, we declared a new result type called “tiles” as we are now using tiles instead of plain jsp for the view technology. Struts2 has its support for the Tiles View result type, so we create the result type “tiles” to be of the “org.apache.struts2.view.tiles.TilesResult” class.

The struts.xml now defines a new Result type for Tiles. This result type is used in <result> tag for different actions. Also note that we have define a new action user. This is just an empty declaration to redirect user to user form page when she clicks Add User link from menu.

Next, we want to say if the request is for /usermenu.action take the user to the mainTemplate tiles page and if the request is for /madhurimenu.action take the user to the madhuri tiles page.

We achieve this using a bit of regular expression. In our action definition, we say anything that matches the pattern “*menu” will be handled by this action. The matching method will be invoked in the UserAction class. That is, aliamenu.action will invoke alia() and madhurimenu.action will invoke madhuri(). We then need to map the outcome of the result to the appropriate tiles pages.

myapp.properties

user.name=User Name
user.age=User Age
user.gender=Gender
user.job=Job Type
user.hobby=Hobbies
submit=Add User

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/user

This will give you following screen:

output

Fill the user form and click on “Add User” button we will get the following page.
http://localhost:8080/doj/addUsermenu.action

output

Click on the Madhuri Dixit link from menu then we will get the following screen.
http://localhost:8080/doj/madhurimenu.action

output

Click on the Aalia Bhatt link from menu then we will get the following screen.
http://localhost:8080/doj/aliamenu.action

output

Download Source Code + Libs
Struts2Tiles2Spring3Integration.zip

<<Previous <<   || Index ||   >>Next >>

Struts2 Spring 3 Integration Example

In this tutorial, it shows the integration between Struts 2 and Spring3. Why you want to integrate spring with struts 2? Spring provides some features which are not available in struts 2.Most powerful among them is dependency injection. To learn more about dependency injection, you can refer dependency injection in spring link.

There are following tool we need to create this application.
1. Strus2
2. Spring3
3. STS or Eclipse

Step 1: Project Structure

Struts2 Spring 3 Integration Example

Step 2: There are following jars file need to be add
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
freemarker-2.3.18.jar
javassist-3.0.jar
ognl-3.0.4.jar
spring-asm-3.0.1.RELEASE.jar
spring-beans-3.0.1.RELEASE.jar
spring-context-3.0.1.RELEASE.jar
spring-core-3.0.1.RELEASE.jar
spring-expression-3.0.1.RELEASE.jar
spring-jdbc-3.0.1.RELEASE.jar
spring-orm-3.0.1.RELEASE.jar
spring-tx-3.0.1.RELEASE.jar
spring-web-3.0.1.RELEASE.jar
spring-webmvc-3.0.1.RELEASE.jar
struts2-core-2.3.1.2.jar
struts2-dojo-plugin-2.3.15.jar
struts2-spring-plugin-2.3.15.jar
xwork-core-2.3.1.2.jar

Step 3: Struts 2 + Spring 3 Plugin
To integrate Struts 2 and Spring, get and include the “struts2-spring-plugin-xxx.jar” library into your project classpath. As already added above struts2-spring-plugin-2.3.15.jar.

Step 4: Spring Listener
Configure the Spring listener “org.springframework.web.context.ContextLoaderListener” in web.xml file.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Spring3Intergration</display-name>
   <welcome-file-list>
        <welcome-file>User.jsp</welcome-file>
    </welcome-file-list>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>

The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring’s configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file.

Step 5: Register Spring Bean
Register all the Spring’s Beans in the applicationContext.xml file, the Spring listener will locate this xml file automatically.
applicationContext.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <context:component-scan base-package="com.dineshonjava.struts2.bean" />
 <bean id="user" class="com.dineshonjava.struts2.action.user.UserAction">
   </bean>
   <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean">
   </bean>
</beans>

Step 7: Create Action class and User bean.
UserAction.java

package com.dineshonjava.struts2.action.user;

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

import com.dineshonjava.struts2.bean.UserBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Dinesh Rajput
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<UserBean>{

 private static final long serialVersionUID = 1L;
 
 @Autowired
 private UserBean userBean;

 public String execute()
 {
  return SUCCESS;
 }
 
 public String addUser()
 {
  return SUCCESS;
 }
 
 @Override
 public UserBean getModel() {
  return userBean;
 }
}

Here userBean property autowired with action class UserAction java it is also powerfull feature of Spring framework.

UserBean.java

package com.dineshonjava.struts2.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class UserBean {
 private String userName;
 private int userAge;
 private String userGender;
 private String userJob;
 private String []userHobbies;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public int getUserAge() {
  return userAge;
 }
 public void setUserAge(int userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJob() {
  return userJob;
 }
 public void setUserJob(String userJob) {
  this.userJob = userJob;
 }
 public String[] getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String[] userHobbies) {
  this.userHobbies = userHobbies;
 }
}

Step 8: Struts.xml
Declared all the relationship here.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="user" extends="struts-default">
        <action name="user" class="user" method="execute">
            <result name="success">/success.jsp</result>
            <result name="input">/User.jsp</result>
        </action>
    </package>
 </struts>

The important thing to note is that we are using the id user to refer to the class. This means that we are using spring to do the dependency injection for the User class.
Step 9: Create View
Next let us create the User.jsp in the WebRoot folder:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style type="text/css">
b{color: blue;}  
</style>
<title>Struts2 - Spring integration | dineshonjava.com</title>
</head>
<body>

   <h1><span style="background-color: #FFFFcc">User From Struts2 - Spring integration</span></h1>
 <h2>Add User</h2><b>
    <s:form  action="user" method="addUser">
    <s:textfield name="userName" key="user.name" />
    <s:textfield name="userAge" key="user.age" value=""/>
    <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" />
    <s:select name="userJob"  key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/>  
    <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" />  
    <s:submit key="submit" align="center"/>
 </s:form>
 </b>
</body>
</html>

Creating success.jsp file for after submit.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Struts2 - Spring integration | dineshonjava.com</title>
</head>
<body>

     <h1><span style="background-color: #FFFFcc">User From Struts2 - Spring integration</span></h1>
 <h2>List of User</h2>
    <ul>
   <li>User Name : <s:property value="userName" /></li>
   <li>User Age : <s:property value="userAge" /></li>
   <li>User Gender : <s:property value="userGender" /></li>
   <li>User Jobs : <s:property value="userJob" /></li>
   <li>User Hobbies : <s:property value="userHobbies" /></li>
 </ul> 
</body>
</html>

myapp.properties

user.name=User Name
user.age=User Age
user.gender=Gender
user.job=Job Type
user.hobby=Hobbies
submit=Add User

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access 

URL http://localhost:8080/doj/User.jsp. 

This will give you following screen:

output

Clicking on “Add User” button then we will see following screen:

output

Download Source Code + Libs
Struts2Spring3Intergration.zip

<<Previous <<   || Index ||   >>Next >>

Struts 2 – The Ajax Tags Example

In this tutorial we will discuss about struts 2 Ajax Call tag with using struts dojo plugin in our application.
Struts uses the DOJO framework for the AJAX tag implementation. First of all, to proceed with this example, you need to add struts2-dojo-plugin-2.3.15.jar to your classpath.

For this exercises, let us create ajax.jsp as follows:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title>Ajax Tag Struts2 | dineshonjava.com</title>
<s:head />
<sx:head />
</head>
<body>
   <s:form>
      <sx:autocompleter label="Favourite Colour"
         list="{'red','green','blue'}" />
      <br />
      <sx:datetimepicker name="deliverydate" label="Delivery Date"
         displayFormat="dd/MM/yyyy" />
      <br />
      <s:url id="url1" value="/count1" />
      <s:url id="url2" value="/count2" />
      <s:url id="url3" value="/count3" />
      <sx:div href="%{#url3}" delay="2000">
           Initial Content
      </sx:div>
      <br/>
      <sx:tabbedpanel id="tabContainer">
         <sx:div label="Tab 1" href="%{#url1}">Tab 1</sx:div>
         <sx:div label="Tab 2" href="%{#url2}">Tab 2</sx:div>
      </sx:tabbedpanel>
   </s:form>
</body>
</html>

select.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Form Tag Struts2 | dineshonjava.com</title>
<s:head />
</head>
<body>
   <s:form action="login.action">
      <s:select name="username" label="Username"
         list="{'Mike','John','Smith'}" />

      <s:select label="Company Office" name="mySelection"
         value="%{'America'}"
         list="%{#{'America':'America'}}">
      <s:optgroup label="Asia" 
         list="%{#{'India':'India','China':'China'}}" />
      <s:optgroup label="Europe"
         list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" />
      </s:select>

      <s:combobox label="My Sign" name="mySign"
         list="#{'aries':'aries','capricorn':'capricorn'}"
         headerKey="-1" 
         headerValue="--- Please Select ---" emptyOption="true"
         value="capricorn" />
      <s:doubleselect label="Occupation" name="occupation"
         list="{'Technical','Other'}" doubleName="occupations2"
         doubleList="top == 'Technical' ? 
         {'I.T', 'Hardware'} : {'Accounting', 'H.R'}" />

   </s:form>
</body>
</html>

welcome.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Tag Struts2 | dineshonjava.com</title>
</head>
<body>
<b>Welcome to Ajax Call in Struts2</b>
</body>
</html>

success.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

   <s:form action="employee">
   <s:radio label="Gender" name="gender" list="{'male','female'}" />
   <s:checkboxlist label="Job Types" name="jobtypes"
   list="{'Software','Hardware','Networking','Marketing'}" />
   </s:form>

Strus2 Configuration file
struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="default" extends="struts-default" namespace="/">
        <action name="ajaxtag" class="com.dineshonjava.struts2.action.FormTagAction">
            <result name="success">/ajax.jsp</result>
        </action>
        <action name="count1" class="com.dineshonjava.struts2.action.FormTagAction" method="tab1">
            <result name="success">/select.jsp</result>
        </action>
        <action name="count2" class="com.dineshonjava.struts2.action.FormTagAction" method="tab2">
            <result name="success">/success.jsp</result>
        </action>
         <action name="count3" class="com.dineshonjava.struts2.action.FormTagAction" method="tab3">
            <result name="success">/welcome.jsp</result>
        </action>
    </package>
 </struts>

Create Action Class:

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class FormTagAction extends ActionSupport {

 private static final long serialVersionUID = 1L;
 
 public String execute(){
  return SUCCESS;
 }
 public String tab1(){
  return SUCCESS;
 }
 public String tab2(){
  return SUCCESS;
 }
 public String tab3(){
  return SUCCESS;
 }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2FormTags</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Let us now go through this example one step at a time.

First thing to notice is the addition of a new tag library with the prefix sx. This (struts-dojo-tags) is the tag library specifically created for the ajax integration.

Then inside the HTML head we call the sx:head. This initializes the dojo framework and makes it ready for all AJAX invocations within the page. This step is important – your ajax calls will not work without the sx:head being initialized.

First we have the autocompleter tag. The autocompleter tag looks pretty much like a select box. It is populated with the values red, green and blue. But the different between a select box and this one is that it auto completes. That is, if you start typing in gr, it will fill it with “green”. Other than that this tag is very much similar to the s:select tag which we covered earlier.

Next, we have a date time picker. This tag creates an input field with a button next to it. When the button is pressed, a popup date time picker is displayed. When the user selects a date, the date is filled into the input text in the format that is specified in the tag attribute. In our example, we have specified dd/MM/yyyy as the format for the date.

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/ajaxtag.

This will give you following screen:

output

After 2000 ms delay one ajax call action “count3” and display following

output

When click on “tab2” ajax call “count2” action and display following.

output

Download Source Code + Libs
ajaxtagstruts2example.zip

<<Previous <<   || Index ||   >>Next >>

The Form Tags in Struts2

Simple UI Tags:
We have used these tags in our examples already, we will brush them in this chapter. Let us look a simple view page index.jsp with several simple UI tags:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<s:head/>
<title>Hello World</title>
</head>
<body>
   <s:div>Email Form</s:div>
   <s:text name="Please fill in the form below:" />
   <s:form action="hello" method="post" enctype="multipart/form-data">
   <s:hidden name="secret" value="abracadabra"/>
   <s:textfield key="email.from" name="from" />
   <s:password key="email.password" name="password" />
   <s:textfield key="email.to" name="to" />
   <s:textfield key="email.subject" name="subject" />
   <s:textarea key="email.body" name="email.body" />
   <s:label for="attachment" value="Attachment"/>
   <s:file name="attachment" accept="text/html,text/plain" />
   <s:token />
   <s:submit key="submit" />
   </s:form>
</body>
</html>

If you are aware of HTML then all the tags used are very common HTML tags with an additional prefix s: alongwith each tag and different attributes. When we execute the above program, we get the following user interface provided you have setup proper mapping for all the keys used.

The Form Tags in Struts2

As shown, the s:head generates the javascript and stylesheet elements required for the Struts2 application.

Next, we have the s:div and s:text elements. The s:div is used to render a HTML Div element. This is useful for people who do not like to mix HTML and Struts tags together. For those people, they have the choice to use s:div to render a div.

The s:text as shown is used to render a text on the screen.

Next we have the famiilar s:form tag. The s:form tag has an action attribute that determines where to submit the form. Because we have a file upload element in the form, we have to set the enctype to multipart. Otherwise, we can leave this blank.

At the end of the form tag, we have the s:submit tag. This is used to submit the form. When the form is submitted, all the form values are submitted to the the action specified in the s:form tag

Inside the s:form, we have a hidden attribute called secret. This renders a hidden element in the HTML. In our case, the “secret” element has the value “abracadabra”. This element is not visible to the end user and is used to carry the state from one view to another.

Next we have the s:label, s:textfield, s:password and s:textarea tags. These are used to render the label, input field, password and the text area respectively. We have seen these in action in the “Struts – Sending Email” example. The important thing to note here is the use of “key” attribute. The “key” attribute is used to fetch the label for these controls from the property file. We have already covered this feature in the Struts-Internalization chapter.

Then, we have the s:file tag which renders a input file upload component. This component allows the user to upload files. In this example, we have used the “accept” paramter of the s:file tag to specify which file types are allowed to be uploaded.

Finally we have the s:token tag. The token tag generates an unique token which is used to find out whether a form has been double submitted.

When the form is rendered, a hidden variable is placed as the token value. Let us say, for example that the token is “ABC”. When this form is submitted, the Struts Fitler checks the token against the token stored in the session. If it matches, it removes the token from the session. Now, if the form is accidentally resubmitted (either by refreshing or by hitting the browser back button), the form will be resubmitted with “ABC” as the token. In this case, the filter checks the token against the token stored in the session again. But because the token “ABC” has been removed from the session, it will not match and the Struts filter will reject the request.

Group UI Tags:
The group UI tags are used to create radio button and the checkbox. Let us look a simple view page employee.jsp with check box and radio button tags:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<STYLE type="text/css">

b{color: blue;}

</STYLE>
<title>Form Tag Struts2 | dineshonjava.com</title>
</head>
<body>
   <s:form action="employee">
   <s:radio label="Gender" name="gender" list="{'male','female'}" />
   <s:checkboxlist label="Job Types" name="jobtypes"
   list="{'Software','Hardware','Networking','Marketing'}" />
   </s:form>
</body>
</html>

When we execute the above program our output will look similar to the following:

Form Tags

Let us look at the example now. In the first example, we are creating a simple radiobutton with the label “Gender”. The name attribute is mandatory for the radiobutton tag, so we specify a name which is “gender”. We then supply a list to the gender. The list is populated with the values “male” and “female”. Therefore, in the output we get a radiobutton with two values in it.

In the second example, we are creating a checkbox list. This is to gather the employee’s job type. The employee can have more than one job and therefore we are using the checkbox instead of the radiobutton. The checkbox is populated with the list “Software”, “Hardware”,”Networking” and “Marketing”. This presents the hobbies as a checkbox list.

Select UI Tags:
Let us explore the different variations of the Select Tag offered by Struts. Let us look a simple view page select.jsp with select tags:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Form Tag Struts2 | dineshonjava.com</title>
<s:head />
</head>
<body>
   <s:form action="login.action">
      <s:select name="username" label="Username"
         list="{'Mike','John','Smith'}" />

      <s:select label="Company Office" name="mySelection"
         value="%{'America'}"
         list="%{#{'America':'America'}}">
      <s:optgroup label="Asia" 
         list="%{#{'India':'India','China':'China'}}" />
      <s:optgroup label="Europe"
         list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" />
      </s:select>

      <s:combobox label="My Sign" name="mySign"
         list="#{'aries':'aries','capricorn':'capricorn'}"
         headerKey="-1" 
         headerValue="--- Please Select ---" emptyOption="true"
         value="capricorn" />
      <s:doubleselect label="Occupation" name="occupation"
         list="{'Technical','Other'}" doubleName="occupations2"
         doubleList="top == 'Technical' ? 
         {'I.T', 'Hardware'} : {'Accounting', 'H.R'}" />

   </s:form>
</body>
</html>

When we execute the above program our output will look similar to the following:

Form Tags in struts

  • First, the select tag renders the HTML select box. In the first example, we are creating a simple select box with name “username” and the label “username”. The select box will be populated with a list that contains the names Mike, John and Smith.
  • In the second example, our company has head offices in America. It also has global offices in Asia and Europe. We want to display the offices in a select box but we want to group the global offices by the name of the continent. This is where the optgroup comes in handy. We use the s:optgroup tag to create a new group. We give the group a label and a separate list.
  • In the third example, the combobox is used. A combo box is a combination of an input field and a select box. The user can either select a value from the select box in which case the input field is automatically filled in with the value the user has selected. Should the user to enter a value directly then no values from the select box will be selected.
  • In our example we have the combobox listing the sun signs. The selectbox lists only four entries allowing the user to type in his sun sign if it is not in the list. We also add a header entry to the select box. The headerentry is the one that is displayed at the top of the select box. In our case we want to display “Please Select”. If the user does not select anything, then we assume -1 as the value. In some cases, we do not want the user to select an empty value. In those conditions, one would set the “emptyOption” property to false. Finally, in our example we supply “capricorn” as the default value for the combobox.
  • In the fourth example, we have a double select. A double select is used when you want to display two select boxes. The value selected in the first select box determines what appears in the second select box. In our example the first select box displays “Technical” and “Other”. If the user selects Technical, we will display IT and Hardware in the second select box. Otherwise we will display Accounting and HR. This is possible using the “list” and “doubleList” atrributes as shown in the example.
<<Previous <<   || Index ||   >>Next >>

Struts 2 Url Tag Example

In this tutorial, We will discuss about the URL tag in struts2. This tag is used to create an URL and output it as a text format. It is never work by itself, but it can provides URL to other tags like <s:a> to create a hyperlink or <img> to render an image.

The url tag is responsible for generating URL strings. The advantage of this is that you can supply parameters to the tag. Let us go through an example to show the usage of url tag.

Create action classes:

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class DataTagAction extends ActionSupport {

 private static final long serialVersionUID = -7744420104547018874L;
 private String name;
 
 public String execute() {
  return SUCCESS;
 }

 public String getName() {
  return name;
 }

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

Create views
Let us have success.jsp with the following content:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<STYLE type="text/css">

b{color: blue;}

</STYLE>
<title>Text Data Tag Struts2 | dineshonjava.com</title>
</head>
<body>
   <h1><span style="background-color: #FFFFcc">Text Data Tags Example!</span></h1>
   <ol>
  <li>Image URL Here:<br>
   <a href="https://www.dineshonjava.com"><img src="<s:url value="http://2.bp.blogspot.com/-rBLnvKuVDO0/UWBnJJ4n1yI/AAAAAAAADCQ/Vh_cVJ34JFw/s1600/new-logo.png" /> " /></a>
  </li>

  <li>Simple URL Here:<br>
   <a href="<s:url value="https://www.dineshonjava.com" />">Dieshonjava</a>
  </li>

  <li>
   <s:url action="URLtag.action" var="URLtag">
    <s:param name="name">Dineshonjava</s:param>
   </s:url> 
   <a href="<s:property value="#URLtag" />">URL Tag Action (via property)</a>
  </li>

  <li>
   <s:url action="URLtag.action" var="URLtag">
    <s:param name="name">Dinesh Rajput</s:param>
   </s:url> 
   <s:a href="%{URLtag}">URL Tag Action (via %)</s:a>
  </li>
 </ol>
</body>
</html>

Configuration Files
Your struts.xml should look like:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="default" extends="struts-default" namespace="/">
        <action name="urltag" class="com.dineshonjava.struts2.action.DataTagAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
 </struts>

Your web.xml should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2DataTag</display-name>
 <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/urltag.

This will give you following screen:

Struts 2 Url Tag Example

Download Source Code
URLDataTagExample.zip

<<Previous <<   || Index ||   >>Next >>

Struts 2 Text Tag Example

The text tag is a generic tag that is used to render a I18n text message. The message must be in a resource bundle with the same name as the action that it is associated with. In practice this means that you should create a properties file in the same package as your Java class with the same name as your class, but with .properties extension.

The text tag is a generic tag that is used to render a I18n text message. Follow one of the three steps:

  • The message must be in a resource bundle with the same name as the action that it is associated with. In practice this means that you should create a properties file in the same package as your Java class with the same name as your class, but with .properties extension.
  • If the named message is not found, then the body of the tag will be used as default message.
  • If no body is used, then the name of the message will be used.

Let us check the following example to understand the usage of text tag:
Create action classes:

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class DataTagAction extends ActionSupport {

 private static final long serialVersionUID = -7744420104547018874L;
 private String name;
 
 public String execute() {
  return SUCCESS;
 }

 public String getName() {
  return name;
 }

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

Create views
Let us have success.jsp with the following content:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<STYLE type="text/css">

b{color: blue;}

</STYLE>
<title>Text Data Tag Struts2 | dineshonjava.com</title>
</head>
<body>
   <h1><span style="background-color: #FFFFcc">Text Data Tags Example!</span></h1>
   <b><s:i18n name="HelloWorldAction">
     <s:text name="name.success"/><br>
     <s:text name="name.xyz">Message doesn't exists</s:text><br>
     <s:text name="name.msg.param">
        <s:param >DINESH</s:param>
   </s:text>
</s:i18n></b>
</body>
</html>

Configuration Files
Let us create a property file with the same name as of your action class package name. So in this case we will create myapp.properties file and keep in the class path:

label.username = User Name
label.submit = Submit
name.success = This is success message
name.msg.param = The param example - param : {0}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="default" extends="struts-default" namespace="/">
        <action name="texttag" class="com.dineshonjava.struts2.action.DataTagAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
 </struts>

web.xml should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2DataTag</display-name>
 <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/texttag.

This will give you following screen:

Struts 2 Text Tag Example

Download Source Code
TextDataTagExample.zip

<<Previous <<   || Index ||   >>Next >>