tgoop.com/easy_java_ru/1925
Create:
Last Update:
Last Update:
Веб-приложение на Java – это серверное приложение, которое обрабатывает HTTP-запросы и отправляет ответы клиенту.
Установка зависимостей (Maven)
Создайте pom.xml и добавьте
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.2.2</version> <!-- Используйте актуальную версию -->
</dependency>
</dependencies>
Создание основного класса (точка входа)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyWebApp {
public static void main(String[] args) {
SpringApplication.run(MyWebApp.class, args);
}
}
Создание контроллера (обработка HTTP-запросов)**
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Привет, это веб-приложение на Java!";
}
}
Теперь при открытии
http://localhost:8080/api/hello сервер вернёт: Привет, это веб-приложение на Java!
Если приложение рендерит страницы на сервере, используйте Thymeleaf.
Добавьте зависимость в
pom.xml<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Создайте HTML-шаблон (
src/main/resources/templates/index.html)<!DOCTYPE html>
<html>
<head>
<title>Главная страница</title>
</head>
<body>
<h1>Привет, <span th:text="${name}"></span>!</h1>
</body>
</html>
Создайте контроллер для отображения страницы
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WebController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("name", "Гость");
return "index"; // Возвращает "index.html"
}
}
Добавьте зависимости в
pom.xml<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
Настройте
application.properties (подключение к БД)spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
Создайте сущность (таблицу в БД)
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Геттеры и сеттеры
}
Создайте
Repository для работы с БДimport org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Контроллер для работы с БД
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping
public List<User> getUsers() {
return userRepository.findAll();
}
@PostMapping
public User addUser(@RequestBody User user) {
return userRepository.save(user);
}
}
Запустите приложение:
mvn spring-boot:run
Проверьте API через браузер или Postman
http://localhost:8080/users
Ставь 👍 и забирай 📚 Базу знаний
