Friday, May 2, 2014

Java Web Application + Spring + Hibernate + Maven

Simple Java Web Application using DI & ORM framework on top of Maven


Problem Statement

Create a simple Java web application where a user can enter comments on a simple web page. The comments should be persisted to a MySQL database and displayed on the screen. The comments can be anonymous (no login/username required)


Database Script



 -- --------------------------------------------------------  
 -- Host:             127.0.0.1  
 -- Server version:        5.5.28 - MySQL Community Server (GPL)  
 -- Server OS:          Win64  
 -- HeidiSQL version:       7.0.0.4053  
 -- Date/time:          2014-04-29 21:18:39  
 -- --------------------------------------------------------  
 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;  
 /*!40101 SET NAMES utf8 */;  
 /*!40014 SET FOREIGN_KEY_CHECKS=0 */;  
 -- Dumping database structure for midas-test  
 CREATE DATABASE IF NOT EXISTS `midas-test` /*!40100 DEFAULT CHARACTER SET utf8 */;  
 USE `midas-test`;  
 -- Dumping structure for table midas-test.comments  
 CREATE TABLE IF NOT EXISTS `comments` (  
  `id` bigint(20) NOT NULL AUTO_INCREMENT,  
  `comment` mediumtext NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
 -- Dumping data for table midas-test.comments: ~0 rows (approximately)  
 /*!40000 ALTER TABLE `comments` DISABLE KEYS */;  
 /*!40000 ALTER TABLE `comments` ENABLE KEYS */;  
 /*!40014 SET FOREIGN_KEY_CHECKS=1 */;  
 /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;  


Project Template

Create a Spring Project using Spring Tool or eclipse or maven.
The project structure will be like below-




















Controller Class


 import java.util.Locale;  
 import java.util.Map;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.ui.Model;  
 import org.springframework.validation.BindingResult;  
 import org.springframework.validation.annotation.Validated;  
 import org.springframework.web.bind.annotation.ModelAttribute;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 import com.test.comment.db.Comment;  
 import com.test.comment.model.CommentModel;  
 import com.test.comment.service.CommentService;  
 /**  
  * Handles requests for the application home page.  
  */  
 @Controller  
 public class HomeController {  
      private static final Logger logger = LoggerFactory  
                .getLogger(HomeController.class.getName());  
      @Autowired  
      private CommentService commentService;  
      // @Autowired  
      // private CommentValidator commentValidator;  
      /**  
       * Simply selects the home view to render by returning its name.  
       */  
      @RequestMapping(value = "/")  
      public String home(@ModelAttribute("comment") @Validated Comment cto,  
                Locale locale, Model model) {  
           return "views/login";  
      }  
      @RequestMapping(value = "/index", method = RequestMethod.GET)  
      public String loginPage(Locale locale, Model model) {  
           return "views/login";  
      }  
      @RequestMapping(value = "/user")  
      public String login(@ModelAttribute("comment") Comment cto,  
                @Validated CommentModel comments, Model model) {  
           return "views/user";  
      }  
      @RequestMapping("/list")  
      public String listComments(Map<String, Object> map) {  
           map.put("comment", new Comment());  
           map.put("commentList", commentService.listComment());  
           return "views/login";  
      }  
      @RequestMapping(value = "/add", method = RequestMethod.POST)  
      public String addComment(@ModelAttribute("comment") @Validated Comment cto,  
                BindingResult result, Model model) {  
           if (result.hasErrors()) {  
                logger.info("Returning empSave.jsp page");  
                return "";  
           }  
           String commentValue = cto.getCommentValue().trim();  
           if (commentValue != null && commentValue.length() > 0) {  
                commentService.addComment(cto);  
           }  
           return "redirect:/list";  
      }  
 }  

Spring Login page


 <%@ page language="java" contentType="text/html; charset=UTF-8"  
   pageEncoding="UTF-8"%>  
 <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>  
 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <style>  
 .error {  
      color: #ff0000;  
 }  
 .errorblock {  
      color: #000;  
      background-color: #ffEEEE;  
      border: 3px solid #ff0000;  
      padding: 8px;  
      margin: 16px;  
 }  
 </style>  
 <title>Login Page</title>  
 </head>  
 <body>  
 <form:form method="post" action="add" commandName="comment">  
      <form:errors path="*" cssClass="errorblock" element="div" />  
      <tr>  
     <td><form:label path="commentValue"><spring:message code="label.commentValue"/></form:label></td>  
     <td><form:errors path="commentValue" cssClass="error" /></td>  
   </tr>   
   <tr>  
   <td><form:textarea path="commentValue" /></td>   
   </tr>  
   <tr>  
     <td colspan="2">  
     </td>  
   </tr>  
  <table>  
  </table><input type="submit" value='<spring:message code="label.addComment"/>'>  
 </form:form>  
 <h3><br><br><br><br><br><br>  LIST OF COMMENTS</h3>  
 <c:if test="${!empty commentList}">  
 <table class="data">  
 <tr>  
   <th>Comment</th>  
 </tr>  
 <c:forEach items="${commentList}" var="comment">  
   <tr>  
     <td>${comment.commentValue}</td>  
   </tr>  
 </c:forEach>  
 </table>  
 </c:if>  
 </body>  
 </html>  



Spring pom.xml


 <?xml version="1.0" encoding="UTF-8"?>  
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
      <modelVersion>4.0.0</modelVersion>  
      <groupId>com.journaldev</groupId>  
      <artifactId>CommentDemo</artifactId>  
      <name>CommentDemo</name>  
      <packaging>war</packaging>  
      <version>1</version>  
      <properties>  
           <java-version>1.7</java-version>  
           <org.springframework-version>4.0.3.RELEASE</org.springframework-version>  
           <org.springframework.version>3.2.0.RELEASE</org.springframework.version>  
           <org.aspectj-version>1.7.4</org.aspectj-version>  
           <org.slf4j-version>1.7.5</org.slf4j-version>  
           <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
           <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
      </properties>  
      <dependencies>  
           <!-- Spring -->  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-context</artifactId>  
                <version>${org.springframework-version}</version>  
                <exclusions>  
                     <!-- Exclude Commons Logging in favor of SLF4j -->  
                     <exclusion>  
                          <groupId>commons-logging</groupId>  
                          <artifactId>commons-logging</artifactId>  
                     </exclusion>  
                </exclusions>  
           </dependency>  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-webmvc</artifactId>  
                <version>${org.springframework-version}</version>  
           </dependency>  
           <!-- AspectJ -->  
           <dependency>  
                <groupId>org.aspectj</groupId>  
                <artifactId>aspectjrt</artifactId>  
                <version>${org.aspectj-version}</version>  
           </dependency>  
           <!-- Logging -->  
           <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-api</artifactId>  
                <version>${org.slf4j-version}</version>  
           </dependency>  
           <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>jcl-over-slf4j</artifactId>  
                <version>${org.slf4j-version}</version>  
                <scope>runtime</scope>  
           </dependency>  
           <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-log4j12</artifactId>  
                <version>${org.slf4j-version}</version>  
                <scope>runtime</scope>  
           </dependency>  
           <dependency>  
                <groupId>log4j</groupId>  
                <artifactId>log4j</artifactId>  
                <version>1.2.15</version>  
                <exclusions>  
                     <exclusion>  
                          <groupId>javax.mail</groupId>  
                          <artifactId>mail</artifactId>  
                     </exclusion>  
                     <exclusion>  
                          <groupId>javax.jms</groupId>  
                          <artifactId>jms</artifactId>  
                     </exclusion>  
                     <exclusion>  
                          <groupId>com.sun.jdmk</groupId>  
                          <artifactId>jmxtools</artifactId>  
                     </exclusion>  
                     <exclusion>  
                          <groupId>com.sun.jmx</groupId>  
                          <artifactId>jmxri</artifactId>  
                     </exclusion>  
                </exclusions>  
                <scope>runtime</scope>  
           </dependency>  
           <!-- @Inject -->  
           <dependency>  
                <groupId>javax.inject</groupId>  
                <artifactId>javax.inject</artifactId>  
                <version>1</version>  
           </dependency>  
           <!-- Servlet -->  
           <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>servlet-api</artifactId>  
                <version>2.5</version>  
                <scope>provided</scope>  
           </dependency>  
           <dependency>  
                <groupId>javax.servlet.jsp</groupId>  
                <artifactId>jsp-api</artifactId>  
                <version>2.1</version>  
                <scope>provided</scope>  
           </dependency>  
           <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>jstl</artifactId>  
                <version>1.2</version>  
           </dependency>  
           <!-- HIBERNATE -->  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-jdbc</artifactId>  
                <version>${org.springframework-version}</version>  
           </dependency>  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-orm</artifactId>  
                <version>${org.springframework-version}</version>  
           </dependency>  
           <!-- Hibernate framework -->  
           <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-core</artifactId>  
                <version>4.3.4.Final</version>  
           </dependency>  
           <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-log4j12</artifactId>  
                <version>1.6.1</version>  
           </dependency>  
           <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-c3p0</artifactId>  
                <version>4.3.4.Final</version>  
           </dependency>  
           <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-entitymanager</artifactId>  
                <version>4.3.4.Final</version>  
           </dependency>  
           <!-- <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-annotations</artifactId>  
                <version>3.5.6-Final</version>  
           </dependency>  
           <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-commons-annotations</artifactId>  
                <version>3.2.0.Final</version>  
           </dependency>  
  -->  
           <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-ehcache</artifactId>  
                <version>4.3.4.Final</version>  
           </dependency>  
           <!-- <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId>   
                <version>5.1.30</version> </dependency> <dependency> <groupId>commons-dbcp</groupId>   
                <artifactId>commons-dbcp</artifactId> <version>20030825.184428</version>   
                </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId>   
                <version>20030825.183949</version> </dependency> -->  
           <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>5.1.9</version>  
           </dependency>  
           <dependency>  
                <groupId>dom4j</groupId>  
                <artifactId>dom4j</artifactId>  
                <version>1.6.1</version>  
           </dependency>  
           <dependency>  
                <groupId>commons-logging</groupId>  
                <artifactId>commons-logging</artifactId>  
                <version>1.1.1</version>  
           </dependency>  
           <dependency>  
                <groupId>commons-collections</groupId>  
                <artifactId>commons-collections</artifactId>  
                <version>3.2.1</version>  
           </dependency>  
           <dependency>  
                <groupId>antlr</groupId>  
                <artifactId>antlr</artifactId>  
                <version>2.7.7</version>  
           </dependency>  
           <!-- Test -->  
           <dependency>  
                <groupId>junit</groupId>  
                <artifactId>junit</artifactId>  
                <version>4.7</version>  
                <scope>test</scope>  
           </dependency>  
      <!--      <dependency>  
                <groupId>javax.validation</groupId>  
                <artifactId>validation-api</artifactId>  
                <version>1.1.0.Final</version>  
           </dependency> -->  
      </dependencies>  
      <build>  
           <plugins>  
                <plugin>  
                     <artifactId>maven-eclipse-plugin</artifactId>  
                     <version>2.9</version>  
                     <configuration>  
                          <additionalProjectnatures>  
                               <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>  
                          </additionalProjectnatures>  
                          <additionalBuildcommands>  
                               <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>  
                          </additionalBuildcommands>  
                          <downloadSources>true</downloadSources>  
                          <downloadJavadocs>true</downloadJavadocs>  
                     </configuration>  
                </plugin>  
                <plugin>  
                     <artifactId>maven-resources-plugin</artifactId>  
                     <version>2.5</version>  
                     <configuration>  
                          <encoding>UTF-8</encoding>  
                     </configuration>  
                </plugin>  
                <plugin>  
                     <artifactId>maven-compiler-plugin</artifactId>  
                     <version>3.0</version>  
                     <configuration>  
                          <source>${java-version}</source>  
                          <target>${java-version}</target>  
                          <compilerVersion>${java.version}</compilerVersion>  
                          <encoding>UTF-8</encoding>  
                     </configuration>  
                </plugin>  
                <plugin>  
                     <groupId>org.codehaus.mojo</groupId>  
                     <artifactId>exec-maven-plugin</artifactId>  
                     <version>1.2.1</version>  
                     <configuration>  
                          <mainClass>org.test.int1.Main</mainClass>  
                     </configuration>  
                </plugin>  
           </plugins>  
      </build>  
 </project>  

make sure the version of Spring , hibernate must be compatiable.
One point to take care , if using Spring 3 , use Hibernate 3 only same in case of Spring 4.


Application Context File

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
      <!-- The definition of the Root Spring Container shared by all Servlets   
           and Filters -->  
      <context-param>  
           <param-name>contextConfigLocation</param-name>  
           <param-value>/WEB-INF/spring/root-context.xml</param-value>  
      </context-param>  
      <!-- Creates the Spring Container shared by all Servlets and Filters -->  
      <listener>  
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
      </listener>  
      <!-- Processes application requests -->  
      <servlet>  
           <servlet-name>appServlet</servlet-name>  
           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
           <init-param>  
                <param-name>contextConfigLocation</param-name>  
                <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>  
           </init-param>  
           <load-on-startup>1</load-on-startup>  
      </servlet>  
      <servlet-mapping>  
           <servlet-name>appServlet</servlet-name>  
           <url-pattern>/</url-pattern>  
      </servlet-mapping>  
      <filter>  
    <filter-name>hibernateFilter</filter-name>  
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
    <init-param>  
      <param-name>sessionFactoryBeanName</param-name>  
      <param-value>sessionFactory</param-value>       
    </init-param>     
   </filter>  
 </web-app>  


Database Settings

Run the DB Script mentioned above

JDBC Properties-
 jdbc.driverClassName=com.mysql.jdbc.Driver  
 jdbc.dialect=org.hibernate.dialect.MySQLDialect  
 jdbc.url=jdbc:mysql://localhost:3306/midas-test  
 jdbc.username=root  
 jdbc.password=root  


HBM File
 <?xml version='1.0' encoding='utf-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
   "-//Hibernate/Hibernate Configuration DTD//EN"  
   "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
   <session-factory>  
     <mapping class="com.test.comment.db.Comment" />  
   </session-factory>  
 </hibernate-configuration>  


Rest all the files are Hibernate DAO , Service file.
Download the zip to test the project.
Maven Compile and package the same before using it.
Download Project





No comments: