dineshonjava

Create New Project Using Maven In Eclipse

In last tutorial we learnt to configure maven in eclipse . In this tutorial we will learn to create new maven project in eclipse.

To create a new project in maven we need to follow following steps 

1) Open eclipse and follow stated navigation represented in below pic

Create New Project Using Maven In Eclipse
2) A new pop- up will open , in that pop-up we need to check the provided option as below

Using Maven In Eclipse


3) Again a new pop-up will open, in that pop-up box we need to fill some information related to our project.

Maven In Eclipse


After filling required fields click finish button.

4) After clicking finish button you will find a new project being created in the project explorer.


5) You can see a new project has been created with symbol 'M' over the project which shows that it is maven project. 

6) You can see maven has provided the specified folder structure and a POM.xml file by his own. This is why maven is called as "Convention Over Configuration".

7) POM.xml is heart of maven project.

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelversion>4.0.0</modelversion>

<groupid>com.dineshonjava.example</groupid>

<artifactid>maven_first_example</artifactid>

<version>0.0.1-SNAPSHOT</version>

<name>sample project</name>

<description>this project is being created for learning.</description>
</project>

8) The content of this pom.xml is being generated based on the information we have filled while creating the new project using maven.

9) By following Convention over configuration maven states that " I am providing specific folder structure to put specific files, like : 
     src/main/java --> to put .java file
     src/main/resources --> to put resource files like properties file in class path
     src/test/java ---> to put . java file for junit test cases.

10)  Now we will be writing simple Java program in src/main/java
package com.dineshonjava;
public class Example1 {
public static void main(String[] args) {
System.out.println("welcome to maven");

 }
}


11) Now we need to run the application, Before running the application we need to build that and to build that 
  a) right click on the project 
  b) click on the run as 'maven install' 
  c) after clicking that look into console , if every thing will be fine you will find following :
    
[INFO] 
[INFO] --- maven-jar-plugin:2.3.2:jar (default-jar) @ maven_first_example ---
[INFO] Building jar: E:\newsprinws\maven_first_example\target\maven_first_example-0.0.1-SNAPSHOT.jar
[INFO] 
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ maven_first_example ---
[INFO] Installing E:\newsprinws\maven_first_example\target\maven_first_example-0.0.1-SNAPSHOT.jar to C:\Users\lenovo\.m2\repository\com\dineshonjava\example\maven_first_example\0.0.1-SNAPSHOT\maven_first_example-0.0.1-SNAPSHOT.jar
[INFO] Installing E:\newsprinws\maven_first_example\pom.xml to C:\Users\lenovo\.m2\repository\com\dineshonjava\example\maven_first_example\0.0.1-SNAPSHOT\maven_first_example-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.271s
[INFO] Finished at: Tue Jun 16 23:35:35 IST 2015
[INFO] Final Memory: 7M/178M
[INFO] ------------------------------------------------------------------------

12) After running that process , when you will look into project explorer you will find following 


13) Due to above process which ease the building of project , maven is also famous as automated building tool.

14) Now to run this simple application just click on the project and run as a java application and you can find the desired output in console.

More we will learn about the different components of maven in upcoming tutorial .

Keep Learning, Happy Coding




Testimonials for dineshonjava.com

"Recently I attended the online training course - Spring 4 MVC - conducted by Mr Dinesh Rajput personally, and I certify that he was able to give hands-on trainin on the basics of developing Spring MVC applications using STS-Gradle-Thymeleaf technologies. Having said that, I highly recommend DOJ to anybody in need of first-hand technology support."

By,
Bhawani Shanker
Austria (European Union)
January, 2015

"Hi Dinesh, I follow your dineshonjava.com which is one of the best online resource to learn Java and related technologies. I really enjoyed going through your articles. These are helped me to learn frameworks like doing and implement them. Thank you so much."

By reader,
Murali k
Senior Software Engineer at UHG (Unified Healthcare Group)

"wow! this is an exhaustive look at Spring Boot’s Actuator on the Dinesh on Java blog."

By-
Josh Long
Spring Community


"Amazing post with amazing blog.. In my learning phase mostly I prefer your blog well explain java concepts"

By-
Yogendra Sharma

"I don’t know if I would call this complete, but it is exhaustive! Well done Dinesh, on this lengthy introduction to Spring Boot "

By-
Josh Long
Spring Community


"Spring for Delphi. Cool! Eren Av?aro?ullar? has a nice post showing how to use dynamic languages (in particular, Groovy) with Spring. Dinesh Rajput has put together a blog introducing some of the features unique to the Spring Batch 2.x generation, which - while Spring Batch 2.x has been out"

By-
Josh Long
Spring Community

"But it's also stuff that's very convenient to reference in a pinch and it's nice to see it all laid out in order with a little bit of narrative. The Dinesh on Java blog has a nice post on how to setup Spring Security. The Lucky Ryan blog has a really à propos post on migrating XML-based Spring MVC configuration"

By-
Josh Long
Spring Community

"The Dinesh on Java blog has a nice post on how to use Spring Data"

By-
Josh Long
Spring Community

"on server-side pagination with ZK (a widget-centric web framework), Spring Data MongoDB and Google Maps. Do I need to say anymore? Check it out! The Dinesh on Java blog has a nice, introductory post on using Spring MVC interceptors. Good stuff!"-

By-
Josh Long
Spring Community




How work Garbage Collector in Java

In this tutorial we will explain how to garbage collector work in JVM. In the first tutorial of garbage collector we have seen what is garbage collection in java and its related some methods. In Java, allocation and de-allocation of memory space for objects are done by the garbage collection process in an automated way by the JVM.

Java Memory Management
Java Memory Management, with its built-in garbage collection, is one of the language’s finest achievements. It allows developers to create new objects without worrying explicitly about memory allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This enables faster development with less boilerplate code, while eliminating memory leaks and other memory-related problems. At least in theory.
Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most memory-management issues are solved, but often at the cost of creating serious performance problems. Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize system. In order to wrap your head around garbage collection, you need first to understand how memory management works in a Java Virtual Machine (JVM).

Java Garbage Collection GC Initiation
Being an automatic process, programmers need not initiate the garbage collection process explicitly in the code. System.gc() and Runtime.gc() are hooks to request the JVM to initiate the garbage collection process.

Though this request mechanism provides an opportunity for the programmer to initiate the process but the onus is on the JVM. It can choose to reject the request and so it is not guaranteed that these calls will do the garbage collection. This decision is taken by the JVM based on the eden space availability in heap memory. The JVM specification leaves this choice to the implementation and so these details are implementation specific.

Undoubtedly we know that the garbage collection process cannot be forced. I just found out a scenario when invoking System.gc() makes sense. Just go through this article to know about this corner case when System.gc() invocation is applicable.

Java Garbage Collection Process
Garbage collection is the process of reclaiming the unused memory space and making it available for the future instances.

How work Garbage Collector in Java

Eden Space: When an instance is created, it is first stored in the eden space in young generation of heap memory area.

Survivor Space (S0 and S1): As part of the minor garbage collection cycle, objects that are live (which is still referenced) are moved to survivor space S0 from eden space. Similarly the garbage collector scans S0 and moves the live instances to S1.

Instances that are not live (dereferenced) are marked for garbage collection. Depending on the garbage collector (there are four types of garbage collectors available and we will see about them in the next tutorial) chosen either the marked instances will be removed from memory on the go or the eviction process will be done in a separate process.

Old Generation: Old or tenured generation is the second logical part of the heap memory. When the garbage collector does the minor GC cycle, instances that are still live in the S1 survivor space will be promoted to the old generation. Objects that are dereferenced in the S1 space is marked for eviction.

Major GC: Old generation is the last phase in the instance life cycle with respect to the Java garbage collection process. Major GC is the garbage collection process that scans the old generation part of the heap memory. If instances are dereferenced, then they are marked for eviction and if not they just continue to stay in the old generation.

Memory Fragmentation: Once the instances are deleted from the heap memory the location becomes empty and becomes available for future allocation of live instances. These empty spaces will be fragmented across the memory area. For quicker allocation of the instance it should be defragmented. Based on the choice of the garbage collector, the reclaimed memory area will either be compacted on the go or will be done in a separate pass of the GC.


What is the garbage collector in Java?

Garbage Collector is part of JRE that makes sure that object that are not referenced will be freed from memory. Garbage collector can be viewed as a reference count manager. if an object is created and its reference is stored in a variable, its reference count is increased by one. during the course of execution if that variable is assigned with NULL. reference count for that object is decremented. so the current reference count for the object is 0. Now when Garbage collector is executed, It checks for the objects with reference count 0. and frees the resources allocated to it.

Advantage of Garbage Collection
  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
  • By nulling the reference
    Student s=new Student();
    s=null;

  • By assigning a reference to another
    Student s1=new Student();
    Student s2=new Student();
    s1=s2;//now the first object referred by s1 is available for garbage collection

  • By annonymous object etc.
    new Student();
finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}

The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc(){}

Many people think garbage collection collects and discards dead objects.
In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage.

When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system. To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm.





Adding an existing project to GitHub using the command line

Step for existing project to GitHub using command line, following steps are required to this.

Step 1: Creating an account to the GitHub. Suppose
Username for GitHub: myGitUser
Password for GitHub: myGitPassword

https://github.com/myGitUser/

Step 2: Access above url using mention username and password.

Step 3: Create New Repository to your account. To avoid errors, do not initialize the new repository with README. You can add these files after your project has been pushed to GitHub.

Suppose your repository name: myRepository

https://github.com/myGitUser/myRepository
Step 4: Installing GitBash to you machine. for this link http://git-scm.com/download/win

Step 5: After installing GitBash open the command prompt for Git.

GitShell

Step 6: In the Command prompt, change the current working directory to your local project.

Step 7: Initialize the local directory as a Git repository. As follows

git-init

Step 8: Add the files in your new local repository. This stages them for the first commit.

git-add

Step 9: Commit the files that you've staged in your local repository.

git-commit

Commits the tracked changes and prepares them to be pushed to a remote repository

Step 10: At the top of your GitHub repository's Quick Setup page, click to copy the remote repository URL

https://github.com/myGitUser/myRepository.git

Step 11: In the Command prompt, add the URL for the remote repository where your local repository will be pushed

git-remote

# Sets the new remote

Step 12: Push the changes in your local repository to GitHub.

git-push

# Pushes the changes in your local repository up to the remote repository you specified as the origin


Struts to Spring mvc migration

Hi in this tutorial we will see the migration of a web application made in struts to spring mvc. Struts to Spring migration we will do step by step. Here I will share you step by step approach to migrate application from Struts to Spring using annotations.

Struts to spring migration

Step 1: Replace struts libraries with spring libraries.

Firstly while migrating from struts to spring we have to replace our struts related libraries with spring libraries in lib folder. I have mentioned basic libraries of both struts and spring for your clarification.

Struts basic libraries :
1. struts.jar
2. struts-legacy.jar
etc..
Spring basic libraries :
1. standard.jar
2. org.springframework.asm-4.0.1.RELEASE-A.jar
3. org.springframework.beans-4.0.1.RELEASE-A.jar
4. org.springframework.context-4.0.1.RELEASE-A.jar
5. org.springframework.core-4.0.1.RELEASE-A.jar
6. org.springframework.expression-4.0.1.RELEASE-A.jar
7. org.springframework.web.servlet-4.0.1.RELEASE-A.jar
8. org.springframework.web-4.0.1.RELEASE-A.jar
etc..

Step 2: Change made to web.xml file for struts to spring migration

In this step we have to remove Action filter dispatcher for the web.xml and add Spring dipatcher servlet as Front controller

In Strut application web.xml look like as follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2MyFirstApp</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

In Spring application web.xml look like as follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springApp</display-name>
  <servlet>
    <servlet-name>springApp</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springApp</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Step 3: Replace config files for struts to spring migration
Now replace all struts configuration files to spring configuration file as follows
In Struts applivation struts configuration file-
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
    <package name="default" extends="struts-default" namespace="/">
        <action name="login" class="com.dineshonjava.struts2.login.LoginAction">
            <result name="success">Welcome.jsp</result>
            <result name="error">Login.jsp</result>
        </action>
    </package>
</struts>

In Spring application spring configuration file as follows
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:context="http://www.springframework.org/schema/context"  
     xmlns:p="http://www.springframework.org/schema/p"    
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     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">  
      
     <context:component-scan base-package="com.dineshonjava.spring.login.controller" />  
      
     <bean id="viewResolver"  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>  

Here, <context:component-scan> tag is used, so that spring will load all the components from given package i.e. "com.dineshonjava.spring.login.controller"

We can use different view resolver, here I have used InternalResourceViewResolver. In which prefix and suffix are used to resolve the view by prefixing and suffixing values to the object returned by ModelAndView in action class.

Step 4: JSP changes for struts to spring migration
While migration an application from struts to spring we need to change in jsp file as following

Firstly replace all tlds-

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

Replace these with following spring taglib's :
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

In Struts :
<html:form action="/addLogin" method="post">
In Spring :
<form:form method="POST" commandName="loginForm" name="loginForm" action="login.do">
Here commandName is going to map with corresponding formbean for that jsp. Next we will see, how action is getting called with spring 4 annotations.

Step 5: Action class changes for struts to spring migration
Now following changes need to be done in action classes for struts to spring migration using annotations-

Struts Action:
package com.dineshonjava.struts2.login;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
@SuppressWarnings("serial")
public class LoginAction  extends ActionSupport{
 private String username;
    private String password;
    
 public String execute() {
   
        if (this.username.equals("dinesh") 
                && this.password.equals("sweety")) {
            return "success";
        } else {
         addActionError(getText("error.login"));
            return "error";
        }
    }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
 
}

Spring action
package com.dineshonjava.spring.login.controller;

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

/**
 * @author Dinesh.Rajput
 *
 */
@Controller
public class LoginController {
 
 @RequestMapping(value="/login.do", method = RequestMethod.GET)
 public String doLogin(ModelMap model, LoginForm loginForn) {
 if (this.username.equals("dinesh") 
                && this.password.equals("sweety")) {
            model.addAttribute("message", "Login Success");
        } else {
            model.addAttribute("message", "Login Failure");
        }
         return "home";
 
 }
}


Step 6: Validation changes for struts to spring migration
in struts JSP file validation changes as follows
<%
 ActionErrors actionErrors = (ActionErrors)request.getAttribute("org.apache.struts.action.ERROR");
%>
In Spring JSP file as follows-
<form:errors path="*" cssClass="error" />  




Java Database Connectivity(JDBC) Tutorial

Java Database Connectivity:

JDBC is a Java database connectivity technology (Java Standard Edition platform) from Oracle Corporation. This technology is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.

JDBC drivers:

JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand.

Types:

There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:
JDBC technology drivers fit into one of four categories.
1.     JDBC-ODBC bridge
2.     Native-API Driver
3.     Network-Protocol Driver(MiddleWare Driver)
4.     Database-Protocol Driver(Pure Java Driver


   1. JDBC-ODBC bridge:
The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls.
Java Database Connectivity(JDBC) Tutorial

Sun provides a JDBC-ODBC Bridge driver: sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.

Advantages:

  • Almost any database for which an ODBC driver is installed can be accessed, and data can be retrieved.

Disadvantages:

Performance overhead since the calls have to go through the jdbc Overhead bridge to the ODBC driver, then to the native db connectivity interface (thus may be slower than other types of drivers)

2.     Native-API Driver

The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.For example: Oracle OCI driver is a Type 2 Driver.
JDBC

Advantages:
As there is no implementation of jdbc-odbc bridge, its considerably faster than a type 1 driver.

Disadvantages:
The vendor client library needs to be installed on the client machine.

3 .     Network-Protocol Driver(MiddleWare Driver)

The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is a database driver implementation which makes use of a middle tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.
JDBC tutorial

Advantages:

Since the communication between client and the middleware server is database independent, there is no need for the database vendor library on the client. The client need not be changed for a new database.

Disadvantages:

· The middleware layer added may result in additional latency, but is typically overcome by using better middleware services.

4.     Database-Protocol Driver(Pure Java Driver)

Schematic of the Native-Protocol driver.The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol.
JDBC

Advantages:

· Completely implemented in Java to achieve platform independence.
· These drivers don't translate the requests into an intermediary format (such as ODBC).

Disadvantages:

  • Drivers are database dependent, as different database vendors use widely different (and usually proprietary) network protocols.

JDBC Basics – Java Database Connectivity Steps:

Step 1: Loading a database driver: The first thing you need to do before you can open a database connection is to load the JDBC driver for the database.


Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

Step 2: Opening the Connection
To open a database connection you use the java.sql.DriverManager class.
String url      = "jdbc:h2:~/test";  
String user     = "sa";
String password = "";

Connection connection =
    DriverManager.getConnection(url, user, password);


Step 3: Creating a jdbc Statement object: Once a connection is obtained we can interact with the database.
Statement statement = connection.createStatement();
A statement object is used to send and execute SQL statements to a database.

Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.

Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements.

Step 4: Closing the Connection
Once you are done using the database connection you should close it. This is done by calling the Connection.close() method, like this:
connection.close();

Example-

import java.sql.*;

class TestRetrieve
{
 public static void main(String[] args)
 {
  try
  {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection c=DriverManager.getConnection("Jdbc:Odbc:mydsn");
   Statement s=c.createStatement();
   ResultSet result1=s.executeQuery("select * from emp");
   while(result1.next())
   {
    System.out.println(result1.getString(1));
    System.out.println(result1.getString(2));
   }
  }catch(SQLException e)
     {
      System.out.println(e);
     }
   catch(Exception i)
   {
    System.out.println(i);
   }
  
 }
}



Spring MVC view layer- Thymeleaf vs. JSP

In this tutorial we will describe about two view layers for Spring MVC. One is JSP and another is Thymeleaf. Here we will compare the same page (a subscription form) created twice for the same Spring MVC application: once using Thymeleaf and another time using JSP, JSTL and the Spring tag libraries.

Common requirements-
Our customers need a form for subscribing new members to a message list, with two fields:
  • Email address
  • Type of subscription
Our application will have two @Controllers, which will contain exactly the same code but will forward to different view names:


  • SubscribeJsp for the JSP page (the subscribejsp view).
  • SubscribeTh for the Thymeleaf page (the subscribeth view).


We will have the following classes in our model:


  • Subscription form-backing bean with two fields: String email and String type.
  • Type has values EMAILS and DAILY_DIGEST.
Doing it with JSP



And this is our JSP code, making use of both JSTL (core) and Spring (tags and form) JSP tag libraries:

SubscribeJsp.jsp

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
 
<html>
 
  <head>
    <title>Spring MVC view layer: Thymeleaf vs. JSP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" href="<s:url value='/css/thvsjsp.css' />"/>
  </head>
 
  <body>
 
    <h2>This is a JSP</h2>
 
    <s:url var="formUrl" value="/subscribejsp" />
    <sf:form modelAttribute="subscription" action="subscribeMe">
 
      <fieldset>
 
        <div>
          <label for="email">Email: </label>
          <sf:input path="email" />
        </div>
        <div>
          <label>Type: </label>
          <ul>
              <li>
                <sf:radiobutton path="type" value="Email" />
                <label for="subscriptionType1">
                  All emails
                </label>
              </li>
              <li>
                <sf:radiobutton path="type" value="Digest" />
                <label for="subscriptionType2">
                  All Digests
                </label>
              </li>
          </ul>
        </div>
 
        <div class="submit">
          <button type="submit" name="save">SUBSCRIBE ME</button>
        </div>
 
      </fieldset>
 
    </sf:form>
 
  </body>
 
</html>

Doing it with Thymeleaf

Spring MVC view layer- Thymeleaf vs. JSP

And this is our Thymeleaf code:

SubscribeTh.html

<!DOCTYPE html>
 
<html xmlns:th="http://www.thymeleaf.org">
 
  <head>
    <title>Spring MVC view layer: Thymeleaf vs. JSP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all"
      href="../../css/thvsjsp.css" th:href="@{/css/thvsjsp.css}"/>
  </head>
 
  <body>
 
    <h2>This is a Thymeleaf template</h2>
 
    <form action="#" th:object="${subscription}" th:action="@{/subscribeth}">
 
      <fieldset>
 
        <div>
          <label for="email">Email: </label>
          <input type="text" th:field="*{email}" />
        </div>
        <div>
          <label>Type: </label>
          <ul>
            <li>
              <input type="radio" th:field="*{type}" th:value="email" />
              <label>All emails</label>
            </li>
            <li>
              <input type="radio" th:field="*{type}" th:value="digest" />
              <label>All Digest</label>
            </li>
            <li th:remove="all"><input type="radio" /> <label>Second Type</label></li>
          </ul>
        </div>
 
        <div class="submit">
          <button type="submit" name="save">Subscribe me!</button>
        </div>
 
      </fieldset>
 
    </form>
 
  </body>
 
</html>

Things to notice here:
  • This looks much more HTML-ish than the JSP version – no strange tags, just some meaningful attributes.
  • Variable expressions (${...}) are Spring EL and execute on model attributes, asterisk expressions (*{...}) execute on the form backing bean, hash expressions (#{...}) are for internationalization and link expressions (@{...}) rewrite URLs. (If you want to know more about this, have a look at the “Getting started with the Standard Dialect in 5 minutes” guide).
  • We are allowed to have prototype code there: for example, we can set an Email: text in the label for the first field, knowing that Thymeleaf will substitute it with the internationalized text with key subscription.email when it executes the page.
  • We have even been able to add anfor a second radiobutton just for prototyping pleasure. It will be removed when Thymeleaf executes our page.

Change the page style--

Let’s see the steps we would have to take with each technology:

Changing the page style using JSP

Step 1: Deploy the application into our development server and start it up. Our JSP page will not render without starting the server, so this will be a requirement.

Step 2: Navigate through the pages until we find the one to change. Normally, the page to change will be one among several dozen pages in our application, and it is quite possible that in order to reach it we will need to click links, submit forms and/or query databases.

Step 3: Fire up firebug, dragonfly, or our favourite in-browser web development tool. This will allow us to modify our styles acting directly on the browser’s DOM, and thus see immediate results.

Step 4: Make the colour changes. Probably trying a couple of different tones of blue before deciding on the one we like.

Step 5: Copy-paste the changes into our CSS files.

Changing the page style using Thymeleaf

Step 1: Double-click on the .html template file itself and let our browser open it. Being a Thymeleaf template, it will show just fine, only with template/prototype data.

Step 2: Open the .css file with our favourite text editor. The template file statically links to the CSS in its tag (with an href that Thymeleaf substitutes when executing the template by the one generated by th:href). So any changes we make to that CSS will be applied to the static page our browser is displaying.

Step 3: Make the colour changes. As was the case with JSP, we will probably have to try several colour combinations, which will be refreshed in our browser just by pressing F5.

The difference in the number of steps is not really important here (we could also have used firebug with the Thymeleaf template). What is really important is the complexity, the effort and the time required by each of the steps required for JSP. Having to deploy and start the whole application made JSP just lose.

What’s more: think of how this difference would evolve if:

  • Our development server was not local but remote.
  • Changes didn’t involve only CSS but also adding/removing some HTML code.
  • We still hadn’t implemented the required logic in our application to actually reach that page once deployed.

Pros and Cons in JSP

Standard Tags have many benefits:


  • I can use them to do much more than just externalizing layout information. In the end, they can easily make your JSPs 5 times smaller than they would be otherwise.
  • Eclipse/STS works well with custom tags so you’re able to use CTRL+space for auto-completion.

On the down side:


  • Documentation is not the best.
  • Even though custom tags are pretty neat already, I can’t recall any improvement to them in the past few years.
  • Using Custom tags implies that you’re using a JSP Engine inside your web container. You can then expect some minor differences depending on the web container you’re using (Apache Tomcat, IBM Websphere, Oracle Weblogic…).
  • It is also harder to Unit Test your view layer. You can see Spring MVC Test framework if you’re interested in this topic.

Pros and Cons in Thymeleaf

On the bright side:

  • ThymeLeaf is a healthy open source project: new features coming up each month, good documentation, responsive user forums…
  • It is the ideal template engine if you want your web designer to be able to read your view files
  • The Expression Language used (actually called Standard Dialect) is much more powerful than JSP Expression Language.
  • Unlike JSPs, Thymeleaf works well for Rich HTML emails (see http://www.thymeleaf.org/springmail.html).

On the down side:

  • Thymeleaf does not have an equivalent to custom tags (.tagx files) yet.
  • At this stage, ThymeLeaf is not compatible with JSP tag libraries.

Conclusion


We’ve seen the JSP and Thymeleaf approaches side by side. If your application uses hundreds of JSPs, we are not saying that you should ditch them all and start over again using Thymeleaf. However you might consider Thymeleaf for HTML pages outside of the web container such as for Rich HTML emails.

If you are starting on a new project, we strongly encourage you to compare both Thymeleaf and JSPs in order to figure out which one is more suitable to your needs.




Gradle Spring MVC Web Project Example

In this tutorial we explain the spring mvc project and it is managed by Gradle. For this Gradle Spring MVC Web Project Example required following technologies.
  • gradle-2.2.1-all.zip
  • Spring 4.0.6.RELEASE
  • STS
Gradle Tutorial

Step 1. Add Gradle plugin to STS IDE

Step 2. Create Project Structure for Dynamic Web Project As following.

Gradle Spring MVC

Step 3. Gradle Build File
Build.gradle
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'

repositories {
   mavenCentral()
}
 
dependencies {
   providedCompile 'javax.servlet:servlet-api:2.5'
   compile 'org.springframework:spring-webmvc:4.0.0.RELEASE'
   compile 'org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE'
   compile 'org.thymeleaf:thymeleaf:2.1.4.RELEASE'
   runtime 'javax.servlet:jstl:1.1.2'
}
Step 4. Go to the project folder, same level with build.gradle, issue the following command :

$ gradle cleanEclipse eclipse

Now, you can import the project into STS IDE.

or

Step 4. Right click on the project and goto the configure and click convert gradle project.

convert-gradle-project

Step 5. Spring MVC Files Code

HomeController.java
package com.doj.controller;

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

@Controller
public class HomeController {
 
 @RequestMapping(value="/", method = RequestMethod.GET)
 public String printWelcome(ModelMap model) {
  model.addAttribute("message", "Spring 4 MVC Hello Gradle World!!! This is a Thymeleaf template ");
  return "home";
 
 }
}


home.jsp
<html>
<body>
 <h1>Message : ${message}</h1> 
</body>
</html>

mygradleapp-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:p="http://www.springframework.org/schema/p"    
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     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">  
      
     <context:component-scan base-package="com.doj.controller" />  
             
     <bean id="viewResolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix">  
          <value>/WEB-INF/view/</value>  
        </property>  
        <property name="suffix">  
          <value>.jsp</value>  
        </property>  
      </bean>   
</beans>  

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>mygradleapp</display-name>
  <servlet>
    <servlet-name>mygradleapp</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mygradleapp</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

Step 6: Run It
Start and deploy above web project.

http://localhost:8080/mygradleapp/


gradle-spring-output



Step 7. Create WAR File
Clean and build a WAR file with the following command :

$ gradle clean build
:clean
:compileJava
:processResources
:classes
:war
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build

BUILD SUCCESSFUL

Total time: 4.012 secs


The generated WAR file is located at the build\libs folder.

${Project}\build\libs\mygradleapp.war



Download Source Code

mygradleapp.zip



Building Java Projects with Gradle

This guide walks you through using Gradle to build a simple Java project. You’ll create a simple app and then build it using Gradle.

What you’ll need

About your 15 minutes
Gradle 2.0
A favorite text editor or IDE
JDK 6 or later

Step 1: Setup the Gradle to Machine
For this click here how setup

Step 2: Set up the project

First you set up a Java project for Gradle to build. To keep the focus on Gradle, make the project as simple as possible for now.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello

└── src
         └── main
                 └── java
                          └── hello

Within the src/main/java/hello directory, you can create any Java classes you want. For simplicity’s sake and for consistency with the rest of this guide, Spring recommends that you create two classes: HelloWorld.java and Greeter.java.

src/main/java/hello/HelloWorld.java
package hello;

public class HelloWorld {
  public static void main(String[] args) {
    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}
src/main/java/hello/Greeter.java
package hello;

public class Greeter {
  public String sayHello() {
    return "Hello world!";
  }
}

Step 3: Build Java code

Starting simple, create a very basic build.gradle file that has only one line in it:
apply plugin: 'java'
This single line in the build configuration brings a significant amount of power. Run gradle tasks again, and you see new tasks added to the list, including tasks for building the project, creating JavaDoc, and running tests.

You’ll use the gradle build task frequently. This task compiles, tests, and assembles the code into a JAR file. You can run it like this:

gradle build

After a few seconds, "BUILD SUCCESSFUL" indicates that the build has completed.

To see the results of the build effort, take a look in the build folder. Therein you’ll find several directories, including these three notable folders:

  • classes. The project’s compiled .class files.
  • reports. Reports produced by the build (such as test reports).
  • libs. Assembled project libraries (usually JAR and/or WAR files).

The classes folder has .class files that are generated from compiling the Java code. Specifically, you should find HelloWorld.class and Greeter.class.

At this point, the project doesn’t have any library dependencies, so there’s nothing in the dependency_cache folder.

Declare dependencies

The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common and/or complex functionality.

For example, suppose that in addition to saying "Hello World!", you want the application to print the current date and time. You could use the date and time facilities in the native Java libraries, but you can make things more interesting by using the Joda Time libraries.

First, change HelloWorld.java to look like this:

package mail.java.hello;

import org.joda.time.LocalTime;

public class HelloWorld {
  public static void main(String[] args) {
    LocalTime currentTime = new LocalTime();
    System.out.println("The current local time is: " + currentTime);

    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}


Here HelloWorld uses Joda Time’s LocalTime class to get and print the current time.

If you ran gradle build to build the project now, the build would fail because you have not declared Joda Time as a compile dependency in the build.

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

// tag::repositories[]
repositories {
    mavenLocal()
    mavenCentral()
}
// end::repositories[]

// tag::jar[]
jar {
    baseName = 'gs-gradle'
    version =  '0.1.0'
}
// end::jar[]

// tag::dependencies[]
dependencies {
    compile "joda-time:joda-time:2.2"
}
// end::dependencies[]

// tag::wrapper[]
task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}
// end::wrapper[]





How to Install Gradle

Hi in this post we will learn how to setup Gradle building tool to machine. Gradle is a dependency management / build tool that combines the best of Maven and Ant, making it an extremely powerful and customizable tool. It also uses a sleek Groovy DSL instead of the XML approach of Maven and Ant and is my personal tool-of-choice when I start a new project. Here’s how to install. I have some links to other gradle tutorials at the bottom of this post.

Prerequisites
Gradle requires a Java JDK or JRE to be installed, version 6 or higher (to check, use java -version). Gradle ships with its own Groovy library, therefore Groovy does not need to be installed. Any existing Groovy installation is ignored by Gradle.

Gradle uses whatever JDK it finds in your path. Alternatively, you can set the JAVA_HOME environment variable to point to the installation directory of the desired JDK.
Step 1: Install Java

First you need to have the Java JDK (Java Development Kit) installed; having the JRE (Java Runtime Environment) is not enough. To check if you have the JDK installed, open a command prompt or terminal and type javac -version. If you have a JDK installed, you will see your javac version output, eg. javac 1.7.0_01. If you get an error that javac is not a recognized command, download and install the Java JDK.

Step 2: Gradle Download
You can download one of the Gradle distributions from the Gradle web site.

Step 3: Unpacking
The Gradle distribution comes packaged as a ZIP. The full distribution contains:

  • The Gradle binaries.
  • The user guide (HTML and PDF).
  • The DSL reference guide.
  • The API documentation (Javadoc and Groovydoc).
  • Extensive samples, including the examples referenced in the user guide, along with some complete and more complex builds you can use as a starting point for your own build.
  • The binary sources. This is for reference only. If you want to build Gradle you need to download the source distribution or checkout the sources from the source repository. See the Gradle web site for details.

Step 4: Environment variables for Window
For running Gradle, add GRADLE_HOME/bin to your PATH environment variable. Usually, this is sufficient to run Gradle.
gradle-environment

Environment variables for Mac/Linux

  1. Extract the distribution archive, i.e. gradle-x.x-bin.tar.gz to the directory you wish to install Gradle. These instructions assume you chose /usr/local/gradle. The subdirectory gradle-x.x will be created from the archive.
  2. In a command terminal, add Gradle to your PATH variable: export PATH=/usr/local/gradle/gradle-x.x/bin:$PATH
  3. Make sure that JAVA_HOME is set to the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.7.0_06 and that $JAVA_HOME/bin is in your PATH environment variable.
  4. Run gradle –version to verify that it is correctly installed.


Step 5: Running and testing your installation
You run Gradle via the gradle command. To check if Gradle is properly installed just type gradle -v. The output shows the Gradle version and also the local environment configuration (Groovy, JVM version, OS, etc.). The displayed Gradle version should match the distribution you have downloaded.

To test the Gradle installation, run Gradle from the command-line:
gradle

If all goes well, you see a welcome message:

gradle-environment-success

You now have Gradle installed.

Find out what Gradle can do

Now that Gradle is installed, see what it can do. Before you even create a build.gradle file for the project, you can ask it what tasks are available:

gradle tasks

ou should see a list of available tasks. Assuming you run Gradle in a folder that doesn’t already have a build.gradle file, you’ll see some very elementary tasks such as this:

gradle-tasks

Even though these tasks are available, they don’t offer much value without a project build configuration. As you flesh out the build.gradle file, some tasks will be more useful. The list of tasks will grow as you add plugins to build.gradle, so you’ll occasionally want to run tasks again to see what tasks are available.


Step 6: JVM options
JVM options for running Gradle can be set via environment variables. You can use either GRADLE_OPTS or JAVA_OPTS, or both. JAVA_OPTS is by convention an environment variable shared by many Java applications. A typical use case would be to set the HTTP proxy in JAVA_OPTS and the memory options in GRADLE_OPTS. Those variables can also be set at the beginning of the gradle or gradlew script.