티스토리 뷰

728x90
반응형

개발 환경

java 21.0.4 2024-07-16 LTSJava(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)

Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)

 

Tomcatv 10.1

EclipseVersion: 2024-06 (4.32.0)Build id: 20240606-1231


pom.xml

<dependencies>
    <!--https://mvnrepository.com/artifact/org.springframework/spring-webmvc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.1.11</version>
    </dependency>
    <!--https://mvnrepository.com/artifact/org.springframework/spring-context-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.1.11</version>
    </dependency>

    <!--https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api-->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.0.0</version>
        <scope>provided</scope> <!-- 배포 시에는 포함되지 않습니다. -->
    </dependency>

    <!--https://mvnrepository.com/artifact/jakarta.servlet.jsp.jstl/jakarta.servlet.jsp.jstl-api-->
    <dependency>
        <groupId>jakarta.servlet.jsp.jstl</groupId>
        <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
        <version>3.0.0</version>
    </dependency>
    <!--https://mvnrepository.com/artifact/org.glassfish.web/jakarta.servlet.jsp.jstl-->
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jakarta.servlet.jsp.jstl</artifactId>
        <version>3.0.1</version>
    </dependency>
</dependencies>

web.xml

<!-- DispatcherServlet -->
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:dispatcherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

dispatcherServelt.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           https://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context 
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc 
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- spring MVC annotation(@)을 사용하기 위한 설정 -->
	<mvc:annotation-driven />
	<!-- controller 를 처리할 view 위치 및 확장자명 설정 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- base-package 속성에 지정된 패키지와 그 하위 패키지에 있는 모든 클래스를 스캔합니다. -->
	<context:component-scan base-package="com.interceptor" />


	<mvc:interceptors>
		<!-- 다국어 interceptor -->
		<mvc:interceptor>
			<mvc:mapping path="/interceptor/locale" />
			<bean class="com.interceptor.config.LocaleInterceptor"></bean>
		</mvc:interceptor>
		
		<!-- 로그인 interceptor -->
		<mvc:interceptor>
		 	<mvc:mapping path="/**"/>
		 	<mvc:exclude-mapping path="/interceptor/test"/>
	        <mvc:exclude-mapping path="/interceptor/login"/>
	        <mvc:exclude-mapping path="/interceptor/register"/>
	        <mvc:exclude-mapping path="/css/**"/>
	        <mvc:exclude-mapping path="/js/**"/>
			<bean class="com.interceptor.config.LoginInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
	<!-- Define the message source for loading localized messages -->
	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:locale/messages" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>

</beans>

LocaleInterceptor.java

 

package com.interceptor.config;

import java.util.Locale;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class LocaleInterceptor implements HandlerInterceptor {
	
	@Override // 컨트롤러 실행 전
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
        String localeParam = request.getParameter("locale");
        
        Locale locale;
        if (localeParam != null) {
            locale = Locale.forLanguageTag(localeParam);
        } else {
            locale = Locale.KOREAN;
        }

        session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
        return true;
	}

	@Override // 컨트롤러 실행 후 DispatcherServlet이 뷰로 보내기 전에 호출됩니다.
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override // 뷰까지 수행하고 나서 호출됩니다.
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	
}

LoginInterceptor.java

package com.interceptor.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loggedInUser"); // 세션에 저장된 로그인 사용자 정보 확인

        if (user == null) { // 로그인이 되어 있지 않다면
            response.sendRedirect("/interceptor/login"); // 로그인 페이지로 리다이렉트
            return false; // 요청을 처리하지 않음
        }

        return true; // 로그인이 되어 있으면 계속 진행
    }
}

InterceptorController.java

 

package com.interceptor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class InterceptorController {
	
	@GetMapping("/interceptor/locale")
	public String locale() {
		return "redirect:/";
	}
	
	@GetMapping("/interceptor/test")
	public ModelAndView test() {
		ModelAndView modelAndView = new ModelAndView("/interceptor/test");
		return modelAndView;
	}
	
	@GetMapping("/interceptor/login")
	public ModelAndView login() {
		ModelAndView modelAndView = new ModelAndView("/interceptor/login");
		
		return modelAndView;
	}
	
}

test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        function changeLocale(locale) {
            $.ajax({
                url: '/interceptor/locale',  // AJAX 요청을 처리할 URL
                type: 'GET',
                data: { locale: locale },
                success: function() {
                    location.reload();  // 페이지 새로 고침
                },
                error: function(error) {
                    console.log("Error: " + error);
                }
            });
        }
    </script>
<title>Insert title here</title>
</head>
<body>
	<a href="javascript:void(0);" onclick="changeLocale('ko')"> 한국어 </a>
    <br>
    <a href="javascript:void(0);" onclick="changeLocale('us')"> English </a>
	<br><br>
	
	<input type="button" value="<spring:message code="button.title" text="default text" />" />
	<br><br>
	<spring:message code="default.language" text="exception text" />
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	this is a login page.
</body>
</html>

호출

다국어
http://localhost:8080/interceptor/test

로그인
http://localhost:8080/interceptor/login

프로젝트 구조


추가 정보

Filter, DispatcherServlet, Interceptor 등의 차이점이나 사용 목적에 대해서 추가로 공부해야 할것 같다.

728x90
반응형