[SpringBoot]String리턴 > ModelAndView리턴 사용

Glen(OH TaekJoo)·2023년 11월 17일
0

Study

목록 보기
44/53

기존 코드와 수정한 코드

	@PreAuthorize("isAuthenticated()")
    @GetMapping("/article/modify/{id}")
    public String articleModify(QuestionForm articleForm, @PathVariable("id") Integer id, Principal principal) {
        Question article = this.questionService.getQuestion(id);
        if (!article.getAuthor().getUsername().equals(principal.getName())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "수정권한이 없습니다.");
        }
        articleForm.setSubject(article.getSubject());
        articleForm.setContent(article.getContent());
        return "question_form";
    }

기존 컨트롤러의 게시글 수정 메서드에서 해당 게시글을 작성한 회원과
접속중인 회원의 정보가 다를경우 'ResponseStatusException' 을 통해
400에러 안에 해당 에러문구가 나오게 되어있었다.

400에러 대신 '에러템플릿'이 새창으로 나오도록 메서드를 수정하였다.

@PreAuthorize("isAuthenticated()")
@GetMapping("/article/modify/{id}")
public ModelAndView articleModify(QuestionForm articleForm, @PathVariable("id") Integer id, Principal principal) {
    Question article = this.questionService.getQuestion(id);
    if (!article.getAuthor().getUsername().equals(principal.getName())) {
        ModelMap model = new ModelMap();
        model.addAttribute("errorMessage", "수정권한이 없습니다.");
        return new ModelAndView("error_page", model);
    }
    articleForm.setSubject(article.getSubject());
    articleForm.setContent(article.getContent());
    return new ModelAndView("question_form", "questionForm", articleForm);
}

String 타입으로 리턴을 하는 것이 아닌 ModelAndView 타입으로 리턴하도록 메서드를 수정하였다.
그리고 해당 작성자의 아이디정보와 접속자의 아이디정보가 다를 경우 저장한 모델과 뷰를 같이 보여주도록 수정하였다.

모델의 에러메세지에 수정권한이 없다는 메세지를 저장하고 리턴값으로 '에러페이지' 템플릿 과 해당 모델을 리턴하였다.

Model 과 ModelAndView 의 차이점

모델은 모델값만 리턴이 가능하나 모델엔드뷰는 모델과 뷰를 동시에 리턴할 수 있다.

해당 템플릿에 모델값으로 저장한 에러메세지와
이전템플릿으로 돌아갈 수 있게 a태그를 넣어놓았다.

profile
병아리 개발자 의 우당탕탕 성장기

0개의 댓글