EASY_JAVA_RU Telegram 1925
🤔 Как на Java писать веб-приложение?

Веб-приложение на Java – это серверное приложение, которое обрабатывает HTTP-запросы и отправляет ответы клиенту.

🚩Написание веб-приложения на Spring Boot

Установка зависимостей (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!


🚩Разработка фронтенда (HTML + Thymeleaf)

Если приложение рендерит страницы на сервере, используйте 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"
}
}


🚩Работа с базой данных (Spring Data JPA + PostgreSQL)

Добавьте зависимости в 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


Ставь 👍 и забирай 📚 Базу знаний
Please open Telegram to view this post
VIEW IN TELEGRAM
👍12



tgoop.com/easy_java_ru/1925
Create:
Last Update:

🤔 Как на Java писать веб-приложение?

Веб-приложение на Java – это серверное приложение, которое обрабатывает HTTP-запросы и отправляет ответы клиенту.

🚩Написание веб-приложения на Spring Boot

Установка зависимостей (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!


🚩Разработка фронтенда (HTML + Thymeleaf)

Если приложение рендерит страницы на сервере, используйте 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"
}
}


🚩Работа с базой данных (Spring Data JPA + PostgreSQL)

Добавьте зависимости в 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


Ставь 👍 и забирай 📚 Базу знаний

BY Java | Вопросы собесов


Share with your friend now:
tgoop.com/easy_java_ru/1925

View MORE
Open in Telegram


Telegram News

Date: |

The SUCK Channel on Telegram, with a message saying some content has been removed by the police. Photo: Telegram screenshot. How to create a business channel on Telegram? (Tutorial) In 2018, Telegram’s audience reached 200 million people, with 500,000 new users joining the messenger every day. It was launched for iOS on 14 August 2013 and Android on 20 October 2013. “[The defendant] could not shift his criminal liability,” Hui said. Hashtags are a fast way to find the correct information on social media. To put your content out there, be sure to add hashtags to each post. We have two intelligent tips to give you:
from us


Telegram Java | Вопросы собесов
FROM American