레이어드 아키텍처(Layered Architecture) 실습2

oyeon·2021년 1월 26일
0
post-custom-banner

환경 설정

1. WebMvcContextConfiguration.java

package kr.or.connect.guestbook.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "kr.or.connect.guestbook.controller" })
public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
    }
 
    // default servlet handler를 사용하게 합니다.
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
   
    @Override
    public void addViewControllers(final ViewControllerRegistry registry) {
    	System.out.println("addViewControllers가 호출됩니다. ");
        registry.addViewController("/").setViewName("index");
    }
    
    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

2. DBConfig.java

package kr.or.connect.guestbook.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/* @EnableTransactionManagement는 트랜잭션과 관련된 설정을 자동으로 해준다.
 * 단, 사용자 간의 트랜잭션 처리를 위한 PlatformTransactionManager를 설정하기 위해서는
 * TransactionManagementConfigurer을 구현하고 
 * annotationDrivenTransactionManager() 메서드를 오버라이딩 해야한다.
 */

@Configuration
@EnableTransactionManagement
public class DBConfig implements TransactionManagementConfigurer {
	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String DB_URL= "jdbc:mysql://localhost:3306/connectdb?serverTimezone=UTC";
	private static final String DB_ID = "connectuser";
	private static final String DB_PASSWORD = "connect123!@#";

	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(DRIVER);
		dataSource.setUrl(DB_URL);
		dataSource.setUsername(DB_ID);
		dataSource.setPassword(DB_PASSWORD);
		return dataSource;
	}

	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return transactionManger();
	}

	@Bean
	public PlatformTransactionManager transactionManger() {
		return new DataSourceTransactionManager(dataSource());
	}
}

3. ApplicationConfig.java

package kr.or.connect.guestbook.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = { "kr.or.connect.guestbook.dao",  "kr.or.connect.guestbook.service"})
@Import({ DBConfig.class })
public class ApplicationConfig {

}

4. web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
  <display-name>Spring JavaConfig Sample</display-name>
  <context-param>
  	<param-name>contextClass</param-name>
  	<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>kr.or.connect.guestbook.config.ApplicationConfig</param-value>
  </context-param>
  
  <!-- Layered 아키텍처 특성상 분리한 ApplicationConfig, DBConfig를 읽어 들이는 부분 -->
  <!-- listener : 특정한 이벤트가 일어났을 때 동작 -->
  <!-- Context가 로딩되는 이벤트가 일어났을 때 ContextLoaderListener클래스를 실행 -->
  <!-- 실행되면 위의 코드 context-param에 등록된 부분을 참고한다. -->
  <!-- 즉, ApplicationConfig의 설정 파일을 읽어들이고, -->
  <!-- contextClass는 AnnotationConfigWebApplicationContext을 사용  -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
    <!-- 설정 파일 클래스가 등록되고 있다. 항상 패키지명까지 포함해서 등록해야 한다. -->
    <!-- AnnotationConfigWebApplicationContext를 사용할 것이다. 컨테이너 등록 -->
    <init-param>
      <param-name>contextClass</param-name>
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>kr.or.connect.guestbook.config.WebMvcContextConfiguration</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <!-- mvc라는 이름을 가진 sevlet element 안에 있는 mvc를 찾고 그곳에 등록되어 있는 servlet-class를  본다. --> 
  <!-- Spring이 제공하고 있는 DispatcherServlet를 FrontController로 하는 것을 볼 수 있다. -->
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- spring이 제공하는 CharacterEncodingFilter을 등록하여 한글 인코딩 처리 -->
  <!-- 모든 요청에 대해 적용하고 싶기 때문에 url-pattern을 /*로 설정 -->
  <filter>
  	<filter-name>encodingFilter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter
  	</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Redirect

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	response.sendRedirect("list");
%>

결과

profile
Enjoy to study
post-custom-banner

0개의 댓글