Spring Form Submission to PostgreSQL – Spring Boot

Spring Form Submission to PostgreSQL – Spring Boot

The tutorial will introduce you how to submit a web form to PostgreSQL database.

I. Technology for Spring Form Submission to PostgreSQL

– Java 1.8
– Maven: 3.3.9
– Editor: Spring Tool Suite – Version 3.7.3.RELEASE
– Spring Boot: Version: 3.8.0.RELEASE

II. Overview
1. Struct of Project

spring form submission to postgresql structure

2. Step to do

– Create Spring Boot project
– Configure datasource
– Create a Data Model
– Create a Repository
– Create a Web Controller
– Create web views
– Create database table
– Run & Enjoy result

3. Demo Video
III. Practices
1. Create Spring Boot project

Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, input info as below picture:

spring form submission to postgresql -  createproject

Press Next button. Now add needed dependencies:

– For Spring Web MVC, choose Web then select Web
– For Thymeleaf view technologies, choose Template Engines then select Thymeleaf
– For JPA and Postgresql, choose SQL then select JPA and PostgresSQL.
Follow images:

spring form submission to postgresql -  createproject - add dependencies

Then Press Finish. Spring boot project is created successful.
Open pom.xml for check dependencies:


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web



          org.springframework.boot
          spring-boot-starter-data-jpa
      
      

    org.postgresql
    postgresql

2. Configure datasource

Open application.properties, configure datasource:

spring.datasource.url=jdbc:postgresql://localhost/testdb
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.generate-ddl=true
3. Create a Data Model

Create a simple data model: Customer.java

@Entity:Specifies that the class is an entity. This annotation is applied to the
entity class.
@Table:Specifies the primary table for the annotated entity.
@Id:Specifies the primary key of an entity.
@Column:Is used to specify the mapped column for a persistent property or field.

package com.javasampleapproach.formhandler.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer implements Serializable{
	
	private static final long serialVersionUID = -3009157732242241606L;
	@Id
    //@GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    
    @Column(name = "firstname")
    private String firstname;
    
    @Column(name = "lastname")
    private String lastname;

    public void setId(long id){
    	this.id = id;
    }
    
    public long getId(){
    	return id;
    }
    
    public void setFirstname(String firstName){
    	this.firstname = firstName;
    }
    
    public String getFirstname(){
    	return this.firstname;
    }
    
    public void setLastname(String lastName){
    	this.lastname = lastName;
    }
    
    public String getLastname(){
    	return this.lastname;
    }
    
    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstname = firstName;
        this.lastname = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstname, lastname);
    }
}
4. Create a Repository

interface CrudRepository: Interface for generic CRUD operations on a repository for a specific type.

package com.javasampleapproach.formhandler.repo;

import org.springframework.data.repository.CrudRepository;
import com.javasampleapproach.formhandler.model.Customer;

public interface CustomerRepository extends CrudRepository {}
5. Create a Web Controller

Create SimpleWebController with 3 @RequestMapping
– @RequestMapping(value=”/form”, method=RequestMethod.GET): get input form
– @RequestMapping(value=”/form”, method=RequestMethod.POST): submit input form to postgresql
– @RequestMapping(value=”/load”, method=RequestMethod.GET): load customer from postgresql then shows on web.

package com.javasampleapproach.formhandler.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.javasampleapproach.formhandler.model.Customer;
import com.javasampleapproach.formhandler.repo.CustomerRepository;



@Controller
public class SimpleWebController {

	@Autowired
	CustomerRepository customerRepository;
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
    @RequestMapping(value="/form", method=RequestMethod.GET)
    public String customerForm(Model model) {
        model.addAttribute("customer", new Customer());
        return "form";
    }

    @RequestMapping(value="/form", method=RequestMethod.POST)
    public String customerSubmit(@ModelAttribute Customer customer, Model model) {
    	
        model.addAttribute("customer", customer);
        String info = String.format("Customer Submission: id = %d, firstname = %s, lastname = %s", 
        								customer.getId(), customer.getFirstname(), customer.getLastname());
        log.info(info);
        customerRepository.save(customer);
                
        return "result";
    }
    
    @RequestMapping(value="/load", method=RequestMethod.GET)
    public String customerSubmit(@RequestParam("id") long id, Model model) {
    	
        Customer customer = customerRepository.findOne(id);
        model.addAttribute("customer", customer);
        
        return "load";
    }
    
}
6. Create web views

For each @RequestMapping, we create a html view:
form.html: create a form for input customer info.




    Form Submission
    


	

Customer Form

Id:

%MINIFYHTMLd4c600970d519759dc5b296aa5504b3518% %MINIFYHTMLd4c600970d519759dc5b296aa5504b3519%

First Name:

Last Name:

%MINIFYHTMLd4c600970d519759dc5b296aa5504b3520%

result.html: create a notified view after submit customer form.




    
    


	

SUBMIT SUCCESSFUL

Submit another Customer Form

load.html: create a view that displays info of a customer form database.




    Customer Info
    


    

7. Create database table

Open pgAmin III , and create customer table as below sql:

DROP TABLE IF EXISTS customer;
  
CREATE TABLE customer (
    ID Bigserial PRIMARY KEY NOT NULL,
    FIRSTNAME varchar(100) NOT NULL,
    LASTNAME varchar(100) NOT NULL
);

spring form submission to postgresql-form customer - sql

Now customer table is created succesfully.

spring form submission to postgresql-form customer - create table successful

8. Run & Enjoy result

Maven Build :
clean install

Maven Run as mode: Spring Boot App
Make request:
http://localhost:8080/form

Input info, then press Submit:

spring form submission to postgresql-form customer

Result

– On Web:
spring form submission to postgresql -  submit successful

– Check Database:

spring form submission to postgresql-form customer - table

Request:
http://localhost:8080/load?id=10

Result:

spring form submission to postgresql -  load result

IV. Source code

springformhandler



By grokonez | August 29, 2016.

Last updated on June 4, 2017.



Related Posts


9 thoughts on “Spring Form Submission to PostgreSQL – Spring Boot”

  1. hi, this is eli, all the way from Kenya. wanna thank you for this great tutorial. i used it to build on my knowledge about linking my app with the db. i have tried with different databases and it works perfectly.
    thanks alot.
    keep them comming

    1. Hi Eli,

      Thank you so much for your feedback 🙂
      We’re on the way to make this Site more useful for all of you.

      Best Regard!

      1. hi, i need some help with making updates to my table entries.
        (both back-end and front-end) of the application, with refence to this tutorial.
        Any help is appreciated.
        Regards.

  2. Hi !
    Could you please specify where to create webviews in the project structure ?
    (Sorry for the trivial question, I’m a beginner).

  3. Hi
    I have try this tutorial with eclipse, but there is no customerRepository.findOne() method ?
    can you explain that ?
    Thank you

  4. Hi,

    Hi,

    Why inserts dont work with schemas?

    @Table(name = “customer”, schema=”xxx”)

    And without “schema” worked.

    tks

  5. currency-trading-brokers.com/forex-comparisons-ratings-reviews-czechia.html Žebříček-posuzování-evaluace regulovaných forex společností.

  6. zWSBwARzghrMouWSc4BJhu3eddaXYyU6
    jAAwNH9rGZgrUlGXAGMpeGRyy2y1DF92
    jYlZg2APzNz6GrZ9Mh9RWyg4bba5mrK7
    RAQEJq6a0TUNpEiqvudK83az2Udb4YXg
    ED0CeJDDEjFgaSS0GBJYunPmgLyk6yLb

  7. K4qt83F8gheQueFxLnPl0KDU8eMak5Z1
    e6X7YNmK8az9QFeJqQ3Kcw2PU2WS0Ac7
    Ymrd3G9u0wTDPfkcGs8PnNDYuj7sfS5w
    9UDplfiW13EWO0oLXHWSGYS7ARuGbvTw
    NmAEG1o7OYv4iMGYDiFSqBWzW0Q0p0Lt

Got Something To Say:

Your email address will not be published. Required fields are marked *

*