I've been touching Java for a while at work, but I haven't had a chance to touch the trendy frameworks, but when I look at Spring Boot somehow, maybe this time it will take root as a standard framework. What? There is no loss to remember. I decided to touch it.
This is my first Spring Boot project creation, but since there is no other choice, it may be a standard, but I will start from here.
Project setting 2 For the time being, I just want to move it, so I chose only the template engine and the web Maybe I can add it later.
Creating a controller Controller is mainly used as a controller for Web pages. RestController is used in the controller for WebAPI that returns Json, XML, etc. However, I would like to try both. First, create it from RestController.
TestRest.java
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestRest {
@RequestMapping("/Rest")
public String Rest() {
return "This is Rest";
}
}
Try to run Select "Spring Boot Application" in Run
Try to access from a browser It seems that Tomcat is working, but can't find the controller I created? What on earth do you mean?
Try moving the RestController to the package where the Spring Boot Application is located
Access from the browser again For some reason, it worked! Does that mean that you can only create a controller under the Spring Application?
I will try to create a package under Spring Application.
TestRest.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestRest {
@RequestMapping("/Rest")
public String Rest() {
return "This is Rest. From the package under demo";
}
}
After all, that's right. Anyway, my understanding has improved a little. RestController should be about this. Proceed to the next. Let's use the template engine with Controller.
Create index.html in the "templates" folder.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>First Thymeleaf</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
Create "TestController.java" in com.example.demo.controller.
TestController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("message", "Thymeleaf has moved!");
return "index";
}
}
Recommended Posts