IT/etc

[ETC] Spring Controller에서 자바스크립트 경고창 띄우는 방법

@욕심쟁이 2021. 1. 27. 18:41
반응형

1. 아래와 같이 경고창을 띄울수 있는 Class를 생성합니다.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;


//=> 컨트롤에서 경고창 전달시 사용 
public class ScriptAlertUtils {
	   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 {
	    	// 사용법 : ScriptAlertUtils.alert("아이디가 중복");
	        init(response);
	        PrintWriter out = response.getWriter();
	        out.println("<script>alert('" + alertText + "');</script> ");
	        out.flush();
	    }
        
        public static void alertAndBackPage(HttpServletResponse response, String alertText) throws IOException {
	    	// 사용법 : ScriptAlertUtils.alertAndBackPage("아이디가 중복", "/login.do");
	        init(response);
	        PrintWriter out = response.getWriter();
	        out.println("<script>alert('" + alertText + "'); history.go(-1);</script>");
	        out.flush();
	    }
	 
	    public static void alertAndMovePage(HttpServletResponse response, String alertText, String nextPage) throws IOException {
	    	// 사용법 : ScriptAlertUtils.alertAndMovePage("아이디가 중복","/login.do");
	        init(response);
	        PrintWriter out = response.getWriter();
	        out.println("<script>alert('" + alertText + "'); location.href='" + nextPage + "';</script> ");
	        out.flush();
	    }
	 
	   

}

2. Controller 에서 아래와 같은 방법으로 사용

@RequestMapping(value = "/joinPro", method = RequestMethod.POST)
	public String join(EmpBean b, Model model,HttpServletRequest request,HttpSession session,HttpServletResponse response) {

		try {
			int stf_id = (int) session.getAttribute("u_id");
			int cnt = empService.empChk(stf_id);
			if(cnt > 0) {
				ScriptUtils.alertAndBackPage("아이디중복", "/join.do");
			}else {				
                	empService.joinPro(b);
			}
		} catch (Exception e) {			
			e.printStackTrace();
		}
		// /WEB-INF/views/sub3/commuteList.jsp
		return "redirect:/login";
	}
	
반응형