점프투 스프링 부트 컨트롤러에서 뷰에 json 형식의 데이터를 보내는거에 대해 질문이 있습니다

안녕하세요 응용님 컨트롤러에서 이제 프론트에 json형식의 데이터를 보내기 위해 아래와 같이 apiController을 구현해 봤습니다. 근데 이제 이렇게 코드를 짜는건지 너무 헷갈리더라고요 특히 검증하는 부분에서 저렇게 검증을 해도되는건가 라는 생각이 들더라고요 아래와 같이 코드를 짯는데 제가 맞게 짠걸까요?

package com.mysite.sbb.api.questionApiController;

import com.mysite.sbb.controller.answerController.AnswerForm;
import com.mysite.sbb.controller.questionController.QuestionForm;
import com.mysite.sbb.entity.answer.Answer;
import com.mysite.sbb.entity.question.Question;
import com.mysite.sbb.entity.siteUser.SiteUser;
import com.mysite.sbb.service.AnswerService;
import com.mysite.sbb.service.QuestionService;
import com.mysite.sbb.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.validation.Valid;
import java.security.Principal;

@RestController
@RequestMapping("/api/question")
@RequiredArgsConstructor
public class QuestionApiController {

private final QuestionService questionService;
private final UserService userService;
private final AnswerService answerService;

@GetMapping("/{id}")
public ResponseEntity<Question> question(@PathVariable("id") Long id) {
    Question question = questionService.getQuestion(id);
    return ResponseEntity.ok(question);

}

@GetMapping("/list")
public ResponseEntity<PagingKw> list(Model model, @RequestParam(value = "page", defaultValue = "0") int page,
                                     @RequestParam(value = "kw", defaultValue = "") String kw) {

    Page<Question> paging = questionService.getList(page, kw);
    PagingKw qp = new PagingKw();
    qp.setPaging(paging);
    qp.setKw(kw);

    return ResponseEntity.ok(qp);
}

/*
 * 상세 질문을 보기 위해 데이터를 가공하는 함수
   답변 페이징 처리를 위해 @RequestParam(value = "page", defaultValue = "0") int page 추가
 * */

@GetMapping("/detail/{id}")
public ResponseEntity<PagingQuestion> detail(Model model, @PathVariable("id") Long id, AnswerForm answerForm,
                     @RequestParam(value = "page", defaultValue = "0") int page) {

    // 답변 페이징 처리
    Page<Answer> pagingAnswer = answerService.getList(page, id);
    Question question = this.questionService.getQuestion(id);
    questionService.updateView(id); // views ++ 조회수 처리

    PagingQuestion pq = new PagingQuestion();
    pq.setQuestion(question);
    pq.setPagingAnswer(pagingAnswer);

    return ResponseEntity.ok(pq);
}


@PreAuthorize("isAuthenticated()")
@PostMapping("/create")
public ResponseEntity<Question> questionCreate(@Valid QuestionForm questionForm,
                             BindingResult bindingResult, Principal principal) {
    if (bindingResult.hasErrors()) {
        return ResponseEntity.notFound().build();
    }
    SiteUser siteUser = userService.getUser(principal.getName());
    return ResponseEntity.ok(questionService.create(questionForm.getSubject(), questionForm.getContent(), siteUser));

}


@PreAuthorize("isAuthenticated()")
@GetMapping("/modify/{id}")
public ResponseEntity<QuestionForm> questionModify(QuestionForm questionForm, @PathVariable("id") Long id, Principal principal) {
    Question question = this.questionService.getQuestion(id);
    if(!question.getAuthor().getUsername().equals(principal.getName())) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "수정권한이 없습니다.");
    }
    questionForm.setSubject(question.getSubject());
    questionForm.setContent(question.getContent());
    return ResponseEntity.ok(questionForm);
}


@PreAuthorize("isAuthenticated()")
@PutMapping("/modify/{id}")
public ResponseEntity<Question> questionModify(@Valid QuestionForm questionForm, BindingResult bindingResult,
                             Principal principal, @PathVariable("id") Long id) {
    if (bindingResult.hasErrors()) {
        return ResponseEntity.notFound().build();
    }
    Question question = this.questionService.getQuestion(id);
    if (!question.getAuthor().getUsername().equals(principal.getName())) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "수정권한이 없습니다.");
    }

            // question 객체를 return 합니다
    return ResponseEntity.ok(this.questionService.modify(question, questionForm.getSubject(), questionForm.getContent()));
}


@PreAuthorize("isAuthenticated()")
@GetMapping("/delete/{id}")
public Long questionDelete(Principal principal, @PathVariable("id") Long id) {
    Question question = this.questionService.getQuestion(id);
    if (!question.getAuthor().getUsername().equals(principal.getName())) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "삭제권한이 없습니다.");
    }
    this.questionService.delete(question);
    return id;
}


@PreAuthorize("isAuthenticated()")
@GetMapping("/vote/{id}")
public Long questionVote(Principal principal, @PathVariable("id") Long id) {
    Question question = questionService.getQuestion(id);
    SiteUser siteUser = userService.getUser(principal.getName());
    questionService.vote(question, siteUser);
    return id;
}

}

kim123 54

2022년 9월 7일 11:58 오후

목록으로