miércoles, 30 de marzo de 2016

Spring Crud

Spring CRUD Example using One to One Mapping of Two Tables

In this example show how to write a simple web based application with CRUD operation using Spring3 MVC Framwork with Hibernate3 using Annotation handling two database tables(Category & Publication), 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:

Step 1: Create a Database DAVDB on MySql Database and also we create Category and Publication tables on this database.

Category Table
  1. CREATE TABLE `category` (  
  2.   `categoryId` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `categoryName` varchar(255) DEFAULT NULL,  
  4.   PRIMARY KEY (`categoryId`)  
  5. )   

Publication Table
  1. CREATE TABLE `publication` (  
  2.   `pubId` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `content` varchar(255) DEFAULT NULL,  
  4.   `Title` varchar(255) DEFAULT NULL,  
  5.   `categoryId` int(11) DEFAULT NULL,  
  6.   PRIMARY KEY (`pubId`),  
  7.   KEY `FK23254A0CAF274936` (`categoryId`),  
  8.   CONSTRAINT `FK23254A0CAF274936` FOREIGN KEY (`categoryId`) REFERENCES `category` (`categoryId`)  
  9. )  
Step 2: Create a database.properties for database configuration information in the resources folder under src folder in the created project.
  1. database.driver=com.mysql.jdbc.Driver    
  2.     database.url=jdbc:mysql://localhost:3306/DAVDB    
  3.     database.user=root    
  4.     database.password=root    
  5.     hibernate.dialect=org.hibernate.dialect.MySQLDialect    
  6.     hibernate.show_sql=true    
  7.     hibernate.hbm2ddl.auto=create  

Step 3: Create a Dynamic Web Project with a name elhumeante and create packages com.dineshonjava.controller, com.dineshonjava.bean, com.dineshonjava.dao, com.dineshonjava.service, com.dineshonjava.model 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.


Step 5: Create a Java class CategoryController, PublicationController, CategoryBean, PublicationBean, CategoryDao, CategoryDaoImpl, PublicationDao, PublicationDaoImpl, CategoryService, CategoryServiceImpl, PublicationService, PublicationServiceImpl under the respective packages..

Step 6: Create Spring configuration files web.xml and sdnext-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 addCategory.jsp and addPublication.jsp under this sub-folder.

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

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(CategoryDao, PublicationDao). 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 CategoryService, PublicationService.

CategoryBean.java
  1. package com.dineshonjava.bean;  
  2.   
  3. import javax.persistence.Column;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.GenerationType;  
  7. import javax.persistence.Id;  
  8. import javax.persistence.Table;  
  9.   
  10. @Entity  
  11. @Table(name="Category")  
  12. public class CategoryBean {  
  13.    
  14.  @Id  
  15.  @Column(name="categoryId")  
  16.  @GeneratedValue(strategy=GenerationType.AUTO)  
  17.  private Integer categoryId;  
  18.    
  19.  @Column(name="categoryName")  
  20.  private String categoryName;  
  21.   
  22.  public Integer getCategoryId() {  
  23.   return categoryId;  
  24.  }  
  25.   
  26.  public void setCategoryId(Integer categoryId) {  
  27.   this.categoryId = categoryId;  
  28.  }  
  29.   
  30.  public String getCategoryName() {  
  31.   return categoryName;  
  32.  }  
  33.   
  34.  public void setCategoryName(String categoryName) {  
  35.   this.categoryName = categoryName;  
  36.  }  
  37. }  

PublicationBean.java

  1. package com.dineshonjava.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.OneToOne;  
  12. import javax.persistence.Table;  
  13.   
  14. @Entity  
  15. @Table(name="Publication")  
  16. public class PublicationBean implements Serializable{  
  17.   
  18.  private static final long serialVersionUID = 1L;  
  19.    
  20.  @Id  
  21.  @GeneratedValue(strategy=GenerationType.AUTO)  
  22.  @Column(name = "pubId")  
  23.  private Integer pubId;  
  24.    
  25.  @Column(name="Title")  
  26.  private String pubTitle;  
  27.    
  28.  @OneToOne  
  29.         @JoinColumn(name="categoryId")  
  30.  private CategoryBean category;  
  31.    
  32.  @Column(name="content")  
  33.  private String pubContent;  
  34.    
  35.  public Integer getPubId() {  
  36.   return pubId;  
  37.  }  
  38.  public void setPubId(Integer pubId) {  
  39.   this.pubId = pubId;  
  40.  }  
  41.  public String getPubTitle() {  
  42.   return pubTitle;  
  43.  }  
  44.  public void setPubTitle(String pubTitle) {  
  45.   this.pubTitle = pubTitle;  
  46.  }  
  47.  public String getPubContent() {  
  48.   return pubContent;  
  49.  }  
  50.  public CategoryBean getCategory() {  
  51.   return category;  
  52.  }  
  53.  public void setCategory(CategoryBean category) {  
  54.   this.category = category;  
  55.  }  
  56.  public void setPubContent(String pubContent) {  
  57.   this.pubContent = pubContent;  
  58.  }  
  59. }  

CategoryDao.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.bean.CategoryBean;  
  6.   
  7. public interface CategoryDao {  
  8.    
  9.  public void addCategory(CategoryBean categoryBean);  
  10.    
  11.  public List<CategoryBean> getCategories();  
  12.    
  13.  public CategoryBean getCategory(int categoryId);  
  14.    
  15.  public void deleteCategory(int categoryId);  
  16. }  

PublicationDao.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.bean.PublicationBean;  
  6.   
  7. public interface PublicationDao {  
  8.    
  9.  public void addPublication(PublicationBean publicationBean);  
  10.    
  11.  public List<PublicationBean> getPublications();  
  12.    
  13.  public PublicationBean getPublication(int pubId);  
  14.    
  15.  public void deletePublication(int pubId);  
  16. }  

CategoryDaoImpl.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.dineshonjava.bean.CategoryBean;  
  10.   
  11. /** 
  12.  * @author Dinesh Rajput 
  13.  * 
  14.  */  
  15.   
  16. @Repository("categoryDao")  
  17. public class CategoryDaoImpl implements CategoryDao {  
  18.    
  19.  @Autowired  
  20.  private SessionFactory sessionFactory;  
  21.    
  22.  @Override  
  23.  public void addCategory(CategoryBean categoryBean) {  
  24.   sessionFactory.getCurrentSession().saveOrUpdate(categoryBean);  
  25.  }  
  26.   
  27.  @SuppressWarnings("unchecked")  
  28.  @Override  
  29.  public List<CategoryBean> getCategories() {  
  30.   return (List<CategoryBean>) sessionFactory.getCurrentSession().createCriteria(CategoryBean.class).list();  
  31.  }  
  32.   
  33.  @Override  
  34.  public CategoryBean getCategory(int categoryId) {  
  35.   return (CategoryBean) sessionFactory.getCurrentSession().get(CategoryBean.class, categoryId);  
  36.  }  
  37.   
  38.  @Override  
  39.  public void deleteCategory(int categoryId) {  
  40.   sessionFactory.getCurrentSession().createQuery("DELETE FROM category WHERE categoryId = "+categoryId).executeUpdate();  
  41.  }  
  42.   
  43. }  

PublicationDaoImpl.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.dineshonjava.bean.PublicationBean;  
  10.   
  11. /** 
  12.  * @author Dinesh Rajput 
  13.  * 
  14.  */  
  15.   
  16. @Repository("publicationDao")  
  17. public class PublicationDaoImpl implements PublicationDao {  
  18.   
  19.  @Autowired  
  20.  private SessionFactory sessionFactory;  
  21.    
  22.  public void addPublication(PublicationBean publicationBean) {  
  23.   sessionFactory.getCurrentSession().saveOrUpdate(publicationBean);  
  24.  }  
  25.   
  26.  @SuppressWarnings("unchecked")  
  27.  @Override  
  28.  public List<PublicationBean> getPublications() {  
  29.   return (List<PublicationBean>) sessionFactory.getCurrentSession().createCriteria(PublicationBean.class).list();  
  30.  }  
  31.   
  32.  @Override  
  33.  public PublicationBean getPublication(int pubId) {  
  34.   return (PublicationBean) sessionFactory.getCurrentSession().get(PublicationBean.class, pubId);  
  35.  }  
  36.   
  37.  @Override  
  38.  public void deletePublication(int pubId) {  
  39.   sessionFactory.getCurrentSession().createQuery("DELETE FROM Publication WHERE pubId = "+pubId).executeUpdate();  
  40.  }  
  41.   
  42. }  

CategoryService.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.bean.CategoryBean;  
  6.   
  7. public interface CategoryService {  
  8.    
  9.  public void addCategory(CategoryBean categoryBean);  
  10.    
  11.  public List<CategoryBean> getCategories();  
  12.    
  13.  public CategoryBean getCategory(int categoryId);  
  14.    
  15.  public void deleteCategory(int categoryId);  
  16.   
  17. }  
CategoryServiceImpl.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.dineshonjava.bean.CategoryBean;  
  11. import com.dineshonjava.dao.CategoryDao;  
  12.   
  13. /** 
  14.  * @author Dinesh Rajput 
  15.  * 
  16.  */  
  17.   
  18. @Service("categoryService")  
  19. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)  
  20. public class CategoryServiceImpl implements CategoryService {  
  21.    
  22.  @Autowired  
  23.  private CategoryDao categoryDao;  
  24.    
  25.  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
  26.  public void addCategory(CategoryBean categoryBean) {  
  27.   categoryDao.addCategory(categoryBean);  
  28.  }  
  29.   
  30.  @Override  
  31.  public List<CategoryBean> getCategories() {  
  32.   return categoryDao.getCategories();  
  33.  }  
  34.   
  35.  @Override  
  36.  public CategoryBean getCategory(int categoryId) {  
  37.   return categoryDao.getCategory(categoryId);  
  38.  }  
  39.   
  40.  @Override  
  41.  public void deleteCategory(int categoryId) {  
  42.   categoryDao.deleteCategory(categoryId);  
  43.  }  
  44.   
  45. }  
PublicationService.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.bean.PublicationBean;  
  6.   
  7. public interface PublicationService {  
  8.    
  9.  public void addPublication(PublicationBean publicationBean);  
  10.    
  11.  public List<PublicationBean> getPublications();  
  12.    
  13.  public PublicationBean getPublication(int pubId);  
  14.    
  15.  public void deletePublication(int pubId);  
  16. }  
PublicationServiceImpl.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.dineshonjava.bean.PublicationBean;  
  11. import com.dineshonjava.dao.PublicationDao;  
  12.   
  13. /** 
  14.  * @author Dinesh Rajput 
  15.  * 
  16.  */  
  17. @Service("publicationService")  
  18. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)  
  19. public class PublicationServiceImpl implements PublicationService {  
  20.   
  21.  @Autowired  
  22.  private PublicationDao publicationDao;  
  23.    
  24.  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
  25.  public void addPublication(PublicationBean publicationBean) {  
  26.   publicationDao.addPublication(publicationBean);  
  27.  }  
  28.   
  29.  public List<PublicationBean> getPublications() {  
  30.   return publicationDao.getPublications();  
  31.  }  
  32.   
  33.  @Override  
  34.  public PublicationBean getPublication(int pubId) {  
  35.   return publicationDao.getPublication(pubId);  
  36.  }  
  37.   
  38.  @Override  
  39.  public void deletePublication(int pubId) {  
  40.   publicationDao.deletePublication(pubId);  
  41.  }  
  42.   
  43. }  

CategoryController.java
  1. package com.dineshonjava.controller;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.validation.BindingResult;  
  10. import org.springframework.web.bind.annotation.ModelAttribute;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.servlet.ModelAndView;  
  14.   
  15. import com.dineshonjava.bean.CategoryBean;  
  16. import com.dineshonjava.service.CategoryService;  
  17.   
  18. /** 
  19.  * @author Dinesh Rajput 
  20.  * 
  21.  */  
  22. @Controller  
  23. public class CategoryController {  
  24.    
  25.  @Autowired  
  26.  private CategoryService categoryService;  
  27.    
  28.  @RequestMapping(value = "/saveCategory", method = RequestMethod.POST)  
  29.  public ModelAndView saveEmployee(@ModelAttribute("command") CategoryBean category,   
  30.    BindingResult result) {  
  31.   categoryService.addCategory(category);  
  32.   return new ModelAndView("redirect:/addCategory.html");  
  33.  }  
  34.    
  35.  @RequestMapping(value = "/addCategory", method = RequestMethod.GET)  
  36.  public ModelAndView addCategory(@ModelAttribute("command")  CategoryBean category,  
  37.    BindingResult result) {  
  38.   Map<String, Object> model = new HashMap<String, Object>();  
  39.   model.put("categories",  categoryService.getCategories());  
  40.   return new ModelAndView("addCategory", model);  
  41.  }  
  42.    
  43.  @RequestMapping(value = "/deleteCategory", method = RequestMethod.GET)  
  44.  public ModelAndView deleteCategory(@ModelAttribute("command")  CategoryBean category,  
  45.    BindingResult result) {  
  46.   categoryService.deleteCategory(category.getCategoryId());  
  47.   Map<String, Object> model = new HashMap<String, Object>();  
  48.   model.put("categories",  categoryService.getCategories());  
  49.   return new ModelAndView("addCategory", model);  
  50.  }  
  51.    
  52.  @RequestMapping(value = "/editCategory", method = RequestMethod.GET)  
  53.  public ModelAndView editCategory(@ModelAttribute("command")  CategoryBean category,  
  54.    BindingResult result) {  
  55.   Map<String, Object> model = new HashMap<String, Object>();  
  56.   model.put("category",  categoryService.getCategory(category.getCategoryId()));  
  57.   model.put("categories",  categoryService.getCategories());  
  58.   return new ModelAndView("addCategory", model);  
  59.  }  
  60.    
  61.  @RequestMapping(value="/categories", method = RequestMethod.GET)  
  62.  public List<CategoryBean> getCategories() {  
  63.   return categoryService.getCategories();  
  64.  }  
  65. }  
PublicationController.java
  1. package com.dineshonjava.controller;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.validation.BindingResult;  
  10. import org.springframework.web.bind.annotation.ModelAttribute;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.servlet.ModelAndView;  
  14.   
  15. import com.dineshonjava.bean.PublicationBean;  
  16. import com.dineshonjava.service.CategoryService;  
  17. import com.dineshonjava.service.PublicationService;  
  18.   
  19. @Controller  
  20. public class PublicationController {  
  21.    
  22.  @Autowired  
  23.  private PublicationService publicationService;  
  24.    
  25.  @Autowired  
  26.  private CategoryService categoryService;  
  27.    
  28.  @RequestMapping(value = "/savePublication", method = RequestMethod.POST)  
  29.  public ModelAndView saveEmployee(@ModelAttribute("command") PublicationBean publication,   
  30.    BindingResult result) {  
  31.   publicationService.addPublication(publication);  
  32.   return new ModelAndView("redirect:/addPublication.html");  
  33.  }  
  34.    
  35.  @RequestMapping(value = "/addPublication", method = RequestMethod.GET)  
  36.  public ModelAndView addPublication(@ModelAttribute("command")  PublicationBean publication,  
  37.    BindingResult result) {  
  38.   Map<String, Object> model = new HashMap<String, Object>();  
  39.   model.put("publications",  publicationService.getPublications());  
  40.   model.put("categories",  categoryService.getCategories());  
  41.   return new ModelAndView("addPublication", model);  
  42.  }  
  43.    
  44.  @RequestMapping(value = "/deletePublication", method = RequestMethod.GET)  
  45.  public ModelAndView deletePublication(@ModelAttribute("command")  PublicationBean publication,  
  46.    BindingResult result) {  
  47.   publicationService.deletePublication(publication.getPubId());  
  48.   Map<String, Object> model = new HashMap<String, Object>();  
  49.   model.put("publications",  publicationService.getPublications());  
  50.   model.put("categories",  categoryService.getCategories());  
  51.   return new ModelAndView("addPublication", model);  
  52.  }  
  53.    
  54.  @RequestMapping(value = "/editPublication", method = RequestMethod.GET)  
  55.  public ModelAndView editPublication(@ModelAttribute("command")  PublicationBean publication,  
  56.    BindingResult result) {  
  57.   Map<String, Object> model = new HashMap<String, Object>();  
  58.   model.put("publication",  publicationService.getPublication(publication.getPubId()));  
  59.   model.put("publications",  publicationService.getPublications());  
  60.   model.put("categories",  categoryService.getCategories());  
  61.   return new ModelAndView("addPublication", model);  
  62.  }  
  63.    
  64.  @RequestMapping(value="/publications", method = RequestMethod.GET)  
  65.  public List<PublicationBean> getPublications() {  
  66.   return publicationService.getPublications();  
  67.  }  
  68. }  

Spring Web configuration file web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  5.   
  6.  <servlet>  
  7.   <servlet-name>sdnext</servlet-name>  
  8.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  9.   <init-param>  
  10.             <param-name>contextConfigLocation</param-name>  
  11.             <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>  
  12.         </init-param>  
  13.         <load-on-startup>1</load-on-startup>  
  14.  </servlet>  
  15.   
  16.  <servlet-mapping>  
  17.   <servlet-name>sdnext</servlet-name>  
  18.   <url-pattern>*.html</url-pattern>  
  19.  </servlet-mapping>  
  20.   
  21.  <welcome-file-list>  
  22.   <welcome-file>  
  23.    addCategory.html  
  24.   </welcome-file>  
  25.  </welcome-file-list>  
  26. </web-app>  

Spring Web configuration file sdnext-servlet.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.  xmlns:context="http://www.springframework.org/schema/context"  
  5.  xmlns:tx="http://www.springframework.org/schema/tx"  
  6.  xsi:schemaLocation="  
  7. http://www.springframework.org/schema/beans  
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9. http://www.springframework.org/schema/context  
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11. http://www.springframework.org/schema/tx  
  12. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  13.   
  14.  <context:property-placeholder location="classpath:resources/database.properties" />  
  15.  <context:component-scan base-package="com.dineshonjava" />  
  16.   
  17.  <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>  
  18.   
  19.  <bean id="jspViewResolver"  
  20.   class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  21.   <property name="viewClass"  
  22.    value="org.springframework.web.servlet.view.JstlView" />  
  23.   <property name="prefix" value="/WEB-INF/view/" />  
  24.   <property name="suffix" value=".jsp" />  
  25.  </bean>  
  26.   
  27.  <bean id="dataSource"  
  28.   class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  29.   <property name="driverClassName" value="${database.driver}" />  
  30.   <property name="url" value="${database.url}" />  
  31.   <property name="username" value="${database.user}" />  
  32.   <property name="password" value="${database.password}" />  
  33.  </bean>  
  34.   
  35.  <bean id="sessionFactory"  
  36.   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  37.   <property name="dataSource" ref="dataSource" />  
  38.   <property name="annotatedClasses">  
  39.    <list>  
  40.     <value>com.dineshonjava.bean.CategoryBean</value>  
  41.     <value>com.dineshonjava.bean.PublicationBean</value>  
  42.    </list>  
  43.   </property>  
  44.   <property name="hibernateProperties">  
  45.    <props>  
  46.     <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  47.     <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  48.     <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>      
  49.    </props>  
  50.   </property>  
  51.  </bean>  
  52.   
  53.  <bean id="hibernateTransactionManager"  
  54.   class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  55.   <property name="sessionFactory" ref="sessionFactory" />  
  56.  </bean>  
  57. </beans>  

addCategory.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7.  <head>  
  8.   <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  9.   <title>Spring MVC Form Handling</title>  
  10.  </head>  
  11.  <body><center>  
  12.   <h2>Create New Category</h2>  
  13.   <form:form method="POST" action="/elhumeante/saveCategory.html">  
  14.       <table>  
  15.        <tr>  
  16.            <td><form:label path="categoryId">Category ID:</form:label></td>  
  17.            <td><form:input path="categoryId" readonly="true"/></td>  
  18.        </tr>  
  19.        <tr>  
  20.            <td><form:label path="categoryName">Category Name:</form:label></td>  
  21.            <td><form:input path="categoryName" value="${category.categoryName}"/></td>  
  22.        </tr>  
  23.          
  24.        <tr>  
  25.        <tr>  
  26.         <td>&nbsp;</td>  
  27.          <td><input type="submit" value="SAVE"/></td>  
  28.          </tr>  
  29.    </table>   
  30.   </form:form>  
  31.     
  32.   
  33.   <c:if test="${!empty categories}">  
  34.  <table align="center" border="1">  
  35.   <tr>  
  36.    <th>Category ID</th>  
  37.    <th>Category Name</th>  
  38.    <th>Options</th>  
  39.   </tr>  
  40.   
  41.   <c:forEach items="${categories}" var="category">  
  42.    <tr>  
  43.     <td><c:out value="${category.categoryId}"/></td>  
  44.     <td><c:out value="${category.categoryName}"/></td>  
  45.     <td align="center"><a href="editCategory.html?categoryId=${category.categoryId}">Edit</a> | <a href="deleteCategory.html?categoryId=${category.categoryId}">Delete</a></td>  
  46.    </tr>  
  47.   </c:forEach>  
  48.  </table>  
  49. </c:if>  
  50. <h2><a href="addPublication.html">Adding Publication</a></h2>  
  51. </center>  
  52.  </body>  
  53. </html>  

addPublication.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7.  <head>  
  8.   <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  9.   <title>Spring MVC Form Handling</title>  
  10.  </head>  
  11.  <body>  
  12.  <center>  
  13.   <h2>Create New Publication</h2>  
  14.   <form:form method="POST" action="/elhumeante/savePublication.html">  
  15.       <table>  
  16.        <tr>  
  17.            <td><form:label path="pubId">Publication ID:</form:label></td>  
  18.            <td><form:input path="pubId" value="${publication.pubId}" readonly="true"/></td>  
  19.        </tr>  
  20.        <tr>  
  21.            <td><form:label path="pubTitle">Publication Title:</form:label></td>  
  22.            <td><form:input path="pubTitle" value="${publication.pubTitle}"/></td>  
  23.        </tr>  
  24.          
  25.       <tr>  
  26.         <td>  
  27.          <form:label path="category.categoryId">Publication Type:</form:label>  
  28.         </td>  
  29.         <td>  
  30.          <form:select path="category.categoryId" cssStyle="width: 150px;">      
  31.        <option value="-1">Select a type</option>  
  32.        <c:forEach items="${categories}" var="category">  
  33.         <option value="${category.categoryId}">${category.categoryName}</option>  
  34.        </c:forEach>  
  35.       </form:select>  
  36.      </td>  
  37.        </tr>  
  38.        <tr>  
  39.            <td><form:label path="pubContent">Publication Content:</form:label></td>  
  40.            <td><form:textarea path="pubContent" value="${publication.pubContent}" cssStyle="width: 150px;"/></td>  
  41.        </tr>  
  42.        <tr>  
  43.          <td>&nbsp;</td>  
  44.          <td><input type="submit" value="SAVE"/></td>  
  45.         </tr>  
  46.    </table>   
  47.   </form:form>  
  48.     
  49.   
  50.   <c:if test="${!empty publications}">  
  51.  <table align="center" border="1">  
  52.   <tr>  
  53.    <th>ID</th>  
  54.    <th>Title</th>  
  55.    <th>Type</th>  
  56.    <th>Content</th>  
  57.    <th>Options</th>  
  58.   </tr>  
  59.   
  60.   <c:forEach items="${publications}" var="publication">  
  61.    <tr>  
  62.     <td><c:out value="${publication.pubId}"/></td>  
  63.     <td><c:out value="${publication.pubTitle}"/></td>  
  64.     <td><c:out value="${publication.category.categoryName}"/></td>  
  65.     <td><c:out value="${publication.pubContent}"/></td>  
  66.     <td align="center"><a href="editPublication.html?pubId=${publication.pubId}">Edit</a> |  
  67. <a href="deletePublication.html?pubId=${publication.pubId}">Delete</a></td>  
  68.    </tr>  
  69.   </c:forEach>  
  70.  </table>  
  71. </c:if>  
  72. <h2><a href="addCategory.html">Adding Category</a></h2>  
  73. </center>  
  74.  </body>  
  75. </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 elhumeante.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/elhumeante/ and you should see the following result if everything is fine with your Spring Web Application:

Create category:


Create Publication: 



Download Source code
elhumeante.zip

No hay comentarios:

Publicar un comentario