Spring Boot – Controller 에서 자바스크립트 사용하기

By | 2023년 2월 9일
Table of Contents

Spring Boot – Controller 에서 자바스크립트 사용하기

참조

소스코드

public class ScriptUtil {

    public static void init(HttpServletResponse response) {
        response.setContentType("text/html; charset=utf-8");
        response.setCharacterEncoding("utf-8");
    }

    public static void alert(HttpServletResponse response, String alertText) throws IOException {
        init(response);
        PrintWriter out = response.getWriter();
        out.println(String.format("<script>alert('%s');</script>", alertText));
        out.flush();
    }

    public static void movePage(HttpServletResponse response, String nextPage) throws IOException {
        init(response);
        PrintWriter out = response.getWriter();
        out.println(String.format("<script>location.href='%s';</script>", nextPage));
        out.flush();
    }

    public static void alertAndMovePage(HttpServletResponse response, String alertText, String nextPage) throws IOException {
        init(response);
        PrintWriter out = response.getWriter();
        out.println(String.format("<script>alert('%s'); location.href='%s';</script>", alertText, nextPage));
        out.flush();
    }

    public static void alertAndBackPage(HttpServletResponse response, String alertText) throws IOException {
        init(response);
        PrintWriter out = response.getWriter();
        out.println(String.format("<script>alert('%s'); history.go(-1);</script>", alertText));
        out.flush();
    }
}

사용법

PrintWriter out 를 이용해 스크립트를 전달했으므로 리턴값을 null 로 해도 오류가 없다.

@ControllerAdvice
public class BindExceptionHandler {
    @ExceptionHandler({BindException.class})
    public ResponseEntity<?> validException(HttpServletRequest request, HttpServletResponse response, BindException ex) throws IOException {
        ScriptUtil.alertAndBackPage(response, ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return null;
    }
}
    @GetMapping("/login/doLogout")
    public String logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        deleteCookies(response);
        ScriptUtil.movePage(response, "/");
        return null;
    }

답글 남기기