Lab5: Finished

This commit is contained in:
Katerina881 2023-04-18 13:02:39 +04:00
parent 4410a17fcf
commit 5af0868021
15 changed files with 424 additions and 13 deletions

View File

@ -49,6 +49,10 @@ public class CommentDto {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCustomerName() {
return customerName;
@ -58,6 +62,10 @@ public class CommentDto {
return postId;
}
public void setPostId(long postId) {
this.postId = postId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPostTitle() {return postTitle;}
@ -75,4 +83,19 @@ public class CommentDto {
public String getCreateDate() {
return createDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CommentDto that = (CommentDto) o;
return id == that.id;
}
@Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
}

View File

@ -3,8 +3,8 @@ package np.something.DTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import np.something.model.Post;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class PostDto {
@ -13,7 +13,7 @@ public class PostDto {
public String content;
public String customerName;
public long customerId;
public List<CommentDto> comments;
public ArrayList<CommentDto> comments;
public String createDate;
@ -27,7 +27,7 @@ public class PostDto {
this.content = post.getContent();
this.customerName = post.getCustomer().getUsername();
this.customerId = post.getCustomer().getId();
this.comments = post.getComments().stream().map(CommentDto::new).toList();
this.comments = new ArrayList<>(post.getComments().stream().map(CommentDto::new).toList());
this.createDate = post.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
@ -48,7 +48,7 @@ public class PostDto {
return content;
}
public void setContent() {
public void setContent(String content) {
this.content = content;
}
@ -66,6 +66,10 @@ public class PostDto {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCreateDate() {
return createDate;

View File

@ -0,0 +1,61 @@
package np.something.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import np.something.DTO.CustomerDto;
import np.something.services.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/admin")
public class Admin {
private final CustomerService customerService;
public Admin(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping(value = { "/", "/{id}" })
public String getCustomers(@PathVariable(required = false) Long id, HttpServletRequest request, HttpSession session, Model model) {
model.addAttribute("request", request);
model.addAttribute("session", session);
if (id == null || id <= 0) {
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());
return "admin";
} else {
return "redirect:/customers/" + id;
}
}
@PostMapping("/delete/{id}")
public String deleteCustomer(@PathVariable Long id, HttpSession session) {
session.setAttribute("currentCustomerId", -1);
customerService.deleteCustomer(id);
return "redirect:/admin/";
}
@PostMapping(value = { "/", "/{id}"})
public String manipulateCustomer(@PathVariable(required = false) Long id, @ModelAttribute @Valid CustomerDto customerDto,
HttpServletRequest request, HttpSession session,
BindingResult bindingResult,
Model model) {
model.addAttribute("request", request);
model.addAttribute("session", session);
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "/admin";
}
if (id == null || id <= 0) {
customerService.addCustomer(customerDto.username, customerDto.password);
} else {
customerService.updateCustomer(id, customerDto.username, customerDto.password);
}
return "redirect:/admin/";
}
}

View File

@ -50,6 +50,6 @@ public class Comments {
@PostMapping("/delete/{id}")
public String deleteComment(@PathVariable Long id) {
commentService.deleteComment(id);
return "redirect:/feed/";
return "redirect:/feed";
}
}

View File

@ -33,7 +33,8 @@ public class Customers {
}
@PostMapping("/delete/{id}")
public String deleteCustomer(@PathVariable Long id) {
public String deleteCustomer(@PathVariable Long id, HttpSession session) {
session.setAttribute("currentCustomerId", -1);
customerService.deleteCustomer(id);
return "redirect:/customers/";
}

View File

@ -2,28 +2,69 @@ package np.something.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import np.something.DTO.CommentDto;
import np.something.DTO.CustomerDto;
import np.something.DTO.PostDto;
import np.something.model.Post;
import np.something.services.CommentService;
import np.something.services.CustomerService;
import np.something.services.PostService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Controller
@RequestMapping("/feed")
public class Feed {
private final PostService postService;
private final CustomerService customerService;
public Feed(PostService postService) {
private final CommentService commentService;
public Feed(PostService postService, CustomerService customerService, CommentService commentService) {
this.postService = postService;
this.customerService = customerService;
this.commentService = commentService;
}
@GetMapping
public String getPosts(HttpServletRequest request, HttpSession session, Model model) {
public String getPosts(@RequestParam(required = false) String search, HttpServletRequest request, HttpSession session, Model model) {
model.addAttribute("request", request);
model.addAttribute("session", session);
if (search == null) {
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
} else {
var posts = new ArrayList<>(postService.searchPosts(search));
var comments = commentService.searchComments(search);
for (var post: posts) {
post.getComments().clear();
}
for (var comment: comments) {
boolean found = false;
for (var post: posts) {
if (Objects.equals(comment.getPost().getId(), post.getId())) {
post.getComments().add(comment);
found = true;
break;
}
}
if (!found) {
var newPost = comment.getPost();
newPost.getComments().clear();
newPost.getComments().add(comment);
posts.add(newPost);
}
}
model.addAttribute("posts", posts.stream().map(PostDto::new).toList());
}
model.addAttribute("customers", customerService.findAllCustomers().stream().map(CustomerDto::new).toList());
return "/feed";
}

View File

@ -51,6 +51,6 @@ public class Posts {
postService.updatePost(id, postDto.title, postDto.content);
}
return "redirect:/feed/";
return "redirect:/feed";
}
}

View File

@ -2,6 +2,12 @@ package np.something.repositories;
import np.something.model.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> {
@Query("SELECT DISTINCT c FROM Comment c WHERE c.content LIKE %:tag%")
List<Comment> searchComments(@Param("tag") String tag);
}

View File

@ -1,7 +1,14 @@
package np.something.repositories;
import np.something.model.Comment;
import np.something.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface PostRepository extends JpaRepository<Post, Long> {
@Query("SELECT DISTINCT p FROM Post p WHERE p.title LIKE %:tag% OR p.content LIKE %:tag%")
List<Post> searchPosts(@Param("tag") String tag);
}

View File

@ -66,4 +66,9 @@ public class CommentService {
public void deleteAllComments() {
commentRepository.deleteAll();
}
@jakarta.transaction.Transactional
public List<Comment> searchComments(String tag) {
return commentRepository.searchComments(tag);
}
}

View File

@ -68,4 +68,9 @@ public class PostService {
public void deleteAllPosts() {
postRepository.deleteAll();
}
@Transactional
public List<Post> searchPosts(String tag) {
return postRepository.searchPosts(tag);
}
}

View File

@ -0,0 +1,103 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="row">
<div class="col">
<div class="row mb-5">
<p class='is-center h2'>Профили</p>
</div>
<div class="row mb-5">
<div class="col"></div>
<div class="col-10 is-center">
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
</div>
<div class="col"></div>
</div>
<p class='h3 is-center row mb-5'>Список профилей</p>
<div class="row">
<div class="col">
<div class="row card mb-3">
<div class="row">
<div class="col-3 is-left h3 fw-bold" th:text="ID"></div>
<div class="col-3 is-center h3 fw-bold" th:text="Никнейм"></div>
<div class="col-3 is-right h3 fw-bold" th:text="Пароль"></div>
<div class="col-2"></div>
<div class="col-1"></div>
</div>
</div>
<div th:each="customer: ${customers}" class="row card mb-3">
<div class="row">
<div class="col-3 is-left h3" th:text="${customer.id}"></div>
<a th:href="${ '/customers/' + customer.id}" class="col-3 is-center h3" th:text="${customer.username}"></a>
<div class="col-3 is-right h3" th:text="${customer.password}"></div>
<button style="max-width: 66px; max-height: 38px;" th:data-username="${customer.username}" th:data-password="${customer.password}" th:data-id="${customer.id}" th:onclick="|prepareEditModal(this)|" class="button primary outline is-right" data-bs-toggle="modal" data-bs-target="#customerEdit"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<form th:action="@{/admin/delete/{id}(id=${customer.id})}" method="post" class="col-1 is-right">
<button class="button dark outline is-right" style="max-width: 66px; max-height: 38px;" type="submit"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="modal-content" th:action="@{/admin/}" method="post">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" id="usernameTextC" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" id="passwordTextC" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="modal-content" id="edit-customer-form" method="post">
<div class="modal-header">
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Изменить</button>
</div>
</form>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function prepareEditModal(btn) {
document.getElementById('usernameTextE').value = btn.getAttribute("data-username");
document.getElementById('passwordTextE').value = btn.getAttribute("data-password");
document.getElementById('edit-customer-form').setAttribute('action', '/admin/' + btn.getAttribute("data-id"));
}
</script>
</th:block>
</html>

View File

@ -51,7 +51,7 @@
<form th:action="@{/customers/delete/{id}(id=${customer.id})}" method="post" class="col">
<button class="button dark outline is-full-width" type="submit">Удалить</button>
</form>
<button th:onclick="|document.getElementById('edit-customer-form').setAttribute('action', '/customers/' + ${customer.id})|" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
<button th:data-username="${customer.username}" th:data-password="${customer.password}" th:data-id="${customer.id}" th:onclick="|prepareEditModal(this)|" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
</div>
</div>
</div>
@ -101,4 +101,13 @@
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function prepareEditModal(btn) {
document.getElementById('usernameTextE').value = btn.getAttribute("data-username");
document.getElementById('passwordTextE').value = btn.getAttribute("data-password");
document.getElementById('edit-customer-form').setAttribute('action', '/customers/' + btn.getAttribute("data-id"));
}
</script>
</th:block>
</html>

View File

@ -6,6 +6,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<title>Социальная сеть</title>
</head>
<body class="container">
@ -13,8 +14,8 @@
<div>
<div class="nav row">
<div class="nav-left col-10" th:with="activeLink=${request.requestURI}">
<a href="/customers" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Профили</a>
<a href="/posts" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/posts')} ? 'clear' : ''">Посты</a>
<a href="/customers/" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Профили</a>
<a href="/feed" class="button primary" th:classappend="${#strings.startsWith(activeLink, '/feed')} ? 'clear' : ''">Посты</a>
</div>
<div class="nav-right col-2">
<select class="form-select" style="font-size: 16px;" th:onchange="updateSession()" id="selectBox">

View File

@ -4,7 +4,152 @@
</head>
<body>
<div layout:fragment="content">
<div class="row">
<div class="col">
<div class="row mb-5">
<p class='is-center h2'>Посты</p>
</div>
<form class="row mb-5" action="/feed">
<input type="search" name="search" class="col-10">
<button class="button primary col" type="submit">Найти</button>
</form>
<div class="row mb-5" th:if="${session.currentCustomerId > 0}">
<div class="col"></div>
<form class="col-10" th:action="@{/posts/}" method="post">
<input name="customerId" type="text" style="display: none;" th:value="${session.currentCustomerId}">
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input name="title" type="text" class="col-6" id="createPostTitle" />
</div>
<div class="row mb-4 is-center">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea name="content" type="textarea" class="col-6" id="createPostContent"></textarea>
</div>
<div class="row is-center">
<button type='submit' class="button primary col-8">
Опубликовать
</button>
</div>
</form>
<div class="col"></div>
</div>
<div th:unless="${#arrays.isEmpty(posts)}" class="row">
<div class="col">
<div class="row mb-5 card" th:each="post: ${posts}">
<div class="col">
<div class="row h3">
<div class="col is-left">
<p>Автор: <a th:href="${'/customers/' + post.customerId}" class="text-primary" th:text="${post.customerName}"></a></p>
</div>
<div class="col is-right">
<p>Дата: <span class="text-primary" th:text="${post.createDate}"></span></p>
</div>
</div>
<div class="row text-center">
<span class="h1" th:text="${post.title}"></span>
</div>
<div class="row text-center mb-5">
<span class="h3" th:text="${post.content}"></span>
</div>
<div class="row">
<div class="col">
<p class="row h2 is-center mb-3">Комментарии</p>
<div th:unless="${#arrays.isEmpty(post.comments)}" class="row text-left mb-5 card" th:each="comment: ${post.comments}">
<div class="row mb-1">
<div class="col is-left">
<span class="h2 text-primary" th:text="${comment.customerName}"></span>
</div>
<div class="col is-right">
<span class="h2 text-primary" th:text="${comment.createDate}"></span>
</div>
</div>
<div class="row mb-3">
<span class="h3" th:text="${comment.content}"></span>
</div>
<div th:if="${session.currentCustomerId == comment.customerId}" class="row">
<button th:data-content="${comment.content}" th:data-id="${comment.id}" th:onclick="|prepareCommentEditModal(this)|" class="button primary outline col" data-bs-toggle="modal" data-bs-target="#commentEdit">Изменить комментарий</button>
<form th:action="@{/comments/delete/{id}(id=${comment.id})}" method="post" class="col">
<button type="submit" class="button error is-full-width">Удалить комментарий</button>
</form>
</div>
</div>
<p th:if="${#arrays.isEmpty(post.comments)}" class="h3 row is-center mb-5">Пусто</p>
<form class="row" th:if="${session.currentCustomerId != -1}" th:action="@{/comments/}" method="post">
<input name="content" type="text" class="col-9"/>
<input name="customerId" type="text" style="display: none;" th:value="${session.currentCustomerId}">
<input name="postId" type="text" style="display: none;" th:value="${post.id}">
<button type="submit" class="button col-3 secondary outline">Комментировать</button>
</form>
</div>
</div>
<div class="row" th:if="${session.currentCustomerId == post.customerId}">
<form class="col" th:action="@{/posts/delete/{id}(id=${post.id})}" method="post">
<button type="submit" class="is-full-width button dark outline">Удалить пост</button>
</form>
<button th:data-customer="${session.currentCustomerId}" th:data-id="${post.id}" th:data-title="${post.title}" th:data-content="${post.content}" type="button" th:onclick="|preparePostEditModal(this)|" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#postEdit">Изменить пост</button>
</div>
</div>
</div>
</div>
</div>
<div th:if="${#arrays.isEmpty(posts)}" class="row text-center is-center">
Нет постов
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="commentEdit" tabindex="-1" role="dialog" aria-labelledby="commentEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form method="post" class="modal-content" id="editComment">
<div class="modal-header">
<h5 class="modal-title" id="commentEditLabel">Изменить комментарий</h5>
</div>
<div class="modal-body text-center">
<textarea name='content' id="editModalText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Изменить</button>
</div>
</form>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="modal-content" id="editPost">
<div class="modal-header">
<h5 class="modal-title" id="postEditLabel">Редактировать пост</h5>
</div>
<div class="modal-body text-center">
<p>Заголовок</p>
<textarea name="title" id="editModalTitle" cols="30" rows="1"></textarea>
<p>Содержание</p>
<textarea name="content" id="editModalPostContent" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Изменить</button>
</div>
</form>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function prepareCommentEditModal(btn) {
document.getElementById('editModalText').value = btn.getAttribute("data-content");
document.getElementById('editComment').setAttribute('action', '/comments/' + btn.getAttribute("data-id"));
}
function preparePostEditModal(btn) {
document.getElementById('editModalTitle').value = btn.getAttribute("data-title");
document.getElementById('editModalPostContent').value = btn.getAttribute("data-content");
document.getElementById('editPost').setAttribute('action', '/posts/' + btn.getAttribute("data-id"));
}
</script>
</th:block>
</html>