Spring Form Submission to PostgreSQL – Spring Boot
The tutorial will introduce you how to submit a web form to PostgreSQL database.
Contents
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
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:
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:
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.
%MINIFYHTMLd4c600970d519759dc5b296aa5504b3520%Form Submission Customer Form
– 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 );
Now customer table is created succesfully.
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:
Result
– On Web:
– Check Database:
Request:
http://localhost:8080/load?id=10
Result:
IV. Source code
Last updated on June 4, 2017.
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
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!
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.
Hi !
Could you please specify where to create webviews in the project structure ?
(Sorry for the trivial question, I’m a beginner).
Hi
I have try this tutorial with eclipse, but there is no customerRepository.findOne() method ?
can you explain that ?
Thank you
Hi,
Hi,
Why inserts dont work with schemas?
@Table(name = “customer”, schema=”xxx”)
And without “schema” worked.
tks
currency-trading-brokers.com/forex-comparisons-ratings-reviews-czechia.html Žebříček-posuzování-evaluace regulovaných forex společností.
zWSBwARzghrMouWSc4BJhu3eddaXYyU6
jAAwNH9rGZgrUlGXAGMpeGRyy2y1DF92
jYlZg2APzNz6GrZ9Mh9RWyg4bba5mrK7
RAQEJq6a0TUNpEiqvudK83az2Udb4YXg
ED0CeJDDEjFgaSS0GBJYunPmgLyk6yLb
K4qt83F8gheQueFxLnPl0KDU8eMak5Z1
e6X7YNmK8az9QFeJqQ3Kcw2PU2WS0Ac7
Ymrd3G9u0wTDPfkcGs8PnNDYuj7sfS5w
9UDplfiW13EWO0oLXHWSGYS7ARuGbvTw
NmAEG1o7OYv4iMGYDiFSqBWzW0Q0p0Lt