ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] Controller에서 자바스크립트 alert를 사용해보자
    백엔드/Spring 2020. 11. 4. 23:28


     

         로재의 개발 일기      

    Spring Controller에서 스크립트 사용

    단순 자바에서 가능한 이야기인데, 응답 response에 

    PrintWriter를 사용하여 스크립트를 사용이 가능하다.


    하나의 URI 매핑에서 다른 결과가 도출되는 경우

    알림을 주어, 사용자에게 편의성을 주기 위해서 사용하는 방법이다.

    (예를 들면, 인증번호 확인 절차 실패의 경우에는 알림을 뜨게하고, 페이지에 머문다)


     응답에 PrintWriter를 통해서 스크립트 호출

    1
    2
    3
    4
    5
    // 이때 contentType을 먼저하지 않으면, 한글이 깨질 수 있습니다.
    response.setContentType("text/html; charset=euc-kr");
    PrintWriter out = response.getWriter();
    out.println("<script>alert('인증번호가 틀립니다'); </script>");
    out.flush();
    cs


     정적 클래스를 생성해서 호출

    ScriptUtils 클래스 생성

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    public class ScriptUtils {
     
        public static void init(HttpServletResponse response) {
            response.setContentType("text/html; charset=euc-kr");
            response.setCharacterEncoding("euc-kr");
        }
     
        public static void alert(HttpServletResponse response, String alertText) throws IOException {
            init(response);
            PrintWriter out = response.getWriter();
            out.println("<script>alert('" + alertText + "');</script> ");
            out.flush();
        }
     
        public static void alertAndMovePage(HttpServletResponse response, String alertText, String nextPage)
                throws IOException {
            init(response);
            PrintWriter out = response.getWriter();
            out.println("<script>alert('" + alertText + "'); location.href='" + nextPage + "';</script> ");
            out.flush();
        }
     
        public static void alertAndBackPage(HttpServletResponse response, String alertText) throws IOException {
            init(response);
            PrintWriter out = response.getWriter();
            out.println("<script>alert('" + alertText + "'); history.go(-1);</script>");
            out.flush();
        }
    }
    cs


    사용법

    1
    ScriptUtils.alert("인증 번호가 틀립니다");
    cs


    컨트롤러에 붙인 모습 

    1
    2
    3
    4
    5
    // 중복 로그인 발견
    @RequestMapping(value = "/session-over", method = { RequestMethod.POST, RequestMethod.GET })
    public void sessionOver(HttpServletResponse response, HttpServletRequest request) throws Exception {
        ScriptUtils.alertAndMovePage(response, "외부 로그인 시도를 발견했습니다. 강제 로그아웃을 진행합니다.""/login.do");
    }
    cs


    또한 뷰를 리턴하는 경우 (ModelAndView 혹은 String 형식)

    단순히 null을 반환해도 

    스크립트가 이전에 인식이 되기 때문에

    정상적으로 동작하는 것을 알 수 있다.



    마무리

    더 좋은 방법이 있을 것 같지만, 편의상으로 우선은 쓰고 있습니다.



    ※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다



    반응형
Designed by Tistory.