Interceptor, Cookie(+JSON)
2016. 12. 20. 16:13ㆍProgramming/Spring
목표 : 로그인 안 돼 있을 때,
alert('접근 불가. 먼저 로그인해주세요.') 띄우기
순서 :
1) interceptor 걸릴 영역 지정
2) interceptor 구현
3) 접근 불가시 alert 창 띄우기
1) interceptor 걸릴 영역 지정
<servlet-context.xml>
1 2 3 4 5 6 7 8 9 10 11 | <beans:bean id="loginCheck" class="com.spring.interceptor.LoginCheckInterceptor"/> <interceptors> <interceptor> <mapping path="/*/insert.do"/> <mapping path="/*/delete.do"/> <mapping path="/*/update.do"/> <beans:ref bean="loginCheck"/> </interceptor> </interceptors> | cs |
2) interceptor 구현
ㄱ. HandlerInterceptorAdapter 상속
ㄴ. source > override method
preHandle : 컨트롤러 실행 전
postHandle : 컨트롤러 실행 후
afterCompletion : 모든 작업 완료 후, 요청 처리 중 사용한 리소스 반환시
<LoginCheckInterceptor.java>
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LoginVo loginVo = (LoginVo)request.getSession().getAttribute("loginVo"); if(loginVo!=null){ return true; }else{ response.sendRedirect(request.getContextPath()+"/errorLogin.do"); return false; //false이면 컨트롤러로 넘어가지 않음 } } | cs |
3) 접근 불가시 alert 창 띄우기(java에서 script 이용하기)
1 2 3 4 5 6 7 8 9 | response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<script>"); out.print("alert('접근 권한이 없습니다.');"); out.print("window.history.back();"); out.print("</script>"); out.flush(); | cs |
목표: cookie 이용해 id 기억하기
순서 :
1) remember id? 체크박스 구현
2) @CookieValue로 값(idCookie) 받아오기
3) idCookie의 true/flase에 따라서 쿠키 생성/제거
4) 뷰에서 쿠키 출력
1) remember id? 체크박스 구현
<LoginForm.jsp>
1 2 3 4 5 6 7 | <p>remember id? <input type="checkbox" name="idCookie" <c:if test='${cookie.idCookie !=null}'>checked</c:if> > </p> | cs |
2) @CookieValue로 값(idCookie) 받아오기
<LoginController.java>
1 2 3 4 5 | public String login(Member mem, HttpSession session, RedirectAttributes rttr, HttpServletResponse response ,@CookieValue(value="idCookie", required=false) String idCookieVal){ | cs |
3) idCookie의 true/flase에 따라서 쿠키 생성/제거
<LoginController.java>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //로그인 정보 있을 경우 if(loginVo!=null){ session.setAttribute("loginVo", loginVo); login = 1; url = "/"; //idCookie가 존재할 때(remember id?가 체크됨), 쿠키 저장 if(mem.isIdCookie()){ Cookie c = new Cookie("idCookie", loginVo.getId()); c.setMaxAge(24*60*60*7); response.addCookie(c); }else{ //idCookie가 없으나(쿠키값은 아직 남아있을 때) if(idCookieVal != null){ Cookie c = new Cookie("idCookie", null); c.setMaxAge(0); //쿠키 제거 response.addCookie(c); } } | cs |
4) 뷰에서 쿠키 출력
${cookie.idCookie.value}
목표: cookie를 JSON으로 주고 받기
순서 :
1) jackson 라이브러리 가져오기
2) bean 객체를 JSON화(+퍼센트 인코딩)
3) cookie 인터셉터 구현(퍼센트 디코딩 -> JSON -> bean)
1) jackson 라이브러리 가져오기
<pom.xml>
1 2 3 4 5 6 7 8 9 | <!-- jackson 라이브러리: bean 객체 <-> JSON로 data bind한다. --> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.5</version> </dependency> | cs |
2) bean 객체를 JSON화(+퍼센트 인코딩)
<LoginController.java>
1 2 3 4 5 6 7 8 9 10 11 12 | String loginJson = null; try { //bean 객체(loginVo) --> JSON(loginJson)으로 loginJson = new ObjectMapper().writeValueAsString(loginVo); //퍼센트 인코딩해서 쿠키로 저장 Cookie c = new Cookie("loginCookie", URLEncoder.encode(loginJson, "UTF-8")); c.setMaxAge(60*60*24*7); response.addCookie(c); } catch (JsonProcessingException | UnsupportedEncodingException e) | cs |
3) cookie 인터셉터 구현(퍼센트 디코딩 -> JSON -> bean)
<CookieLoginInterceptor.java>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | if (request.getSession().getAttribute("loginVo") == null) { //WebUtils 이용하면 간편하게 쿠키 받아올 수 있다. Cookie loginCookie = WebUtils.getCookie(request, "loginCookie"); String loginJson = ""; if (loginCookie != null) { //퍼센트 디코딩 loginJson = URLDecoder.decode(loginCookie.getValue(), "UTF-8"); //JSON -> bean 변환 ObjectMapper loginObject = new ObjectMapper(); LoginVo loginVo = loginObject.readValue(loginJson, LoginVo.class); request.getSession().setAttribute("loginVo", loginVo); } } | cs |
'Programming > Spring' 카테고리의 다른 글
AJAX로 댓글 기능 구현 (0) | 2016.12.23 |
---|---|
스프링에서 AJAX 사용하기(+JSON) (0) | 2016.12.22 |
Spring으로 게시판 구현 (0) | 2016.12.16 |
Spring JUnit(단위 테스트), MyBatis (0) | 2016.12.15 |
Spring 기본 (0) | 2016.12.13 |