AJAX로 인터셉터 구현하기
2016. 12. 27. 16:45ㆍProgramming/Spring
순서:
1) 인터셉터
2) 뷰.jsp
1) 인터셉터
AjaxLoginCheckInterceptor.java
public class AjaxLoginCheckInterceptor extends HandlerInterceptorAdapter{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LoginVo loginVo = (LoginVo)request.getSession().getAttribute("loginVo"); boolean login = false; if(loginVo!=null){ login = true; }else{ // /errorLogin.do로 redirect하는 대신 JSON으로 포장해 response한다. response.setContentType("application/json; charset=UTF-8"); response.getWriter().append("{\"login\":-2}"); } //'login=true'이어야 다음 페이지로 넘어간다. return login; } }
2) 뷰.jsp
Comments.jsp
var insertComments = function(formVal) { var http; var url = contextPath + "/comments/"; //JSON 형식으로 요청(send)할 준비 var formDataJson = JSON.stringify({ board_num : formVal.board_num.value, mem_num : formVal.mem_num.value, content : formVal.content.value }); if (window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http = new ActiveXObject(); } http.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var insertJson = JSON.parse(this.responseText); if (insertJson["insert"] > 0) { alert("저장 성공"); loadComments(); //저장 실패시 } else { if(insertJson["login"]==-2){ window.confirm("로그인시 이용가능합니다. 로그인하시겠습니까?") }else{ alert("저장 실패"); } } } } http.open("POST", url, true); //JSON 형식으로 요청(send) http.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); http.send(formDataJson); }
'Programming > Spring' 카테고리의 다른 글
Spring으로 파일 수정, 게시글+댓글 삭제 (0) | 2016.12.30 |
---|---|
Spring으로 파일 업로드 (0) | 2016.12.28 |
AJAX로 페이징 구현하기 (0) | 2016.12.27 |
AJAX로 댓글 기능 구현 (0) | 2016.12.23 |
스프링에서 AJAX 사용하기(+JSON) (0) | 2016.12.22 |