Java Programming

Quickstart Spring MVC

Tạo Databaes

CREATE DATABASE WebStore;
GO
USE WebStore;
GO

Create Project Spring Mvc

Truy cập vào link https://start.spring.io/ để tạo project Spring Mvc

Sau khi truy cập vào link tạo project theo cấu hình như sau

ProjectMaven
LanguageJava
Spring Boot3.4.0
GroupWebStore
ArtifaceWebStore
NameWebStore
Package namewebapp
Packingjar
Java22
DependenciesSpring Boot DevTools
Spring Web
Thymeleaf
Spring Data JPA
MS SQL Server Driver

Configuration database

Vào src/main/resources/application.properties, thêm vào nội dung sau để khai báo kết nối đến CSDL SQL Server

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=WebStore;TrustServerCertificate=true;
spring.datasource.username=sa
spring.datasource.password=123
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql: true
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Lưu ý trong đọn code trên ta kết nối đến Sql Server với username là sa và password=123, tên CSDL là WebStore

Tạo HomeController

Trong thư mục main/java/webapp tạo thêm 2 thư mục là controllersmodels

Sau đó ta tạo HomeControler với nội dung như sau:

@Controller
public class HomeController {
    @GetMapping("/")
    public String index() {
        return "home/index";
    }
}

Tạo view cho action index trong controller HomeControler

Vào thư mục main/resoures/templates tạo thư mục home và file index.html trong thư mục home

Trong file index.html tao đặt nội dung bất kỳ ví dụ

<h2>Welcome Ladies and Gentlemen</h2>