Spring 3 MVC Java Persistence API Tiles Integration Demo
Project Name: SpringJPATiles
web.xml
========================
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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" version="2.4">
<display-name>Spring Example</display-name>
<servlet>
<servlet-name>basicspring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>basicspring</servlet-name>
<url-pattern>*.obj</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
WEB-INF\basicspring-servlet.xml
=======================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.xyz.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<bean id="itemService" class="com.xyz.service.ItemServiceImpl">
<property name="itemDao"><ref local="itemDao" /></property>
</bean>
<bean id="itemDao" class="com.xyz.dao.ItemDaoImpl">
<property name="entityManagerFactory"><ref local="entityManagerFactory"/> </property>
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="dataSource"> <ref local="dataSource" /></property>
</bean>
<!-- Configures the tiles defintions file -->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tile/tiles-def.xml</value>
</list>
</property>
</bean>
<!-- view mappings from localized classpath files -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles.TilesJstlView
</value>
</property>
</bean>
</beans>
src\META-INF\persistence.xml
==================================
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jcrud">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.xyz.dto.Item</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test_db"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<!--
First time comment next line and un comment this line
as the following configuration creates table and inserts data into table, To you have select 1 option
-->
<!--<property name="hibernate.hbm2ddl.auto" value="create"/>
-->
<!--
Second time on time the following configuration updates or selects data from
table. So comment aforesaid line configuration
-->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
WEB-INF\tile\tiles-def.xml
===========================================
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/jsp/baselayout.jsp">
<put name="title" value="" />
<put name="header" value="/jsp/header.jsp" />
<put name="menu" value="/jsp/menu.jsp" />
<put name="body" value="" />
<put name="footer" value="/jsp/footer.jsp" />
</definition>
<definition name="itemhomepage" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/welcome.jsp" />
</definition>
<definition name="searchitempage" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/searchitempage.jsp" />
</definition>
<definition name="invaliditem" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/invaliditem.jsp" />
</definition>
<definition name="item" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/item.jsp" />
</definition>
<definition name="additempage" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/additempage.jsp" />
</definition>
<definition name="insertitem" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/insertitem.jsp" />
</definition>
<definition name="deleteitempage" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/deleteitempage.jsp" />
</definition>
<definition name="deleteitem" extends="baseLayout">
<put name="title" value="Welcome" />
<put name="body" value="/jsp/deleteitem.jsp" />
</definition>
</tiles-definitions>
src\com\xyz\controller\ItemController.java
================================
package com.xyz.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.xyz.dto.Item;
import com.xyz.service.ItemService;
/**
* @author Pedababu M
*
*/
@Controller
@RequestMapping("item")
public class ItemController {
@Autowired
private ItemService itemService;
/**
* @return the itemService
*/
public ItemService getItemService() {
return itemService;
}
/**
* @param itemService the itemService to set
*/
public void setItemService(ItemService itemService) {
this.itemService = itemService;
}
@RequestMapping("/itemhomepage")
public ModelAndView itemHomePage(){
Map myModel = new HashMap();
return new ModelAndView("itemhomepage");
}
@RequestMapping("/searchitempage")
public ModelAndView searchItemPage(){
Map myModel = new HashMap();
return new ModelAndView("searchitempage");
}
@RequestMapping("/searchitem")
public ModelAndView searchItem(@RequestParam("itemCode") String itemCode){
System.out.println("itemCode" + itemCode);
Map myModel = new HashMap();
Item item = getItemService().getItem(Integer.parseInt(itemCode));
if (item == null) {
myModel.put("itemCode", itemCode);
return new ModelAndView("invaliditem","model",myModel);
} else {
myModel.put("item", item);
return new ModelAndView("item","model",myModel);
}
}
@RequestMapping("/additempage")
public ModelAndView addItemPage(){
Map myModel = new HashMap();
return new ModelAndView("additempage");
}
@RequestMapping("/additem")
public ModelAndView addItem(@RequestParam("itemCode") String itemCode,@RequestParam("itemName") String itemName){
System.out.println("itemCode:::" + itemCode + " itemName:::" + itemName);
Map myModel = new HashMap();
Item item = new Item();
item.setItemCode(Integer.parseInt(itemCode));
item.setItemName(itemName);
int insertedItemCode = getItemService().additeam(item);
myModel.put("insertedItemCode", insertedItemCode);
return new ModelAndView("insertitem","model",myModel);
}
@RequestMapping("/deleteitempage")
public ModelAndView deleteItemPage(){
Map myModel = new HashMap();
return new ModelAndView("deleteitempage");
}
@RequestMapping("/deleteitem")
public ModelAndView deleteItem(@RequestParam("itemCode") String itemCode){
System.out.println("itemCode:::" + itemCode);
Map myModel = new HashMap();
getItemService().deleteItem(Integer.parseInt(itemCode));
myModel.put("deletedItemCode", itemCode);
return new ModelAndView("deleteitem","model",myModel);
}
}
src\com\xyz\service\ItemService.java
==================================
package com.xyz.service;
import com.xyz.dto.Item;
/**
* @author Pedababu M
*
*/
public interface ItemService {
int additeam(Item item);
Item getItem(int itemCode);
Item loadItem(int itemCode);
void deleteItem(int itemCode);
}
src\com\xyz\service\ItemServiceImpl.java
===============================
package com.xyz.service;
import com.xyz.dao.ItemDao;
import com.xyz.dto.Item;
/**
* @author Pedababu M
*
*/
public class ItemServiceImpl implements ItemService {
private ItemDao itemDao;
/**
* @return the itemDao
*/
public ItemDao getItemDao() {
return itemDao;
}
/**
* @param itemDao the itemDao to set
*/
public void setItemDao(ItemDao itemDao) {
this.itemDao = itemDao;
System.out.println("setItemDao22222222222"+this.itemDao);
}
/**
* @param item
* @return int
*/
public int additeam(Item item) {
int itemCode = itemDao.additeam(item);
return itemCode;
}
/**
* @param itemCode
* @return
*/
public Item getItem(int itemCode) {
return itemDao.getItem(itemCode);
}
/**
* @param itemCode
* @return
*/
public Item loadItem(int itemCode) {
return itemDao.getItem(itemCode);
}
public void deleteItem(int itemCode) {
itemDao.deleteItem(itemCode);
}
}
src\com\xyz\dao\ItemDao.java
================================
package com.xyz.dao;
import com.xyz.dto.Item;
/**
* @author Pedababu M
*
*/
public interface ItemDao {
int additeam(Item item);
Item getItem(int itemCode);
void deleteItem(int itemCode);
}
src\com\xyz\dao\ItemDaoImpl.java
========================================
package com.xyz.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import com.xyz.dto.Item;
/**
* @author Pedababu M
*
*/
public class ItemDaoImpl implements ItemDao {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
/**
* @return the entityManager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/**
* @param entityManager the entityManager to set
*/
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* @return the entityManagerFactory
*/
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
/**
* @param entityManagerFactory the entityManagerFactory to set
*/
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
entityManager = entityManagerFactory.createEntityManager();
}
Item item = null;
/**
* @param item
* @return
*/
public int additeam(Item item) {
EntityTransaction entityTransaction = getEntityManager().getTransaction();
try {
System.out.println("Before addItem - Dao start");
entityTransaction.begin();
System.out.println("Before addItem - Dao");
entityManager.persist(item);
//item.setItemName("itemName");
entityTransaction.commit();
} catch (Exception exception) {
entityTransaction.rollback();
System.out.println(exception.getMessage());
}
return item.getItemCode();
}
public Item getItem(int itemCode) {
EntityTransaction entityTransaction = getEntityManager().getTransaction();
try {
entityTransaction.begin();
item = (Item) entityManager.find(Item.class, itemCode);
entityTransaction.commit();
} catch (Exception exception) {
entityTransaction.rollback();
System.out.println(exception.getMessage());
}
return item;
}
public void deleteItem(int itemCode) {
EntityTransaction entityTransaction = getEntityManager().getTransaction();
try {
entityTransaction.begin();
Item item = new Item();
item = (Item) entityManager.find(Item.class, itemCode);
//item.setItemCode(itemCode);
entityManager.remove(item);
entityTransaction.commit();
} catch (Exception exception) {
entityTransaction.rollback();
System.out.println(exception.getMessage());
}
}
}
src\com\xyz\dto\Item.java
===============================================
package com.xyz.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.CallbackException;
import org.hibernate.Session;
import org.hibernate.classic.Lifecycle;
import org.hibernate.classic.Validatable;
import org.hibernate.classic.ValidationFailure;
/**
* @author Pedababu M
*
*/
@Entity
@Table(name="Item")
public class Item implements Lifecycle, Validatable{
@Id
@Column(name="item_code")
private int itemCode;
@Column(name="item_name")
private String itemName;
/**
* @return the itemCode
*/
public int getItemCode() {
return itemCode;
}
/**
* @param itemCode the itemCode to set
*/
public void setItemCode(int itemCode) {
this.itemCode = itemCode;
}
/**
* @return the itemName
*/
public String getItemName() {
return itemName;
}
/**
* @param itemName the itemName to set
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Item() {
}
public boolean onDelete(Session arg0) throws CallbackException {
return false;
}
@Override
public void onLoad(Session arg0, Serializable arg1) {
}
@Override
public boolean onSave(Session arg0) throws CallbackException {
System.out.println("Item data is saved");
return false;
}
@Override
public boolean onUpdate(Session arg0) throws CallbackException {
// TODO Auto-generated method stub
return false;
}
public void validate() throws ValidationFailure {
// TODO Auto-generated method stub
System.out.println(itemName + " " + itemName.length());
if (itemName.length()<=0){
throw new ValidationFailure("length must be greater than 0");
}
}
}
index.jsp
==============================
<%@ include file="/jsp/include.jsp" %>
<c:redirect url="/item/itemhomepage.obj" />
jsp\baselayout.jsp
======================================
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insert name="title" ignore="true" /></title>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%" align="center">
<tr height="15%">
<td><tiles:insert name="header" />
</td>
</tr>
<tr height="75%">
<td>
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
<TR>
<td height="80%" width="20%"><tiles:insert name="menu" /></td>
<td width="80%">
<table>
<tr height="100%">
<td>
<tiles:insert name="body" />
</td>
</tr>
</table>
</td>
</TR>
</TABLE>
</td>
</tr>
<tr height="10%">
<td><tiles:insert name="footer" />
</td>
</tr>
</table>
</body>
</html>
jsp\additempage.jsp
========================================
<%@ include file="include.jsp" %>
<%@ taglib uri="/WEB-INF/spring.tld" prefix="spring" %>
<h3>Add Item :</h3>
<form method="post" action="/SpringJPATiles/item/additem.obj">
<br>Enter Item Code:
<input type="text" name="itemCode">
<br>Enter Item Code:
<input type="text" name="itemName">
<input type="submit" value="Add Item">
</form>
jsp\deleteitem.jsp
============================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
Deleted Item Code: <c:out value="${model.deletedItemCode}" /><br/>
jsp\deleteitempage.jsp
================================================
<%@ include file="include.jsp" %>
<%@ taglib uri="/WEB-INF/spring.tld" prefix="spring" %>
<h3>Delete Item:</h3>
<form method="post" action="/SpringJPATiles/item/deleteitem.obj">
<br>Enter Item Code:
<input type="text" name="itemCode">
<input type="submit" value="Delete Item">
</form>
jsp\footer.jsp
=================================================
<%@ page contentType="text/html; charset=UTF-8"%>
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
<TR>
<TD><center>©MPB</center></TD>
</TR>
</TABLE>
jsp\header.jsp
===================================================
<%@ page contentType="text/html; charset=UTF-8"%>
<table width="100%" height="100%" cellspacing="0" cellpadding="0">
<tr height="50%">
<td width="10%">Home</td>
<td width="75%">
</td>
<td width="15%"><span style="float: right">Sign Out</span></td>
</tr>
<TR height="50%">
<TD colspan="3">
<TABLE WIDTH="100%" cellspacing="0" cellpadding="0">
<TR>
<TD bgcolor="#EFEDF1"> </TD>
<TD bgcolor="#EFEDF1" align="right"> </TD>
</TR>
</TABLE>
</TD>
</TR>
</table>
jsp\include.jsp
========================================================
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/fmt.tld" prefix="fmt" %>
jsp\insertitem.jsp
========================================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
Inserted Item Code: <c:out value="${model.insertedItemCode}" /><br/>
jsp\invaliditem.jsp
========================================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
Invalid Item Code: <c:out value="${model.itemCode}" /><br/>
jsp\item.jsp
===========================================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<h2>Item Details</h2>
Item Code: <c:out value="${model.item.itemCode}" /><br/>
Item Name: <c:out value="${model.item.itemName}" /><br/>
jsp\itemhomepage.jsp
===========================================================
<%@ page session="false" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/fmt.tld" prefix="fmt" %>
<h3>Item Operations</h3>
\jsp\menu.jsp
=============================================================
<%@ page contentType="text/html; charset=UTF-8"%>
<center>Left Navigation</center><br/><br/><br/>
<a href="/SpringJPATiles/item/additempage.obj">Add Item</a><br/>
<a href="/SpringJPATiles/item/searchitempage.obj">Search Item</a><br/>
<a href="/SpringJPATiles/item/deleteitempage.obj">Delete Item</a><br/>
<!--
<s:a href="customer-form">Customer</s:a>
-->
jsp\searchitempage.jsp
=============================================================
<%@ include file="include.jsp" %>
<%@ taglib uri="/WEB-INF/spring.tld" prefix="spring" %>
<h3>Item Search:</h3>
<form method="post" action="/SpringJPATiles/item/searchitem.obj">
<br>Enter Item Code:
<input type="text" name="itemCode">
<input type="submit" value="Search Item">
</form>
jsp\welcome.jsp
===========================================================
<%@ page contentType="text/html; charset=UTF-8"%>
<h2>Welcome to Spring MVC JPA Tiles Demo</h2>
No comments:
Post a Comment