Create Spring Boot + Restful Project

Hi Everyone,

Create Spring Boot + Restful Project – with Spring Initializr.

The Spring Initializr is a website that generated a Spring Boot Project structure.
By creating Spring Boot with this Spring Initalizr it will generate all the project details.
Its include the dependencies of your application such build file and contains all the dependencies and configuration for the project.

Prerequisites:

Steps:

  1. Go to Spring initializr website, then add the Group and artifact you want.

1

  • Then Download by Click Button Generate Project, it will generate zip. file.

2. Unzip the project to your workspace, on Eclipse right-click import > Existing Maven Project.

2.jpg

What is Spring MVC Framewok?

1.) What is Spring MVC framework?

1.1.) Spring MVC provides Model, View and Controller Architecture.

        a. Model – Manages the Data, logic and rules of the Application.

        b. View – can be any output of representation information. JSP page written with the Java Standard Tag Library (JSTL).

        c. Controller – Accepts Input and convert it to commands for the Model or View. URL mapping and interact with service layer for business processing and return a Model.

user.jpg

1.2.) Spring MVC patterns results in separating diff aspects of the application ( input logic, business logic, and UI Logic) .

1.3.) Providing a loose coupling between model, vew & controller of Application.

1.4.) Spring is light weight and layer architecture framework which can be used to build complex enterprise applications.

1.5.) Spring Provides a front Controller Servlet named DispactherServlet. to build an Appl. Below description About DispatcherServlet.

  • One and More Controllers that invoke business logic and Create a ModelAndView Object.
  • A visualization components such as JSP.
  • XML or Annotation configuration to Wire the Components together. 

1.6.) Spring provides various controllers for you to use as base classes for creating your own controllers, depending on your needs. Below is the Descriptions:

  • Redirect to static views
  • Provide basic servlet-like functionality
  • Process commands
  • Process shared actions
  • Handle forms
  • Provide wizard-like functionality to process multipage forms

1.7.) Spring  MVC Architecture Diagram.

 

architecture_spring_mvc

=> Description on Spring MVC Diagram :

( 1 ) First Request will be received by DispatcherServlet.

( 2 ) DispatcherServlet will take the help Handler Mapping & Get to know the Controller Class name Associated with the Given Request , so request tranfer to the Controller.

( 3 ) Controller will process the request by executing appropriate methods & returns ModelAndView Object (Contains Model data & View Name) back to DispatcherServlet.

( 4 ) – The Front Controller then tries to resolve the View ( Which can be JSP, Free Marker, Velocity) by Consulting the Resolver Objects.

( 5 ) – The Selected View is then rendered.

( 6 ) – Rendered View Back to Client.

 

 

Spring MVC 4 + Hibernate 4.3.5.Final (Annotation) + JPA + MySql 5.5 – Example Project

1) Example on Maven 3 + Spring 4 (Spring MVC) + Hibernate 4.3.5.Final (Annotation) + JPA + MySQL 5.5  + java 8.

architecture_springMVC_hibernate_JPA_mysql.jpg

Architecture diagram above, is between Spring MVC + Hibernate + JPA + Mysql 5.5

1.1) For this example project , it used Data Access Object Pattern or DAO pattern in Domain layer.

1.2)  Based on Architecture diagram above, in JPA box, I used Hibernate ORM to integrate between table database.

  • Create table ‘user‘ and table ‘user_details‘, One-To-One Join Table.

CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
);

CREATE TABLE `user_details` (
`user_detail_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`address` VARCHAR(255),
`poscode` VARCHAR(10),
PRIMARY KEY (`user_detail_id`),
KEY `user_fk` (`user_id`),
CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
);

open CMD , and your folder  project , add this command and Enter :

mvn archetype:generate -DgroupId=<Your domain name> -DartifactId=<Project Name> -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

  • My Example: mvn archetype:generate -DgroupId=com.fndong -DartifactId=SpringMVCProjOne -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
  • If you check the result is : Build Success , its mean you are successfully create new web app project using maven.

2.) Then , Import the SpringMVCProjOne  maven project to your Eclipse Mars.

2.1) after importing , check your Build Path , some folder java are missing “src\main\java” and “src\test\java” , remove the missing , and Add new “Add Folder..” , create the two missing folder.

3) Check your pom.xml, add your dependencies jar files below:

Add Spring 4 + Hibernate 4.3.5.Final dependency in pom.xml.

  <properties>
<spring.version>4.0.1.RELEASE</spring.version>
<jdk.version>1.8</jdk.version>
<hib.version>4.3.5.Final</hib.version>
</properties>

<dependencies>

<!– Spring 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>

<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!– Hibernate framework –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version> ${hib.version}</version>
</dependency>

4) Then , check Maven Dependency in Web Deployment Assembly.

maven-depency_2.jpg

5.) For creating an entities , i’ll using generate entities using JPA.

5.1) If you creating an entity ,it doesn’t view the database connection , please make sure you enable JPA . ( for newbies – create JPA Project)

jpalink_2.jpg

  • the libraries in jpaLinkEclise :

jpaLink_4

 

5.2.) create package for entity “com.fndong.user.entities“, and add your User table and User_detail table Entity.

5.2.1.) Right-click the SpringMVCProjOne  project in the Project Explorer and select NEW > JPA Entities from Tables.

jpa_entities.jpg

  • unchecked the List generate classes in persistence.xml ( Because we will using Spring Autowired )

5.3.) Then , it will automatically generate classes entities User and User_details.

jpa_enties2.jpg

5.4.) User.java entity in “com.fndong.user.entities” :

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
@Entity
@NamedQuery(name=”User.findAll“, query=”SELECT u FROM User u“)
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name=”user_id“)
private int userId;

private String email;

private String name;

private String password;

//bi-directional many-to-one association to UserDetail
@OneToMany(mappedBy=”user“)
private List<UserDetail> userDetails;

public User() {
}

// getter and Setter …….

5.5.) UserDetail.java entity in “com.fndong.user.entities” :

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name=”user_details“)
@NamedQuery(name=”UserDetail.findAll“, query=”SELECT u FROM UserDetail u“)
public class UserDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name=”user_detail_id“)
private int userDetailId;

private String address;

private String poscode;

//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name=”user_id“)
private User user;

// getter and Setter …….

  • JPALink Plugin will automatically set for the tables that have join – one to Many.

@ManyToOne
@JoinColumn(name=”user_id“)
private User user;

  • JPA API that we have been use such as :
  • @Id annotation
  • @Collumn annotation
  • @JoinColumn annotation
  • @Table annotation
  • @NamedQuery annotation
  • @Entity annotation

 

6.0.) Create the DAO Interface and DAO Implementation “com.fndong.user.Dao” :

6.1.) Create User entity DAO Interface  in “com.fndong.user.Dao” , NEW > Interface > Name – UserDao > Finish .

package com.fndong.user.dao;

import com.fndong.user.entities.User;

public interface UserDao {
// Get / Search
public User getUserDatabyName(String username);

// create
public int create(User user);

// edit
public int updateUser(User user);
}

  • Dao Interface for User – UserDao.java, i have add Three Functions , 1. Search – getUserDatabyName(String username) 2. Add- Create(User user) , Edit – UpdateUser(User user).

6.2.) Create Dao Implementation where your you will add HQL – Hibernate SQL , This class is responsible to get data from a data source which can be database – UserDaoImpl.java.

createDaoImp;l.jpg

  • Above diagram is how you can add the interface UserDao for creating Dao Implementation – UserDaoImpl.java.

package com.fndong.user.dao;

import com.fndong.user.entities.User;

public class UserDaoImpl implements UserDao {

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#getUserDatabyName(java.lang.String)
*/
@Override
public User getUserDatabyName(String username) {
// TODO Auto-generated method stub
return null;
}

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#create(com.fndong.user.entities.User)
*/
@Override
public int create(User user) {
// TODO Auto-generated method stub
return 0;
}

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#updateUser(com.fndong.user.entities.User)
*/
@Override
public int updateUser(User user) {
// TODO Auto-generated method stub
return 0;
}

  • Above Dao Implemention automatically created method from Dao Interface.

7.) Lets creating Hibernate.cfg.xml in package – /src/main/resources (Hibernate ORM Mapping database – Annotation )

<?xml version=”1.0” encoding=”UTF-8“?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd“>
<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class“>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.password“>P@ssw0rd</property>
<property name=”hibernate.connection.url“>jdbc:mysql://localhost:3306/hibernate</property>
<property name=”hibernate.connection.username“>root</property>
<property name=”hibernate.dialect“>org.hibernate.dialect.MySQLDialect</property>
<property name=”cache.provider_class“>org.hibernate.cache.NoCacheProvider</property>
<property name=”show_sql“>true</property>
<property name=”hbm2ddl.auto“>validate</property>

<mapping class=”com.fndong.user.entities.User“/>
<mapping class=”com.fndong.user.entities.UserDetails“/>
</session-factory>
</hibernate-configuration>

cfg.jpg

8.) Create Hibernate SessionFactory class – HibernateUtil.java in new package “com.fndong.util“.

package com.fndong.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

@SuppressWarnings(“deprecation“)
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration()
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

9. Create Service layer …. to be continued

 

 

 

 

Create Simple Project Spring MVC

1.) Create your Web Spring MVC Project, I’ll Show how to create using maven command for Windows User :

  • Before that make sure you have download and install:
  • java 8 or 7
  • Eclipse Mars
  • Tomcat 8

open CMD , and your folder  project , add this command and Enter :

mvn archetype:generate -DgroupId=<Your domain name> -DartifactId=<Project Name> -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

  • My Example: mvn archetype:generate -DgroupId=com.fndong -DartifactId=HelloSpringMVC -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
  • If you check the result is : Build Success , its mean you are successfully create new web app project using maven.
  • Some info: If failed to download lib to local repository because your office Network PC have the proxy setting. To solve it by setting the setting.xml file and add in .m2 folder. You can get the setting.xml from maven Apache installer,  Enable proxy setting :

<proxies>
<!– proxy
| Specification for one proxy, to be used in connecting to the network.
|
–>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username></username>
<password></password>
<host>1**.**.**.**</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

</proxies>

2.) Then , Import the HelloSpringMVC  maven project to your Eclipse Mars.

2.1) after importing , check your Build Path , some folde java are missing “src\main\java” and “src\test\java“.

  • remove the missing , and Add new “Add Folder..

proj_7_1.jpg

3) Then Check the Error.

proj_7_2

  • This is occurred because missing HttpServlet, you can add dependencies or using Tomcat Server  lib Servlet, by add the project to Target Runtimes :   Target Runtimes > select Apache Tomcat 8
  • Then The Error will disappeared.

4) Create web.xml , Map Spring MVC in /Webapp/WEB-INF/web.xml file.

  • In web.xml will map org.springframework.web.servlet.DispatcherServlet with url pattern  <url-pattern>*.htm</url-pattern>.
  • The Name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml  in WEB-INF folder of web application.

<?xml version=1.0 encoding=UTF-8?><web-app version=3.0 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_3_0.xsd> <display-name>Archetype Created Web Application</display-name>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
</web-app>

5.) Create Spring Configuration Bean file. /Webapp/WEB-INF/mvc-dispatcher-servlet.xml

  • Description About mvc-dispatcher-servlet.xml: , mvc-dispatcher-servlet.xml configuration file, we have defined a tag <context:component-scan> . This will allow Spring to load all the components from package com.fndong.controller  and all its child packages.

<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 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.fndong.controller” />

<bean
class=”org.springframework.web.servlet.view.InternalResourceViewResolver“>
<property name=”prefix“>
<value>/WEB-INF/pages/</value>
</property>
<property name=”suffix“>
<value>.jsp</value>
</property>
</bean>
</beans>

6.) Add Spring dependency in pom.xml.

  <properties>
<spring.version>4.0.1.RELEASE</spring.version>
<jdk.version>1.8</jdk.version>
</properties> 

<dependencies>

<!– Spring 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>

7.) Make sure to add Maven dependencies, right click project > properties > Deployment Assembly > Add > Maven Dependencies

maven-depency.jpg

8.) Update your index.jsp , which one button will have action to go to others page – Hello.jsp.

<!DOCTYPE html>
<html>
<head>
http://span%20style=

$(document).ready(function(){
$(“p”).mouseover(function(){
$(“p”).css(“background-color“, “yellow“);
});
$(“p”).mouseout(function(){
$(“p”).css(“background-color“, “lightgray“);
});
});

<style>
.important {
font-weight: bold;
font-size: xx-large;
}

.blue {
color: blue;
}
</style>
</head>
<body>
<p><a href=”hello.htm“>Say Hello…</a></p></body>

9.) Hello.jsp ( for the second Page)

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1“%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd“>
<html>
<head>
text/javascript” src=”jquery-1.2.6.min.js“>
<title>Good Job</title>
</head> <body> <center>
<h2>Great To see You Man, Good Job</h2>
<h4>${message}</h4>
</center></body></html>

10.) Java Controller , HelloController.java.

package com.fndong.controller;

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

@Controller
public class HelloController {
String message = “Good Job Man !“;

@RequestMapping(“/hello“)
public ModelAndView showMessage() {
return new ModelAndView(“hello“, “message“, message);
}
}

11.) OUTPUT, Add to Server (deploy) Tomcat 8, then start the server.

say_hello.jpg

12) click Say Hello …,

result_21.jpg

13.) Full Source Code Project :

full_project_hello_world_spring.jpg

14.) Download This Project from my GitHub by click Download button below:

download