LabWork05: вроде готово

This commit is contained in:
Safgerd 2023-05-02 01:57:12 +04:00
parent 8348a9bf31
commit 60c2564229
24 changed files with 784 additions and 117 deletions

View File

@ -17,6 +17,12 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5' implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.hibernate.validator:hibernate-validator' implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5' implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'

View File

@ -31,7 +31,7 @@ export default {
}, },
async beforeMount() { async beforeMount() {
setInterval(async () => { setInterval(async () => {
const response = await axios.get('http://localhost:8080/customer'); const response = await axios.get('http://localhost:8080/api/customer');
this.customers = []; this.customers = [];
response.data.forEach(element => { response.data.forEach(element => {
this.customers.push(element); this.customers.push(element);

View File

@ -101,27 +101,35 @@ export default {
}, },
methods: { methods: {
async createUser(){ async createUser(){
const response = await axios.post('http://localhost:8080/customer?username=' + this.usernameModal + '&password=' + this.passwordModal); let customer = {
username: this.usernameModal,
password: this.passwordModal
};
const response = await axios.post('http://localhost:8080/api/customer', customer);
this.refreshList(); this.refreshList();
}, },
async deleteUser(id) { async deleteUser(id) {
const response = await axios.delete('http://localhost:8080/customer/' + id); const response = await axios.delete('http://localhost:8080/api/customer/' + id);
this.refreshList(); this.refreshList();
}, },
async editUser() { async editUser() {
const response = await axios.put('http://localhost:8080/customer/' + this.selectedCustomer['id'] + '?username=' + this.usernameModal + '&password=' + this.passwordModal); let customer = {
username: this.usernameModal,
password: this.passwordModal
};
const response = await axios.put('http://localhost:8080/api/customer/' + this.selectedCustomer['id'], customer);
this.refreshList(); this.refreshList();
}, },
async refreshList() { async refreshList() {
this.customers = []; this.customers = [];
if (this.$route.params.id === "") { if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/customer'); const response = await axios.get('http://localhost:8080/api/customer');
response.data.forEach(element => { response.data.forEach(element => {
this.customers.push(element); this.customers.push(element);
console.log(element); console.log(element);
}); });
} else { } else {
const response = await axios.get('http://localhost:8080/customer/' + this.$route.params.id); const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
this.customers.push(response.data) this.customers.push(response.data)
} }
}, },
@ -131,13 +139,13 @@ export default {
this.currentCustomerId = history.state; this.currentCustomerId = history.state;
setInterval(async () => this.currentCustomerId = history.state, 50) setInterval(async () => this.currentCustomerId = history.state, 50)
if (this.$route.params.id === "") { if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/customer'); const response = await axios.get('http://localhost:8080/api/customer');
response.data.forEach(element => { response.data.forEach(element => {
this.customers.push(element); this.customers.push(element);
console.log(element); console.log(element);
}); });
} else { } else {
const response = await axios.get('http://localhost:8080/customer/' + this.$route.params.id); const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
this.customers.push(response.data) this.customers.push(response.data)
} }

View File

@ -203,47 +203,67 @@ export default {
async createComment() { async createComment() {
const content = document.getElementById("post-comment-" + this.selectedPostId).value const content = document.getElementById("post-comment-" + this.selectedPostId).value
await axios.post('http://localhost:8080/comment?text=' + content + '&ownerId=' + this.currentCustomerId + '&postId=' + this.selectedPostId); let comment = {
"content": content,
customerId: this.currentCustomerId,
postId: this.selectedPostId
};
await axios.post('http://localhost:8080/api/comment', comment);
document.getElementById("post-comment-" + this.selectedPostId).value = '' document.getElementById("post-comment-" + this.selectedPostId).value = ''
this.refreshList(); this.refreshList();
}, },
async deleteComment(commentId) { async deleteComment(commentId) {
await axios.delete('http://localhost:8080/comment/' + commentId); await axios.delete('http://localhost:8080/api/comment/' + commentId);
this.refreshList(); this.refreshList();
}, },
async editComment(){ async editComment(){
await axios.put('http://localhost:8080/comment/' + this.selectedCommentId + '?text=' + this.contentModal); let comment = {
content: this.contentModal,
customerId: this.currentCustomerId,
postId: 0
};
await axios.put('http://localhost:8080/api/comment/' + this.selectedCommentId, comment);
this.refreshList(); this.refreshList();
}, },
async createPost() { async createPost() {
const response = await axios.post('http://localhost:8080/post?title=' + this.titleModal + '&content=' + this.postContentModal + '&authorId=' + this.currentCustomerId); let post = {
"content": this.postContentModal,
title: this.titleModal,
customerId: this.currentCustomerId
};
const response = await axios.post('http://localhost:8080/api/post', post);
this.titleModal = '' this.titleModal = ''
this.postContentModal = '' this.postContentModal = ''
this.refreshList(); this.refreshList();
}, },
async deletePost(postId) { async deletePost(postId) {
const response = await axios.delete('http://localhost:8080/post/' + postId); const response = await axios.delete('http://localhost:8080/api/post/' + postId);
this.refreshList(); this.refreshList();
}, },
async editPost(){ async editPost(){
const response = await axios.put('http://localhost:8080/post/' + this.selectedPostId + '?title=' + this.titleModal + '&content=' + this.postContentModal); let post = {
"content": this.postContentModal,
title: this.titleModal,
customerId: this.currentCustomerId
};
const response = await axios.put('http://localhost:8080/api/post/' + this.selectedPostId, post);
this.refreshList(); this.refreshList();
}, },
async refreshList(){ async refreshList(){
this.customers = []; this.customers = [];
this.posts = []; this.posts = [];
const responseCustomer = await axios.get('http://localhost:8080/customer'); const responseCustomer = await axios.get('http://localhost:8080/api/customer');
responseCustomer.data.forEach(element => { responseCustomer.data.forEach(element => {
this.customers.push(element); this.customers.push(element);
console.log(element); console.log(element);
}); });
const responsePost = await axios.get('http://localhost:8080/post'); const responsePost = await axios.get('http://localhost:8080/api/post');
responsePost.data.forEach(element => { responsePost.data.forEach(element => {
this.posts.splice(0, 0, element); this.posts.splice(0, 0, element);
console.log(element); console.log(element);
@ -253,7 +273,7 @@ export default {
async beforeMount() { async beforeMount() {
this.currentCustomerId = history.state; this.currentCustomerId = history.state;
setInterval(async () => this.currentCustomerId = history.state, 50) setInterval(async () => this.currentCustomerId = history.state, 50)
const responseCustomer = await axios.get('http://localhost:8080/customer'); const responseCustomer = await axios.get('http://localhost:8080/api/customer');
responseCustomer.data.forEach(element => { responseCustomer.data.forEach(element => {
this.customers.push(element); this.customers.push(element);
if (element['id'] == this.currentCustomerId) { if (element['id'] == this.currentCustomerId) {
@ -261,7 +281,7 @@ export default {
} }
console.log(element); console.log(element);
}); });
const responsePost = await axios.get('http://localhost:8080/post'); const responsePost = await axios.get('http://localhost:8080/api/post');
responsePost.data.forEach(element => { responsePost.data.forEach(element => {
this.posts.splice(0, 0, element); this.posts.splice(0, 0, element);
console.log(element); console.log(element);

View File

@ -1,38 +1,94 @@
package ru.ulstu.is.labwork.Lab4.DTO; package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment; import ru.ulstu.is.labwork.Lab4.model.Comment;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CommentDto { public class CommentDto {
public final Long id; public long id;
public final String content; public String content;
public final String customerName; public long customerId;
public final String postTitle; public String customerName;
public final String postAuthor; public long postId;
public final long postAuthorId; public String postTitle;
public String postAuthor;
public long postAuthorId;
public CommentDto() {
}
public CommentDto(Comment comment) { public CommentDto(Comment comment) {
this.id = comment.getId(); this.id = comment.getId();
this.content = comment.getContent(); this.content = comment.getContent();
this.customerId = comment.getCustomer().getId();
this.customerName = comment.getCustomer().getUsername(); this.customerName = comment.getCustomer().getUsername();
this.postId = comment.getPost().getId();
this.postTitle = comment.getPost().getTitle(); this.postTitle = comment.getPost().getTitle();
this.postAuthor = comment.getPost().getCustomer().getUsername(); this.postAuthor = comment.getPost().getCustomer().getUsername();
this.postAuthorId = comment.getPost().getCustomer().getId(); this.postAuthorId = comment.getPost().getCustomer().getId();
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() { public long getId() {
return id; return id;
} }
public String getContent() { public String getContent() {
return content; return content;
} }
public void setContent(String content) {
this.content = content;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCustomerName() { public String getCustomerName() {
return customerName; return customerName;
} }
public String getPostTitle() {return postTitle;}
public long getPostId() {
return postId;
}
public void setPostId(long postId) {
this.postId = postId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPostTitle() {
return postTitle;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPostAuthor() { public String getPostAuthor() {
return postAuthor; return postAuthor;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getPostAuthorId() { public long getPostAuthorId() {
return postAuthorId; return postAuthorId;
} }
@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

@ -1,18 +1,19 @@
package ru.ulstu.is.labwork.Lab4.DTO; package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment; import com.fasterxml.jackson.annotation.JsonProperty;
import ru.ulstu.is.labwork.Lab4.model.Customer; import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class CustomerDto { public class CustomerDto {
public final Long id; public long id;
public final String username; public String username;
public final String password; public String password;
public final List<CommentDto> comments; public List<CommentDto> comments;
public final List<PostDto> posts; public List<PostDto> posts;
public CustomerDto() {
}
public CustomerDto(Customer customer){ public CustomerDto(Customer customer){
this.id = customer.getId(); this.id = customer.getId();
@ -22,9 +23,34 @@ public class CustomerDto {
this.posts = customer.getPosts().stream().map(PostDto::new).toList(); this.posts = customer.getPosts().stream().map(PostDto::new).toList();
} }
public Long getId() {return id;} @JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getUsername() {return username;} public Long getId() {
public String getPassword() {return password;} return id;
public List<CommentDto> getComments() {return comments;} }
public List<PostDto> getPosts() {return posts;}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<CommentDto> getComments() {
return comments;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<PostDto> getPosts() {
return posts;
}
} }

View File

@ -1,18 +1,22 @@
package ru.ulstu.is.labwork.Lab4.DTO; package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment; import com.fasterxml.jackson.annotation.JsonProperty;
import ru.ulstu.is.labwork.Lab4.model.Post; import ru.ulstu.is.labwork.Lab4.model.Post;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class PostDto { public class PostDto {
public final Long id; public long id;
public final String title; public String title;
public final String content; public String content;
public final String customerName; public String customerName;
public final long customerId; public long customerId;
public final List<CommentDto> comments; public ArrayList<CommentDto> comments;
public PostDto() {
}
public PostDto(Post post){ public PostDto(Post post){
this.id = post.getId(); this.id = post.getId();
@ -20,17 +24,44 @@ public class PostDto {
this.content = post.getContent(); this.content = post.getContent();
this.customerName = post.getCustomer().getUsername(); this.customerName = post.getCustomer().getUsername();
this.customerId = post.getCustomer().getId(); 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());
} }
public Long getId() { return id; } @JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getTitle() { return title; } public Long getId() {
public String getContent() { return content; } return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCustomerName() { public String getCustomerName() {
return customerName; return customerName;
} }
public List<CommentDto> getComments() { return comments; }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<CommentDto> getComments() {
return comments;
}
public long getCustomerId() { public long getCustomerId() {
return customerId; return customerId;
} }
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
} }

View File

@ -1,15 +1,18 @@
package ru.ulstu.is.labwork.Lab4.controller; package ru.ulstu.is.labwork.Lab4.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto; import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.model.Comment; import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.services.CommentService; import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService; import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService; import ru.ulstu.is.labwork.Lab4.services.PostService;
import ru.ulstu.is.labwork.WebConfiguration;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/comment") @RequestMapping(WebConfiguration.REST_API + "/comment")
public class CommentController { public class CommentController {
private final CommentService commentService; private final CommentService commentService;
private final CustomerService customerService; private final CustomerService customerService;
@ -34,14 +37,18 @@ public class CommentController {
} }
@PostMapping @PostMapping
public CommentDto createComment(@RequestParam("text") String text, @RequestParam("ownerId") Long ownerId, @RequestParam("postId") Long postId){ public CommentDto createComment(@RequestBody @Valid CommentDto commentDto){
final Comment comment = commentService.addComment(customerService.findCustomer(ownerId), postService.findPost(postId), text); final Comment comment = commentService.addComment(
customerService.findCustomer(commentDto.getCustomerId()),
postService.findPost(commentDto.getPostId()),
commentDto.getContent()
);
return new CommentDto(comment); return new CommentDto(comment);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public CommentDto updateComment(@RequestParam("text") String text, @PathVariable Long id) { public CommentDto updateComment(@RequestBody @Valid CommentDto commentDto, @PathVariable Long id) {
return new CommentDto(commentService.updateComment(id, text)); return new CommentDto(commentService.updateComment(id, commentDto.getContent()));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -1,14 +1,16 @@
package ru.ulstu.is.labwork.Lab4.controller; package ru.ulstu.is.labwork.Lab4.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CustomerDto; import ru.ulstu.is.labwork.Lab4.DTO.CustomerDto;
import ru.ulstu.is.labwork.Lab4.model.Customer; import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.services.CustomerService; import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.WebConfiguration;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/customer") @RequestMapping(WebConfiguration.REST_API + "/customer")
public class CustomerController { public class CustomerController {
private final CustomerService customerService; private final CustomerService customerService;
@ -29,14 +31,14 @@ public class CustomerController {
} }
@PostMapping @PostMapping
public CustomerDto createCustomer(@RequestParam("username") String username, @RequestParam("password") String password){ public CustomerDto createCustomer(@RequestBody @Valid CustomerDto customerDto){
final Customer customer = customerService.addCustomer(username, password); final Customer customer = customerService.addCustomer(customerDto.getUsername(), customerDto.getPassword());
return new CustomerDto(customer); return new CustomerDto(customer);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public CustomerDto updateCustomer(@RequestParam("username") String username, @RequestParam("password") String password, @PathVariable Long id) { public CustomerDto updateCustomer(@RequestBody @Valid CustomerDto customerDto, @PathVariable Long id) {
return new CustomerDto(customerService.updateCustomer(id, username, password)); return new CustomerDto(customerService.updateCustomer(id, customerDto.getUsername(), customerDto.getPassword()));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -1,5 +1,6 @@
package ru.ulstu.is.labwork.Lab4.controller; package ru.ulstu.is.labwork.Lab4.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto; import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto; import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
@ -8,13 +9,14 @@ import ru.ulstu.is.labwork.Lab4.model.Post;
import ru.ulstu.is.labwork.Lab4.services.CommentService; import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService; import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService; import ru.ulstu.is.labwork.Lab4.services.PostService;
import ru.ulstu.is.labwork.WebConfiguration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@RestController @RestController
@RequestMapping("/post") @RequestMapping(WebConfiguration.REST_API + "/post")
public class PostController { public class PostController {
private final PostService postService; private final PostService postService;
private final CustomerService customerService; private final CustomerService customerService;
@ -37,23 +39,13 @@ public class PostController {
} }
@PostMapping @PostMapping
public PostDto createPost( public PostDto createPost(@RequestBody @Valid PostDto postDto) {
@RequestParam("title") String title, return new PostDto(postService.addPost(customerService.findCustomer(postDto.getCustomerId()), postDto.getTitle(), postDto.getContent()));
@RequestParam("content") String content,
@RequestParam("authorId") Long authorId
)
{
return new PostDto(postService.addPost(customerService.findCustomer(authorId), title, content));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public PostDto updatePost( public PostDto updatePost(@RequestBody @Valid PostDto postDto, @PathVariable Long id) {
@PathVariable Long id, return new PostDto(postService.updatePost(id, postDto.title, postDto.content));
@RequestParam("title") String title,
@RequestParam("content") String content
)
{
return new PostDto(postService.updatePost(id, title, content));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -1,34 +0,0 @@
package ru.ulstu.is.labwork.Lab4.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/search")
public class SearchController {
private final CommentService commentService;
private final PostService postService;
public SearchController(PostService postService, CommentService commentService){
this.commentService = commentService;
this.postService = postService;
}
@PostMapping
public List<Object> getResult(@RequestParam("searchStr") String searchStr) {
List<Object> result = new ArrayList<>();
result.addAll(commentService.findFilteredComments(searchStr).stream()
.map(CommentDto::new)
.toList());
result.addAll(postService.findFilteredPosts(searchStr).stream()
.map(PostDto::new)
.toList());
return result;
}
}

View File

@ -0,0 +1,55 @@
package ru.ulstu.is.labwork.Lab4.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/comments")
public class Comments {
private final CustomerService customerService;
private final CommentService commentService;
private final PostService postService;
public Comments(CustomerService customerService, CommentService commentService, PostService postService) {
this.customerService = customerService;
this.commentService = commentService;
this.postService = postService;
}
@PostMapping(value = { "/", "/{id}"})
public String manipulateComment(@PathVariable(required = false) Long id, @ModelAttribute @Valid CommentDto commentDto,
HttpServletRequest request, HttpSession session, BindingResult bindingResult, Model model) {
model.addAttribute("request", request);
model.addAttribute("session", session);
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "/feed";
}
if (id == null || id <= 0) {
commentService.addComment(customerService.findCustomer(commentDto.customerId), postService.findPost(commentDto.postId), commentDto.content);
} else {
commentService.updateComment(id, commentDto.content);
}
return "redirect:/feed";
}
@PostMapping("/delete/{id}")
public String deleteComment(@PathVariable Long id) {
commentService.deleteComment(id);
return "redirect:/feed";
}
}

View File

@ -0,0 +1,62 @@
package ru.ulstu.is.labwork.Lab4.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import ru.ulstu.is.labwork.Lab4.DTO.CustomerDto;
import ru.ulstu.is.labwork.Lab4.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("/customers")
public class Customers {
private final CustomerService customerService;
public Customers(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());
} else {
model.addAttribute("customers", new CustomerDto[] { new CustomerDto(customerService.findCustomer(id)) });
}
return "customers";
}
@PostMapping("/delete/{id}")
public String deleteCustomer(@PathVariable Long id, HttpSession session) {
session.setAttribute("currentCustomerId", -1);
customerService.deleteCustomer(id);
return "redirect:/customers/";
}
@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 "/customers";
}
if (id == null || id <= 0) {
customerService.addCustomer(customerDto.username, customerDto.password);
} else {
customerService.updateCustomer(id, customerDto.username, customerDto.password);
}
return "redirect:/customers/";
}
}

View File

@ -0,0 +1,65 @@
package ru.ulstu.is.labwork.Lab4.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.is.labwork.Lab4.DTO.CustomerDto;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.Objects;
@Controller
@RequestMapping("/feed")
public class Feed {
private final PostService postService;
private final CustomerService customerService;
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(@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

@ -0,0 +1,56 @@
package ru.ulstu.is.labwork.Lab4.mvc;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.BindingResult;
import jakarta.validation.Valid;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
@Controller
@RequestMapping("/posts")
public class Posts {
private final CustomerService customerService;
private final CommentService commentService;
private final PostService postService;
public Posts(CustomerService customerService, CommentService commentService, PostService postService) {
this.customerService = customerService;
this.commentService = commentService;
this.postService = postService;
}
@PostMapping("/delete/{id}")
public String deletePost(@PathVariable Long id) {
postService.deletePost(id);
return "redirect:/feed";
}
@PostMapping(value = { "/", "/{id}"})
public String manipulatePost(@PathVariable(required = false) Long id, @ModelAttribute @Valid PostDto postDto,
HttpServletRequest request, HttpSession session,
BindingResult bindingResult,
Model model) {
model.addAttribute("request", request);
model.addAttribute("session", session);
model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList());
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "/feed";
}
if (id == null || id <= 0) {
postService.addPost(customerService.findCustomer(postDto.customerId), postDto.title, postDto.content);
} else {
postService.updatePost(id, postDto.title, postDto.content);
}
return "redirect:/feed";
}
}

View File

@ -0,0 +1,16 @@
package ru.ulstu.is.labwork.Lab4.mvc;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Session {
@PostMapping("/update-session")
public ResponseEntity<Void> updateSession(@RequestParam("currentCustomerId") int currentCustomerId, HttpSession session) {
session.setAttribute("currentCustomerId", currentCustomerId);
return ResponseEntity.ok().build();
}
}

View File

@ -2,9 +2,14 @@ package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.labwork.Lab4.model.Comment; import ru.ulstu.is.labwork.Lab4.model.Comment;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.List; import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> { public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByContentLikeIgnoreCase(String text); @Query("SELECT DISTINCT c FROM Comment c WHERE c.content LIKE %:tag%")
List<Comment> searchComments(@Param("tag") String tag);
} }

View File

@ -3,9 +3,13 @@ package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.labwork.Lab4.model.Post; import ru.ulstu.is.labwork.Lab4.model.Post;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.List; import java.util.List;
public interface PostRepository extends JpaRepository<Post, Long> { public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByContentLikeIgnoreCase(String text); @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

@ -20,9 +20,9 @@ public class CommentService {
this.commentRepository = commentRepository; this.commentRepository = commentRepository;
} }
@Transactional @jakarta.transaction.Transactional
public List<Comment> findFilteredComments(String filter) { public List<Comment> searchComments(String tag) {
return commentRepository.findByContentLikeIgnoreCase("%" + filter + "%"); return commentRepository.searchComments(tag);
} }

View File

@ -21,8 +21,8 @@ public class PostService {
this.postRepository = postRepository; this.postRepository = postRepository;
} }
@Transactional @Transactional
public List<Post> findFilteredPosts(String filter) { public List<Post> searchPosts(String tag) {
return postRepository.findByContentLikeIgnoreCase("%" + filter + "%"); return postRepository.searchPosts(tag);
} }
@Transactional @Transactional

View File

@ -6,6 +6,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*"); registry.addMapping("/**").allowedMethods("*");

View File

@ -0,0 +1,103 @@
<!DOCTYPE html>
<html lang="" 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="ms-5">
<p class='h4 m-3'>Профили</p>
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
<p class='h4 ms-3'>Список</p>
<div class="row">
<div class="col-5">
<div th:each="customer: ${customers}" class="row card is-left mb-3">
<div class="row is-left">
<div class="row is-left h3" th:text="${customer.username}"></div>
</div>
<div class="row" th:if="!${#arrays.isEmpty(customer.comments)}">
<p class="h4">Посты:</p>
<div class="col">
<div th:each="post: ${customer.posts}" class="row is-left card mb-3">
<div class="row is-left h4" th:text="${post.title}"></div>
<div class="row is-left h5" th:text="${post.content}"></div>
</div>
</div>
</div>
<div class="row" th:if="!${#arrays.isEmpty(customer.comments)}">
<p class="h4">Комментарии:</p>
<div class="col">
<div th:each="comment: ${customer.comments}" class="row is-left card mb-3">
<div class="row is-left h5" th:text="${'&quot;' + comment.content + '&quot;' + ' - к посту ' + '&quot;' + comment.postTitle + '&quot;' + ' от пользователя ' + comment.postAuthor}"></div>
</div>
</div>
</div>
<div class="row" th:if="${session.currentCustomerId == customer.id}">
<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: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>
</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="@{/customers/}" 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', '/customers/' + btn.getAttribute("data-id"));
}
</script>
</th:block>
</html>

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
<title>LabWork04 - Social Network</title>
</head>
<body class="container">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<div>
<div>
<p class='text-center m-3 h3'>LabWork04 - Social Network</p>
</div>
<div class="nav row">
<div class="nav-left col-4" th:with="activeLink=${request.requestURI}">
<a href="/customers/" class="text-decoration-none m-3" th:classappend="${#strings.startsWith(activeLink, '/customers')} ? 'clear' : ''">Профили</a>
<a href="/feed" class="text-decoration-none m-3" th:classappend="${#strings.startsWith(activeLink, '/feed')} ? 'clear' : ''">Посты</a>
<select class="form-select mt-4" style="font-size: 16px; max-height: 35px; max-width: 180px; min-height: 35px; min-width: 180px;" th:onchange="updateSession()" id="selectBox">
<option value="-1" th:selected="${session.currentCustomerId == -1}" class="button dark outline">Не выбран</option>
<option th:each="customer: ${customers}" th:selected="${session.currentCustomerId == customer.id}" th:value="${customer.id}" class="button dark outline" th:text="${customer.username}"></option>
</select>
</div>
</div>
<div layout:fragment="content">
</div>
</div>
</body>
<script>
function updateSession() {
let selectBox = document.getElementById("selectBox");
let id = selectBox.options[selectBox.selectedIndex].value;
fetch("/update-session?currentCustomerId=" + id, {method: "post"})
location.reload();
}
</script>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,144 @@
<!DOCTYPE html>
<html lang="" 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="ms-5">
<p class='h3 m-3'>Посты</p>
<div class="col-5">
<form class="row mb-5" action="/feed">
<input type="search" name="search" class="col-7">
<button class="button primary col" type="submit">Найти</button>
</form>
</div>
<div class="row" th:if="${session.currentCustomerId > 0}">
<form class="col-7" th:action="@{/posts/}" method="post">
<input name="customerId" type="text" style="display: none;" th:value="${session.currentCustomerId}">
<div class="row is-left">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input name="title" type="text" class="col-5" id="createPostTitle" />
</div>
<div class="row is-left">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea name="content" type="textarea" class="col-5" id="createPostContent"></textarea>
</div>
<div class="row is-left">
<button type='submit' class="button primary col-7">
Опубликовать
</button>
</div>
</form>
</div>
<div th:unless="${#arrays.isEmpty(posts)}" class="row">
<div class="col-5">
<div class="row mb-5 card" th:each="post: ${posts}">
<div class="col">
<div class="row is-left my-3">
<p><a th:href="${'/customers/' + post.customerId}" class="text-primary" th:text="${post.customerName}"></a></p>
</div>
<div class="row text-left">
<span class="h2" th:text="${post.title}"></span>
<span class="h3" th:text="${post.content}"></span>
</div>
<div class="row">
<div th:unless="${#arrays.isEmpty(post.comments)}">
<p class="row h3 is-left my-3">Комментарии</p>
<div class="row text-left mb-4 card" th:each="comment: ${post.comments}">
<div class="row is-left">
<span class="h2 text-primary" th:text="${comment.customerName}"></span>
<span class="h3" th:text="${comment.content}"></span>
</div>
<div th:if="${session.currentCustomerId == comment.customerId}" class="row mt-3">
<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>
</div>
<form class="row" th:if="${session.currentCustomerId != -1}" th:action="@{/comments/}" method="post">
<input name="content" type="text" class="col-6"/>
<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-6 secondary outline">Комментировать</button>
</form>
</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>
<!-- Modal -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form method="post" 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>
<!-- 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>
</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>