Posted In: Spring MVC

Struts2+Spring3+Hibernate+jQuery Example

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>Struts2Spring3App</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	<filter>
		<filter-name>struts-prepare</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
	</filter>
	<filter>
		<filter-name>struts-execute</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts-prepare</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>struts-execute</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>
<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
		<property name="url" value="jdbc:hsqldb:hsql://localhost:9001/trupti_db" />
		<property name="username" value="sa" />
		<property name="password" value="" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>employee.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect
				</prop>
				<prop key="current_session_context_class">thread</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

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

	<bean id="myService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="txManager" />
		<property name="target" ref="employeeDao" />
		<property name="transactionAttributes">
			<props>
				<prop key="list">PROPAGATION_REQUIRED,readOnly
				</prop>
				<prop key="insert">PROPAGATION_REQUIRED</prop>
				<prop key="update">PROPAGATION_REQUIRED</prop>
				<prop key="delete">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

	<bean id="employeeDao" class="com.company.springapp.EmployeeDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<bean id="employeeAction" class="com.company.strutsapp.EmployeeAction">
		<property name="employeeDao" ref="employeeDao"></property>
	</bean>
</beans>
<?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" />
	<constant name="struts.objectFactory" value="spring" />
	<include file="employee.xml" />
</struts>
<?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>
	<package name="employee" namespace="/employee" extends="struts-default">
		<action name="list" method="execute" class="employeeAction">
			<result>/WEB-INF/jsp/employee_maintenance.jsp
			</result>
			<result name="input">/WEB-INF/jsp/employee_maintenance.jsp
			</result>
		</action>

		<action name="delete" method="delete" class="employeeAction">
			<result>/WEB-INF/jsp/employee_maintenance.jsp
			</result>
			<result name="input">/WEB-INF/jsp/employee_maintenance.jsp
			</result>
		</action>

		<action name="update" method="update" class="employeeAction">
			<result>/WEB-INF/jsp/employee_maintenance.jsp
			</result>
			<result name="input">/WEB-INF/jsp/employee_maintenance.jsp
			</result>
		</action>

		<action name="insert" method="insert" class="employeeAction">
			<result>/WEB-INF/jsp/employee_maintenance.jsp
			</result>
			<result name="input">/WEB-INF/jsp/employee_maintenance.jsp
			</result>
		</action>

    <action name="listAjax" method="execute" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
    </action>

    <action name="deleteAjax" method="delete" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
    </action>

    <action name="updateAjax" method="update" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
    </action>

    <action name="insertAjax" method="insert" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_jquery.jsp
      </result>
    </action>

    <action name="listDojo" method="execute" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
    </action>

    <action name="deleteDojo" method="delete" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
    </action>

    <action name="updateDojo" method="update" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
    </action>

    <action name="insertDojo" method="insert" class="employeeAction">
      <result>/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
      <result name="input">/WEB-INF/jsp/employee_maintenance_dojo.jsp
      </result>
    </action>
	</package>
</struts>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.company.common">
	<class name="Employee" table="EMPLOYEE_DTL">
		<id name="empId" column="EMP_ID">
			<generator class="sequence">
				<param name="sequence">employee_seq</param>
			</generator>
		</id>
		<property name="firstName" type="string" column="FIRST_NM" />
		<property name="lastName" type="string" column="LAST_NM" />
		<property name="dateofBirth" type="date" column="DT_OF_BIRTH" />
		<property name="hireDate" type="date" column="HIRE_DATE" />
	</class>
</hibernate-mapping>
package com.company.common;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable {
  private static final long serialVersionUID = 1L;
  private Long empId;
  private String firstName;
  private String lastName;
  private Date dateofBirth;
  private Date hireDate;

  public Date getDateofBirth() {
    return dateofBirth;
  }

  public void setDateofBirth(Date dateofBirth) {
    this.dateofBirth = dateofBirth;
  }

  public Long getEmpId() {
    return empId;
  }

  public void setEmpId(Long empId) {
    this.empId = empId;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public Date getHireDate() {
    return hireDate;
  }

  public void setHireDate(Date hireDate) {
    this.hireDate = hireDate;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}
package com.company.strutsapp;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.company.common.Employee;
import com.company.springapp.EmployeeDao;
import com.opensymphony.xwork2.ActionSupport;

public class EmployeeAction extends ActionSupport {
  private final Logger logger = Logger.getLogger(EmployeeAction.class);
  private EmployeeDao employeeDao;
  private List<Employee> employeeList;
  private Employee employee = new Employee();

  public void setEmployeeDao(EmployeeDao employeeDao) {
    logger.debug("setEmployeeDao called Spring injection");
    this.employeeDao = employeeDao;
  }

  public void setEmployee(Employee bean) {
    employee = bean;
  }

  public Employee getEmployee() {
    return employee;
  }

  public List<Employee> getEmployeeList() {
    return employeeList;
  }

  public void setEmployeeList(List<Employee> employeeList) {
    this.employeeList = employeeList;
  }

  public String list() throws Exception {
    logger.debug("called");
    return execute();
  }

  public String insert() throws Exception {
    logger.debug("called. employee bean "+BeanUtils.describe(employee));
    employeeDao.insert(employee);
    return execute();
  }

  public String update() throws Exception {
    logger.debug("called. employee bean "+BeanUtils.describe(employee));
    employeeDao.update(employee);
    return execute();
  }

  public String delete() throws Exception {
    logger.debug("called. employee bean "+BeanUtils.describe(employee));
    employeeDao.delete(employee);
    return execute();
  }

  public String execute() throws Exception {
    logger.debug("called");
    employeeList = employeeDao.list();
    return SUCCESS;
  }
}
package com.company.springapp;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.company.common.Employee;

public class EmployeeDao {
  private HibernateTemplate hbrnTmplt;

  public void setSessionFactory(SessionFactory sessionFactory) {
    this.hbrnTmplt = new HibernateTemplate(sessionFactory);
  }

  public List<Employee> list() {
    List<Employee> list = hbrnTmplt.find("from Employee");
    return list;
  }

  public void insert(Employee newEmployee) {
    hbrnTmplt.save(newEmployee);
  }

  public void update(Employee employee) {
    hbrnTmplt.update(employee);
  }

  public void delete(Employee employee) {
    hbrnTmplt.delete(employee);
  }
}
<%@ page import="com.company.common.Employee"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui-1.8.2.custom.min.js"></script>
<script>
function submitForm(insUpdDel,rownum){
	//alert(rownum);
	if(insUpdDel == 'insertAjax')
	{
		document.frm.elements["employee.firstName"].value =  document.frm.elements['firstNameIsrt'].value;	
		document.frm.elements["employee.lastName"].value =  document.frm.elements['lastNameIsrt'].value;	
		document.frm.elements["employee.dateofBirth"].value =  document.frm.elements['dateofBirthIsrt'].value;	
		document.frm.elements["employee.hireDate"].value =  document.frm.elements['hireDateIsrt'].value;	
	}
	else if(insUpdDel == 'deleteAjax')
	{
		document.frm.elements["employee.empId"].value =  document.frm.elements['employeeList['+rownum+'].empId'].value;	
	}
	else if(insUpdDel == 'updateAjax')
	{
		document.frm.elements["employee.empId"].value =  document.frm.elements['employeeList['+rownum+'].empId'].value;
		document.frm.elements["employee.firstName"].value =  document.frm.elements['employeeList['+rownum+'].firstName'].value;	
		document.frm.elements["employee.lastName"].value =  document.frm.elements['employeeList['+rownum+'].lastName'].value;	
		document.frm.elements["employee.dateofBirth"].value =  document.frm.elements['employeeList['+rownum+'].dateofBirth'].value;	
		document.frm.elements["employee.hireDate"].value =  document.frm.elements['employeeList['+rownum+'].hireDate'].value;	
	}
  
  $.ajax({
    url: "<%=request.getContextPath()%>/employee/"+insUpdDel,
    type: "GET",
    data: $("form").serialize(),
    contentType: "text/html; charset=utf-8",
    dataType: "html",
    cache: false,
    processData: false,
    success: function(data, status, returnData) {
      $("#employee_list_table_id").html($("#employee_list_table_id",returnData.responseText).html());
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
    }
  });
}
</script>
</head>
<body>
<form name='frm'>
<table bgcolor="#EFEFEF" border="1" id="employee_list_table_id">
	<tr>
		<td><Strong>Employee Id</Strong></td>
		<td><Strong>First Name</Strong></td>
		<td><Strong>Last Name</Strong></td>
		<td><Strong>Date of Birth</Strong></td>
		<td><Strong>Hire Date</Strong></td>
		<td><Strong>&nbsp;</Strong></td>
		<td><Strong>&nbsp;</Strong></td>
	</tr>
	<s:if test="employeeList.size > 0">
		<s:iterator value="employeeList" status="row">
			<tr>
				<td><s:textfield name="employeeList[%{#row.index}].empId"
					size="20" theme="simple" disabled="true" /></td>
				<td><s:textfield name="employeeList[%{#row.index}].firstName"
					size="20" theme="simple" /></td>
				<td><s:textfield name="employeeList[%{#row.index}].lastName"
					size="20" theme="simple" /></td>
				<td><s:textfield name="employeeList[%{#row.index}].dateofBirth"
					size='20' theme="simple" /></td>
				<td><s:textfield name="employeeList[%{#row.index}].hireDate"
					size="20" theme="simple" /></td>
				<td><input type='button' value='Delete'
					onclick="submitForm('deleteAjax',${row.index})" /></td>
				<td><input type='button' value='Update'
					onclick="submitForm('updateAjax',${row.index})" /></td>
			</tr>
		</s:iterator>
	</s:if>
	<tr>
		<td>&nbsp;</td>
		<td><input type='text' name='firstNameIsrt' size='20' /></td>
		<td><input type='text' name='lastNameIsrt' size='20' /></td>
		<td><input type='text' name='dateofBirthIsrt' size='20' /></td>
		<td><input type='text' name='hireDateIsrt' size='20' /></td>
		<td><input type='button' value='Insert'
			onclick="submitForm('insertAjax')" /></td>
		<td>&nbsp;</td>
	</tr>
</table>
<input type='hidden' name='employee.empId' /> 
<input type='hidden' name='employee.firstName' /> 
<input type='hidden' name='employee.lastName' />
<input type='hidden' name='employee.dateofBirth' /> 
<input type='hidden' name='employee.hireDate' />
	</form>
</body>
</html>

Tags: , , ,

by , on January 14th, 2017

  • Categories