프로젝트/무인 사물함

[AIoT] 무인 사물함 프로젝트 환경 설정 Config

마달랭 2025. 2. 14. 16:00
반응형

개요

설정 파일(예: config.py, .env 파일)이나 환경 변수는 애플리케이션의 설정을 관리하는 역할을한다.

MVC에서 직접적인 역할을 하지는 않지만, Model, View, Controller 모두에서 사용될 수 있다.

MVC 아키텍처에 포함되지는 않지만, 함께 사용되면서 애플리케이션의 유지보수성과 안정성을 높이는 역할을한다.

 

해당 프로젝트에서는 총 3개의 Config를 작성하였으며, 각각 CORS, Swagger(API 명세), Session 관련 설정을 적용하였다.

 

 

WebConfig.java

package com.a207.smartlocker.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://0.0.0.0:3000")    // React 개발 서버 주소
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

 

CORS 관련 세팅을 위한 설정 파일이다.

@Configuration 어노테이션을 통해 이 클래스가 Spring의 설정 클래스임을 나타낸다.

WebMvcConfigurer 인터페이스를 구현하여 Spring MVC의 설정을 커스터마이징할 수 있다.

여기서는 WebMvcConfigurer의 addCorsMappings() 메서드를 오버라이딩하여 CORS 설정을 추가했다.

 


CorsRegistry 객체를 사용하여 CORS 정책을 설정한다.

registry.addMapping("/**")를 통해 모든 엔드포인트(API 경로)에 대해 CORS를 적용한다.

예를 들어, /api/user, /api/products, /auth/login 등 모든 API 경로에 대해 CORS 허용된다.

 

allowedOrigins("http://0.0.0.0:3000")를 통해 3000번 포트(리액트)에서 오는 모든 IP로의 요청을 받는다.

allowedMethods("*")를 통해 모든 HTTP 메서드를 허용한다.

allowedHeaders("*")를 통해 모든 HTTP 헤더를 허용한다.

allowCredentials(true)를 통해 쿠키 및 인증 정보를 포함한 요청을 허용한다. 즉, JWT 토큰, 세션 쿠키 등을 포함한 요청을 허용하려면 true로 설정해야 한다.

 

 

SwaggerConfig.java

package com.a207.smartlocker.config;

import io.swagger.v3.oas.models.OpenAPI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new io.swagger.v3.oas.models.info.Info()
                        .title("Smart Locker API")
                        .version("1.0.0"));
    }
}

API 정보를 쉽게 보기 위해 Swagger를 사용하면 편하다.

따라서 Swagger 세팅을 위한 Config를 작성해 주었다.

사실상 Swagger 세팅은 @Bean으로 등록해 주는 것이 역할이 다이며 어플리케이션 정보와 pom.xml에 의존성 주입이 필요하다.

 

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 최신 버전 확인 후 사용 -->
</dependency>

 

pom.xml에 위 의존성을 추가해 준다.

 

springdoc:
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true

 

application.yml에 위 사항을 적용해 준다.

 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Swagger UI</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui.css">
    <style>
        body {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
    </style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui-standalone-preset.js"></script>
<script>
    window.onload = () => {
      SwaggerUIBundle({
        url: "/v3/api-docs", // OpenAPI 문서 경로
        dom_id: '#swagger-ui',
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        layout: "StandaloneLayout"
      });
    };
</script>
</body>
</html>

 

Swagger의 기본 UI를 사용하기 위해 html파일을 작성해 준다.

해당 내용은 resource/static 디렉토리 내부에 위치하면 된다.



style.css

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
}

header {
    background-color: #4CAF50;
    color: white;
    text-align: center;
    padding: 20px;
}

main {
    padding: 20px;
    text-align: center;
}

button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #45a049;
}

footer {
    background-color: #333;
    color: white;
    text-align: center;
    padding: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
}

 

Swagger의 기본 UI에 CSS를 입혀주기 위한 파일이다.

마찬가지로 resource/static 디렉토리 내부에 위치하면 된다.



SessionConfig.java

package com.a207.smartlocker.config;

import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SessionConfig {
    @Bean
    public HttpSessionListener httpSessionListener() {
        return new HttpSessionListener() {
            @Override
            public void sessionCreated(HttpSessionEvent se) {
                se.getSession().setMaxInactiveInterval(3600); // 30분
            }
        };
    }
}

 

HttpSession 관리를 위한 설정 파일이다.

@Configuration 어노테이션을 통해 해당 클래스가 Spring의 설정 클래스임을 명시해 준다.

@Bean 어노테이션을 통해 이 메소드에서 반환된 객체를 Spring 컨테이너의 으로 등록한다.

 

내부 메소드는 HttpSessionListener 빈을 생성하고 반환한다. HttpSessionListener는 HTTP 세션 이벤트를 처리하는 리스너로, 세션 생성 및 만료 이벤트를 감지할 수 있다.


HttpSessionListener는 세션 이벤트를 처리하기 위한 인터페이스로, sessionCreated() 메서드는 세션이 생성될 때 호출된다.

HttpSessionEvent 객체는 생성된 세션에 대한 정보를 제공하고, getSession()을 호출하면 세션 객체를 가져올 수 있고, setMaxInactiveInterval(int interval) 메서드를 사용해 세션의 최대 비활성 시간을 설정할 수 있다.

만약 세션이 1시간 동안 아무런 요청도 받지 않으면 자동으로 만료된다.

728x90
반응형