[JAVA] Create an app with Spring Boot 2

Continuation of the last time. https://qiita.com/YJ2222/items/8c29fc7fc2d886a9b35e

File creation

-Create the necessary files. Create by referring to the image below and "Explanation of each file".  1.png

-Description of each file.

Write the code in the created file.

templates/userResult.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>User</title>
</head>
<body>
    <h1>UserResult</h1>
    <table>
        <tr>
        	<!-- th:text can be getAttribute using the function of thymeleaf.-->>
            <td>ID:</td><td th:text="${id}"></td>
        </tr>
        <tr>
            <td>nickname:</td><td th:text="${nickname}"></td>
        </tr>
    </table>
<body>
</html>

controller/UserController.java



package com.ex1.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ex1.model.User;
import com.ex1.model.UserFindLogic;

@Controller
public class UserController {
	
	@Autowired //Dependency injection.
	private UserFindLogic userFindLogic;

	@GetMapping("/")
	    public String getUser() {
	        return "user";
    }
	// user.Processing of post from html.@Get the value of name with RequestParam.
	@PostMapping("/user/db")
	public String postDbRequest(@RequestParam("text") String str, Model model) {
		
		int id = Integer.parseInt(str); //String conversion.
		//Without new UserFindLogic@Since the dependency is injected by Autowired, UserFindLogic can be executed as User type.
        User user = userFindLogic.findUser(id); // UserFindLogic.Execute the findUser method of java.
        // UserFindLogic.After receiving the return value from java, execute the following.
        model.addAttribute("id", user.getUserId()); //SetAttribute user information.
        model.addAttribute("nickname", user.getNickName());
        
        return "userResult"; // userResult.Forward to html.
    }
	
}


model/UserFindLogic.java



package com.ex1.model;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ex1.dao.UserDAO;

@Service //Annotation given to business logic.
public class UserFindLogic {
	
	@Autowired
	private UserDAO userDAO;
	
	public User findUser(int id) { //Execute the method according to the instruction from the controller.
		
		Map<String, Object> map = userDAO.findUser(id); //Execute findUser of UserDAO.
		//Receive a user variable from DAO.
        int userId = (Integer) map.get("user_id"); //Decompose the received variable with map.Get information with get.
        String nickName = (String) map.get("nickname");

		User user = new User(); //Create user instance (User.java)
		user.setUserId(userId); //Run setter.
		user.setNickName(nickName);
				
		return user; //Return the user instance to controller as a return value.
	}
}


model/User.java



package com.ex1.model;

public class User {
	private int userId;
    private String nickName;    
    
    public void setUserId(int userId) {
    	this.userId = userId;
    }
    
    public void setNickName(String nickName) {
    	this.nickName = nickName;
    }
    
    public int getUserId() {
    	return userId;
    }
    
    public String getNickName() {
    	return nickName;
    }
}

dao/UserDAO.java



package com.ex1.dao;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository //Annotation given to DAO class.
public class UserDAO {
	@Autowired 
    private JdbcTemplate jdbcTemplate; //Instance that can connect to DB.

    public Map<String, Object> findUser(int id) { // UserFindLogic.Execute the method according to the instruction of java.

        //Generate SELECT statement
        String query = "SELECT "
                + " * "
                + "FROM account "
                + "WHERE user_id=?";

        //Execute SQL for DB by the function of jdbcTemplate.
        Map<String, Object> user = jdbcTemplate.queryForMap(query, id);

        return user; //UserFindLogic for the above processing result.Return to java as a return value.
    }
}

templates/userResult.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>User</title>
</head>
<body>
    <h1>UserResult</h1>
    <table>
        <tr>
            <td>ID:</td><td th:text="${id}"></td>
        </tr>
        <tr>
            <td>nickname:</td><td th:text="${nickname}"></td>
        </tr>
    </table>
<body>
</html>

src/main/resources/application.properties



spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasouce.username=sa
spring.datasouce.password=
spring.datasource.sql-script-encoding=UTF-8
spring.h2.console.enabled=true
spring.datasource.initialize=true
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql

src/main/resources/data.sql



INSERT INTO account (user_id, nickname, password) VALUES (1, 'user1', 'user1+');

src/main/resources/schema.sql



CREATE TABLE IF NOT EXISTS account (
    user_id INT PRIMARY KEY,
    nickname VARCHAR(50),
    password VARCHAR(50)
);

-The process flow is easy to imagine by referring to the comment section of the code and the image below. 3.png

that's all. Now you can even connect to the DB in your local environment.

Recommended Posts

Create an app with Spring Boot 2
Create an app with Spring Boot
Create microservices with Spring Boot
Create a simple search app with Spring Boot
Create Restapi with Spring Boot ((1) Until Run of App)
Download with Spring Boot
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create CRUD apps with Spring Boot 2 + Thymeleaf + MyBatis
Create your own Utility with Thymeleaf with Spring Boot
Create Spring Boot environment with Windows + VS Code
Create a web api server with spring boot
Create a Spring Boot development environment with docker
Create Spring Cloud Config Server with security with Spring Boot 2.0
Create a Spring Boot app development project with the cURL + tar command
Generate barcode with Spring Boot
Hello World with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
[Spring Boot] Send an email
Send email with spring boot
Create a simple demo site with Spring Security with Spring Boot 2.1
Hello World (console app) with Apache Camel + Spring Boot 2
Create an immutable class with JAVA
Use Basic Authentication with Spring Boot
gRPC on Spring Boot with grpc-spring-boot-starter
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
Create a Hello World web app with Spring framework + Jetty
Create an excel file with poi
(Intellij) Hello World with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Create command line app with maven
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Create an app catalog site using CLI for Microsoft 365 with Docker
I implemented an OAuth client with Spring Boot / Security (LINE login)
How to create your own Controller corresponding to / error with Spring Boot
Image Spring Boot app using jib-maven-plugin and start it with Docker
Processing at application startup with Spring Boot
Create Spring Boot development environment on Vagrant
Let's create an instance with .new yourself. .. ..
Create an infinite scroll with Infinite Scroll and kaminari