Monday, July 20, 2015

Creating a Maven web project (Spring 4+Hibernate 4+Tiles 3)

In this tutorial, You can get an idea about the java web project creation. I have used the latest versions of every framework as of now.

Spring 4
Hibernate 4
Tiles 3
MySQL 5
(Also included bootstrap and jquery - latest versions)

Before we move to the tutorial you need an eclipse with maven installed. I am using MySQL as my database, if you need you can use something else. 

That's all you need...!!!

Note: I have attached an sample project end of the tutorial, Please download and have a look if you find any difficulties through out the tutorial.


Step 01 - Creating the web project

Creating a maven project in the eclipse

File->New->Other->Maven->Maven Project

In the second page of the wizard type maven-archetype-webapp and select next

Enter the Group ID - eg: com.isd.testproject
Artifact ID - myfirstproject

Now you have created the maven project.

Step 02 - Add Spring framework

Update your pom file as below,

<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.isd.sappu.savari</groupId>
  <artifactId>SappuSavari</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SappuSavari Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
<spring.version>4.0.5.RELEASE</spring.version>
<tiles.version>3.0.5</tiles.version>
<hibernate.version>4.0.1.Final</hibernate.version>
<mysql.version>5.1.10</mysql.version>
<junit.version>3.8.1</junit.version>
<jdk.version>1.6</jdk.version>
  </properties>
  
  <dependencies>

  <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>    
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
</dependency>

<dependency>      
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
</dependency>

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${spring.version}</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>
     
  </dependencies>
  
  <build>
 
  <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <encoding>UTF-8</encoding>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
        </plugin>            
    </plugins>
    <finalName>SappuSavari</finalName>
  </build>
</project>

Let's add the application-context.xml file,

In my case Im adding my configuration file in the spring_config folder in WEB-INF folder, You can change the location as you want and update in the web.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 

<!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.isd.sappu.savari" />

<!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

<!-- scans packages to find and register beans within the application context -->
<context:component-scan base-package="com.isd.sappu.savari.controllers" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />

<!-- Resolves Views -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/views/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean>

</beans>

Let's update the web.xml accordingly,

<?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>Spring MVC Application</display-name>

<listener>     
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring_config/application-context.xml</param-value>
</context-param>

<servlet>
<servlet-name>spring-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> 
<servlet-mapping>
<servlet-name>spring-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

Now you have added Spring 4.0.5 to your Project.

Let's Check the project is working so far. 

Update your index page as below,

<html>
<body>
<h1><a href="test">Go to Spring Test Page</a></h1>
</body>
</html>


Create another test.jsp file in the WEB-INF and update as below,

<html>
<body>
<h1>${message}</h1>
</body>
</html>


Create a folder in src/main folder named java if you haven't one already, and create a package for your controller file

Now create a first.java file in the package and update as below


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller(value="firstController")
public class FirstClass {

@RequestMapping(value="test", method=RequestMethod.GET)
public ModelAndView firstMethode(){
ModelMap map = new ModelMap();
map.put("message", "isuru");
return new ModelAndView("test", map);
}

}

Now when you run the project a link will show you on index page, when you click on the link the get request will come to the controller you created above. ModelMap will bring the message and redirect to the test.jsp page and show you the message. In my case the message will be "isuru".


Step 02 - Add Hibernate

I am adding mysql database to my project, you can add any database, just add the correct properties.

What we have to update is some jar files(pom file), hibernate configuration xml ,hibernate properties file and application context xml file for new data source.

Update your pom file as below,

<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.isd.sappu.savari</groupId>
  <artifactId>SappuSavari</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SappuSavari Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
<spring.version>4.0.5.RELEASE</spring.version>
<tiles.version>3.0.5</tiles.version>
<hibernate.version>4.0.1.Final</hibernate.version>
<mysql.version>5.1.10</mysql.version>
<junit.version>3.8.1</junit.version>
<jdk.version>1.6</jdk.version>
  </properties>
  
  <dependencies>
  
  <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>    
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
</dependency>

<dependency>      
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
</dependency>

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${spring.version}</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>
    

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>${hibernate.version}</version>
     </dependency>
     <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-validator</artifactId>
         <version>4.2.0.Final</version>
     </dependency>
     <dependency>
         <groupId>org.hibernate.common</groupId>
         <artifactId>hibernate-commons-annotations</artifactId>
         <version>${hibernate.version}</version>
         <classifier>tests</classifier>
     </dependency>
     <dependency>
         <groupId>org.hibernate.javax.persistence</groupId>
         <artifactId>hibernate-jpa-2.0-api</artifactId>
         <version>1.0.1.Final</version>
     </dependency>
     <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-entitymanager</artifactId>
         <version>${hibernate.version}</version>
     </dependency>
     <dependency>
    <groupId>org.hibernate</groupId>
   <artifactId>hibernate-c3p0</artifactId>
   <version>${hibernate.version}</version>
</dependency>
     <dependency>
         <groupId>javax.validation</groupId>
         <artifactId>validation-api</artifactId>
         <version>1.0.0.GA</version>
         <scope>provided</scope>
     </dependency>
     <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>1.6.4</version>
     </dependency>
     <dependency>
         <groupId>org.jboss.logging</groupId>
         <artifactId>jboss-logging</artifactId>
         <version>3.1.0.CR2</version>
     </dependency>
     <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>1.6.4</version>
     </dependency>

     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql.version}</version>
     </dependency>
     
  </dependencies>
  
  <build>
 
  <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <encoding>UTF-8</encoding>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
        </plugin>            
    </plugins>
    <finalName>SappuSavari</finalName>
  </build>

</project>

Add below two files in the src/main/resource folder,

hibernate.propeties

hibernate.connection.driver_class=com.mysql.jdbc.Driver

#LOCAL development database
hibernate.connection.url=jdbc:mysql://localhost:3306/sample_db
hibernate.connection.username=root
hibernate.connection.password=root

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
hibernate.connection.pool_size=5
hibernate.c3p0.min_size=2
hibernate.c3p0.max_size=5
hibernate.c3p0.timeout=300
hibernate.c3p0.acquire_increment=3
hibernate.c3p0.max_statements=100
hibernate.c3p0.max_numHelperThreads=10
hibernate.jdbc.use_streams_for_binary=false
hibernate.connection.useUnicode=true
hibernate.connection.characterEncoding=UTF-8
hibernate.connection.defaultNChar=true
hibernate.search.default.directory_provider=org.hibernate.search.store.FSDirectoryProvider
hibernate.search.default.indexBase=D:/home/sappu_savari
hibernate.search.analyzer=org.apache.lucene.analysis.standard.StandardAnalyzer
hibernate.format_sql=true

hibernate.use_sql_comments=true


hibernate_config.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  
    <property name="connection.url">jdbc:mysql://localhost:3306/sappusavari_db</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
    <property name="show_sql">true</property>
  
    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
  
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>

</session-factory>
</hibernate-configuration>

Update application-context.xml file as below,

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>

<!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.isd.sappu.savari" />

<!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

<!-- scans packages to find and register beans within the application context -->
<context:component-scan base-package="com.isd.sappu.savari.controllers" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />

<!-- Resolves Views -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/views/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${hibernate.connection.driver_class}" />
        <property name="url" value="${hibernate.connection.url}" />
        <property name="username" value="${hibernate.connection.username}" />
        <property name="password" value="${hibernate.connection.password}" />
    </bean>
    
    <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
                          
           <list>               
            <value>com.isd.sappu.savari.domains.Product</value>
           </list>
              
        </property>
        <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>
<prop key="hibernate.connection.provider_class">${hibernate.connection.provider_class}</prop>
<prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
                <prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
                <prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
                <prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
                <prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
                <prop key="hibernate.c3p0.acquire_increment">${hibernate.c3p0.acquire_increment}</prop>
                <prop key="hibernate.c3p0.max_numHelperThreads">${hibernate.c3p0.max_numHelperThreads}</prop>
                <prop key="hibernate.jdbc.use_streams_for_binary">${hibernate.jdbc.use_streams_for_binary}</prop>
                <prop key="hibernate.search.default.directory_provider">${hibernate.search.default.directory_provider}</prop>
                <prop key="hibernate.search.default.indexBase">${hibernate.search.default.indexBase}</prop>
                <prop key="hibernate.connection.useUnicode">${hibernate.connection.useUnicode}</prop>
                <prop key="hibernate.connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
                <prop key="hibernate.connection.defaultNChar">${hibernate.connection.defaultNChar}</prop>
                <prop key="hibernate.search.analyzer">${hibernate.search.analyzer}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop> 
            </props>
        </property>
     </bean>


</beans>

Now you added hibernate to your project.

You can check whether it's working like below,

Create a package and create a Product.java file inside the created package as below,

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="product")
public class Product implements Serializable{

private static final long serialVersionUID = 5489679679570043539L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
private String productName;

public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}

Now build and run the project, there should be table inside the sample_db database.

Step 02 - Add Tiles

Note : I tried to configure Tiles version 2 first, but I failed to do that may be spring 4 won't compatible with tiles version 2 anymore. But tiles version 3 is working fine with spring 4

For adding tiles to your project you have to update pom for few jars, and change the view resolver in the application context xml file.

For adding tiles you should insert below tags in the pom file

        <dependency>
  <groupId>org.apache.tiles</groupId>
  <artifactId>tiles-api</artifactId>
  <version>${tiles.version}</version>
</dependency>
<dependency>
          <groupId>org.apache.tiles</groupId>
          <artifactId>tiles-core</artifactId>
          <version>${tiles.version}</version>
        </dependency>
        <dependency>
          <groupId>org.apache.tiles</groupId>
          <artifactId>tiles-jsp</artifactId>
           <version>${tiles.version}</version>
         </dependency>
         <dependency>
  <groupId>org.apache.tiles</groupId>
  <artifactId>tiles-servlet</artifactId>
  <version>${tiles.version}</version>
        </dependency>
        <dependency>
  <groupId>org.apache.tiles</groupId>
  <artifactId>tiles-template</artifactId>
  <version>${tiles.version}</version>
</dependency>

In application-context.xml file, we have to update the view resolver class like below,

<!-- Resolves Views -->
<bean id="viewResolver"
   class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
</bean>
<bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
   <list>
<value>/WEB-INF/spring_config/tiles.xml</value>
   </list>
</property>
</bean>

As you can see on above configuration tiles.xml file should be created inside the WEB-INF/spring_config folder

tiles.xml file can be vary according to your aspect, Please download the sample project and refer for more details on tiles.

That's all folks, Now you have a powerful platform to build something better.

I have added latest bootsrap and jquery to the project. If you are interested you can download a blank sample project.

Download Sample Project


Have a nice day...!!!

No comments:

Post a Comment