Spring Boot with Thymeleaf

Spring Boot makes it simple to build web application without adding too much configuration. Here I have taken example of Spring Boot, ThemeLeaf and Hibernate.

Project Structure

Project is divided into three layers Service,Controller and View.

SpringBoot Example
SpringBoot

Project Dependency

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
      	 	 <groupId>org.apache.tomcat.embed</groupId>
      	 	 <artifactId>tomcat-embed-jasper</artifactId>
    	</dependency>
     <dependency>
   		 <groupId>javax.servlet</groupId>
   		 <artifactId>jstl</artifactId>
   	 	<scope>provided</scope>
	</dependency>
	<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
	
    </dependencies>

Spring Boot

Annotate one of the class with @SpringBootApplication to run your web application. No need external tomcat to run your application, it is already embedded. You only need to execute this class as java application.


package com.startwithjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class SpringBootExample {
public static void main(String[] args) {
SpringApplication.run(SpringBootExample.class, args);
}
}

CrudRepository

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. The CrudRepository interface provides the CRUD functionality for the entity class.

Methos of CrudRepository Interface

  1. save()
  2. findAll()
  3. findOne()
  4. delete()
  5. count()
  6. exists()

ProductRepository.java

This interface extended CrudRepository for acts as DAO to perform database operations. At runtime Spring Boot generates the implemented class for the same.


package com.startwithjava.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.startwithjava.beans.Product;

public interface ProductRepository extends CrudRepository<Product, Long>{

}

ProductController.java

package com.startwithjava.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.startwithjava.beans.Category;
import com.startwithjava.beans.Product;
import com.startwithjava.services.ProductService;

@Controller
public class ProductController {
	@Autowired
	ProductService productService;
	
	@RequestMapping("/")
	public ModelAndView index(Pageable pageRequest){
		List<Category> categories = (List<Category>) productService.getAllCategories();
		List<Product>  products   = productService.findAll();
		ModelAndView mav = new ModelAndView();
		mav.setViewName("productindex");
		mav.addObject("name", "By StartWithJava");
		mav.addObject("categories", categories);
		mav.addObject("product",new Product());		
		mav.addObject("products",products);
		return mav;
	}
	@RequestMapping(value="/products/add",method=RequestMethod.POST)
	public String add(@ModelAttribute("product")Product product){
		productService.saveOrUpdate(product);
		return "redirect:/";
	}
}

ProductService.java

package com.startwithjava.services;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.startwithjava.beans.Category;
import com.startwithjava.beans.Product;
public interface ProductService {
	public void saveOrUpdate(Product product);
	public List<Product> findAll();
	public Product getProductById(long productId);
	public void removeProduct(Product product);
	public List<Category> getAllCategories();
}

ProductServiceImpl.java

package com.startwithjava.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.startwithjava.beans.Category;
import com.startwithjava.beans.Product;
import com.startwithjava.repository.CategoryRespository;
import com.startwithjava.repository.ProductRepository;
@Service
public class ProductServiceImpl implements ProductService{
	@Autowired
	ProductRepository productRepository;
	
	@Autowired
	CategoryRespository categoryRepository;
	
	@Override
	public void saveOrUpdate(Product product) {
		productRepository.save(product);
	}

	@Override
	public Product getProductById(long productId) {
		return productRepository.findOne(productId);
	}

	@Override
	public void removeProduct(Product product) {
		productRepository.delete(product.getId());
	}
	
	@Override
	public List<Category> getAllCategories(){
		if(categoryRepository.findAll().iterator().hasNext()) {
			return (List<Category>)categoryRepository.findAll();
		}
		return null;
	}

	@Override
	public List<Product> findAll() {
		if(productRepository.findAll().iterator().hasNext()) {
		return (List<Product>) productRepository.findAll();
		}
		else {
			return null;
		}
	}

}

Demo

Spring Boot Output

Download Source Code

Download Spring Boot Example

Leave a Reply