본 포스팅의 예제는 STS 또는 Eclipse를 사용하지 않고 Intellij를 통해 구현하고 있습니다.
그래서 기존의 STS(Spring Tool Studio)에서 생성된 Spring 프로젝트의 스프링 관련 설정 파일명과
프로젝트 구조가 약간 다를 수 있습니다.Intellij 스프링 mvc 프로젝트 생성 포스팅을 참고해주시면 감사하겠습니다.
Spring-MVC 기본 개념 및 테스트 예제 관련 포스팅 링크
순서 | 포스팅 제목 |
1 | Intellij에서 Spring MVC Project 생성하기 |
2 | Spring MVC - MariaDB 연결테스트 |
3 | Spring MVC - Mybatis 설정 및 테스트 |
4 | SpringMVC 구조 |
5 | SpringMVC + Mybatis |
6 | Spring MVC Controller 작성 연습 |
7 | Spring Interceptor |
Spring-MVC 게시판 예제 이전 포스팅 링크
1. 인터셉터 권한 체크 구현하기
1.1 인터셉터 적용을 위한 클래스 생성
src/기본패키지/commons/interceptor/ 패키지 안에 AuthenticationInterceptor 클래스 파일을 생성 후 아래와 같이 내용을 작성 해주세요.
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Override
@LogException
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/* session 객체를 가져옴 */
HttpSession session = request.getSession();
/* login처리를 담당하는 사용자 정보를 담고 있는 객체를 가져옴 */
Object obj = session.getAttribute("sessionUser");
/* 로그인이 안되있을 경우 */
if (obj == null) {
saveDestination(request);
response.setCharacterEncoding("UTF-8");
// 로그인이 안되어 있는 상태임으로 로그인 페이지로 되돌려보냄
response.sendRedirect("/user/login");
/*컨트롤러 수행하지 않게끔 리턴 false로 반환*/
return false;
}
return true;
}
// 로그인 페이지 이동 전 페이지 저장
private void saveDestination(HttpServletRequest request) {
String uri = request.getRequestURI(); // 현재 페이지
String query = request.getQueryString(); // 쿼리
if (query == null || query.equals("null")) {
query = "";
} else {
query = "?" + query;
}
// 현재 페이지 + get 파라미터 저장
if (request.getMethod().equals("GET")) {
request.getSession().setAttribute("destination", uri + query);
}
}
@Override
@LogException
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("TEST");
}
}
1.2 인터셉터 적용을 위한 컨트롤러 구현
src/기본패키지/main/controller 패키지 안에 HomeController 클래스 파일에 아래와 같이 내용을 변경 해줍니다.
@Controller
public class HomeController {
@GetMapping(value = "/")
@LogException
public String homePage(HttpSession session) {
String destination = (String) session.getAttribute("destination");
if (destination != null) {
session.removeAttribute("destination");
}
return "home";
}
@GetMapping(value = "/user/login")
@LogException
public String loginPage(HttpSession session) {
if (session.getAttribute("destination") == null || session.getAttribute("sessionUser") != null) {
return "redirect:../";
}
return "home";
}
}
1.3 인터셉터 적용을 위한 dispatcher-servlet.xml 설정
web-inf/spring/appServlet 패키지 안에 dispatcher-servlet.xml 파일에 아래와 같이 내용을 추가 해줍니다.
<!-- 로그인 권한 인증 요청 인터셉터 -->
<beans:bean id="authentication" class="com.spring.practice.commons.interceptor.AuthenticationInterceptor" />
<interceptors>
<interceptor>
<mapping path="/user/profile"/>
<beans:ref bean="authentication" />
</interceptor>
</interceptors>
1.4 인터셉터 화면 확인
2. 정리
이번에는 인터셉터를 활용한 로그인 여부 체크를 구현 해 보았습니다. 다음에는 계정 복구 기능을 만들어 보도록 하겠습니다.
'스프링 프레임워크 > 스프링 MVC' 카테고리의 다른 글
# Spring MVC 게시판 예제 13 : 자동 로그인 기능 구현 (0) | 2023.03.07 |
---|---|
# Spring MVC 게시판 예제 12 : 계정 복구 (0) | 2023.03.05 |
# Spring MVC 게시판 예제 10 : 내 프로필 페이지 구현하기 (0) | 2023.02.25 |
# Spring MVC 게시판 예제 09 : 아이디 및 비밀번호 찾기 구현 (0) | 2023.02.24 |
# Spring MVC 게시판 예제 08 - HttpSession을 이용한 로그인 (2) | 2023.02.24 |
댓글