Lab5: Completed first stage(added @RequestBody and some other things)

This commit is contained in:
Сергей Полевой 2023-04-18 00:04:42 +04:00
parent 2224416988
commit 7cb753ed2e
12 changed files with 139 additions and 62 deletions

View File

@ -16,6 +16,12 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
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'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.hibernate.validator:hibernate-validator' implementation 'org.hibernate.validator:hibernate-validator'

View File

@ -30,7 +30,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

@ -109,27 +109,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)
} }
}, },
@ -139,13 +147,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

@ -161,42 +161,62 @@ 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);
@ -206,7 +226,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) {
@ -214,7 +234,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

@ -2,29 +2,37 @@ package np.something.DTO;
import np.something.model.Comment; import np.something.model.Comment;
import java.time.LocalDateTime; import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
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 String createDate;
public final String createDate; 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();
this.createDate = comment.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); this.createDate = comment.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() { public long getId() {
return id; return id;
} }
@ -33,20 +41,33 @@ public class CommentDto {
return content; return content;
} }
public long getCustomerId() {
return customerId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCustomerName() { public String getCustomerName() {
return customerName; return customerName;
} }
public long getPostId() {
return postId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPostTitle() {return postTitle;} 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;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCreateDate() { public String getCreateDate() {
return createDate; return createDate;
} }

View File

@ -1,15 +1,21 @@
package np.something.DTO; package np.something.DTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import np.something.model.Customer; import np.something.model.Customer;
import java.io.Serializable;
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();
@ -19,6 +25,7 @@ public class CustomerDto {
this.posts = customer.getPosts().stream().map(PostDto::new).toList(); this.posts = customer.getPosts().stream().map(PostDto::new).toList();
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() { public long getId() {
return id; return id;
} }
@ -31,10 +38,12 @@ public class CustomerDto {
return password; return password;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<CommentDto> getComments() { public List<CommentDto> getComments() {
return comments; return comments;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<PostDto> getPosts() { public List<PostDto> getPosts() {
return posts; return posts;
} }

View File

@ -1,5 +1,6 @@
package np.something.DTO; package np.something.DTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import np.something.model.Post; import np.something.model.Post;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -7,16 +8,19 @@ import java.time.format.DateTimeFormatter;
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 long customerId;
public final long customerId; public List<CommentDto> comments;
public final List<CommentDto> comments;
public String createDate; public String createDate;
public PostDto() {
}
public PostDto(Post post) { public PostDto(Post post) {
this.id = post.getId(); this.id = post.getId();
this.title = post.getTitle(); this.title = post.getTitle();
@ -27,6 +31,7 @@ public class PostDto {
this.createDate = post.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); this.createDate = post.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() { public long getId() {
return id; return id;
} }
@ -39,10 +44,12 @@ public class PostDto {
return content; return content;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCustomerName() { public String getCustomerName() {
return customerName; return customerName;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<CommentDto> getComments() { public List<CommentDto> getComments() {
return comments; return comments;
} }
@ -51,6 +58,7 @@ public class PostDto {
return customerId; return customerId;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getCreateDate() { public String getCreateDate() {
return createDate; return createDate;
} }

View File

@ -6,6 +6,8 @@ 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

@ -1,6 +1,8 @@
package np.something.controllers; package np.something.controllers;
import jakarta.validation.Valid;
import np.something.DTO.CommentDto; import np.something.DTO.CommentDto;
import np.something.WebConfiguration;
import np.something.model.Comment; import np.something.model.Comment;
import np.something.services.*; import np.something.services.*;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -8,7 +10,7 @@ import org.springframework.web.bind.annotation.*;
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;
@ -33,14 +35,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,6 +1,8 @@
package np.something.controllers; package np.something.controllers;
import jakarta.validation.Valid;
import np.something.DTO.CustomerDto; import np.something.DTO.CustomerDto;
import np.something.WebConfiguration;
import np.something.model.Customer; import np.something.model.Customer;
import np.something.services.*; import np.something.services.*;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -8,7 +10,7 @@ import org.springframework.web.bind.annotation.*;
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,13 +1,15 @@
package np.something.controllers; package np.something.controllers;
import jakarta.validation.Valid;
import np.something.DTO.PostDto; import np.something.DTO.PostDto;
import np.something.WebConfiguration;
import np.something.services.CustomerService; import np.something.services.CustomerService;
import np.something.services.PostService; import np.something.services.PostService;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@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;
@ -30,23 +32,15 @@ public class PostController {
} }
@PostMapping @PostMapping
public PostDto createPost( public PostDto createPost(@RequestBody @Valid PostDto postDto)
@RequestParam("title") String title,
@RequestParam("content") String content,
@RequestParam("authorId") Long authorId
)
{ {
return new PostDto(postService.addPost(customerService.findCustomer(authorId), title, content)); return new PostDto(postService.addPost(customerService.findCustomer(postDto.getCustomerId()), postDto.getTitle(), postDto.getContent()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public PostDto updatePost( public PostDto updatePost(@RequestBody @Valid PostDto postDto, @PathVariable Long id)
@PathVariable Long id,
@RequestParam("title") String title,
@RequestParam("content") String content
)
{ {
return new PostDto(postService.updatePost(id, title, content)); return new PostDto(postService.updatePost(id, postDto.title, postDto.content));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -10,10 +10,11 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ControllerAdvice @ControllerAdvice(annotations = RestController.class)
public class AdviceController { public class AdviceController {
@ExceptionHandler({ @ExceptionHandler({
CommentNotFoundException.class, CommentNotFoundException.class,