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>>

Previous
Next

12 Comments

  1. loke November 15, 2013
  2. Dinesh November 18, 2013
  3. Anonymous November 27, 2013
  4. Anonymous January 17, 2014
  5. anil cr February 5, 2014
  6. Dasharath k February 18, 2014
  7. Dasharath k February 18, 2014
  8. Dasharath k February 18, 2014
  9. Amit Kumar March 28, 2019
  10. Amit Kumar March 28, 2019
  11. Amit Kumar March 28, 2019
  12. Dinesh Rajput April 25, 2019