2023. 3. 31. 17:38ㆍspring
String[] split = referrer.substring(referrer.indexOf('?')).split("\\=");
String page = split[1];
[ 문제 발생 ]
게시판을 만들다가 의문이 들었다.
앵커라는 것을 공부하던 중에 해당 스크롤로는 돌아가는데 삭제를 하게 되면 ?
참고로 해당 프로젝트에서 삭제를 위해서는 question_list 에서 게시글 클릭시 --> URL : [ /question / detail / { id값 } ] --> URL : [ / question / delete / {id값} ]
게시글을 삭제하면 기존에 내가 있던 페이지가 어디든 1번 페이지로 돌아간다.
만약 데이터가 굉장히 많고 페이지가 100개씩 있다고 생각한다면 이렇게 불편할 수가 없다.
삭제 뿐만 아니라 어떠한 작업을 통해 새로고침 되면 default값인 0(1) 페이지로 돌아가버린다.
[문제 해결 1]
그래서 처음에는 쉽게 쉽게 생각해보았다.
@GetMapping("/delete/{id}")
public String delete(@PathVariable(value = "id") long id, Principal principal, Pageable pageable){
// Pageable 객체를 사용해 page정보 가져오기 (안됨)
int page = pageable.getPageNumber();
Question question = questionService.getQuestion(id);
if (!question.getAuthor().getUsername().equals(principal.getName())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
questionService.delete(question);
return String.format("redirect:/question/list?page=%s", page);
}
Pageable 이라는 객체는 Pagenation에 관한 정보를 모두 가지고 있기 때문에 당연히 될 거라고 생각했다.
불가능했다. (page 출력해보니 계속 0이 반환됨)
[문제 해결 2]
그래서 찾아보던 중 referrer이 이전 URL 주소를 뜻하는 것을 알게되었다.
하지만 컨트롤러에서 delete 메서드가 실행될때의 이전 주소는 page값을 가지고 있지 않다.
즉, 이전이전에서부터 page 값을 URL에 저장시켜 놓아야 한다고 생각했다.
기존 URL : / question / detail / {id값}
------->
바꾼 URL : / question / detail / {id값} ? page={페이지}
- referrer 가져오기
public String delete(@PathVariable(value = "id") long id,
Principal principal, HttpServletRequest request) {
String referrer = request.getHeader("referer"); //이전 코드
}
- referrer 에서 page값 뽑아내기
String[] split = referrer.substring(referrer.indexOf('?')).split("\\=");
String page = split[1];
- page값 포함시켜서 redirect 하기
return String.format("redirect:/question/list?page=%s", page);
- 전체 예시 코드
@GetMapping("/delete/{id}")
public String delete(@PathVariable(value = "id") long id, Principal principal, HttpServletRequest request) {
String referrer = request.getHeader("referer"); //이전 코드
String[] split = referrer.substring(referrer.indexOf('?')).split("\\=");
String page = split[1];
Question question = questionService.getQuestion(id);
if (!question.getAuthor().getUsername().equals(principal.getName())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
questionService.delete(question);
return String.format("redirect:/question/list?page=%s", page);
}
'spring' 카테고리의 다른 글
[SpringBoot] GET, POST 이외의 HTTP 메서드 사용하기 위한 설정 (0) | 2023.05.05 |
---|---|
[SpringBoot] @ToString(callSuper = true) (0) | 2023.04.13 |
[SpringBoot] 하나의 form을 재활용 하기 위한 방법 (ex_등록,수정을 하나의 form으로 <csrf>) (0) | 2023.03.31 |
[SpringBoot] @Builder.Default / 클래스 내에서 필드 초기화 / NullPointException (0) | 2023.03.21 |
[SpringBoot] 실행 전 데이터 세팅 방법, CommandLineRunner (0) | 2023.03.20 |