기억의 DataBase

Spring Framework를 활용한 방명록 - 1.설정 본문

Spring

Spring Framework를 활용한 방명록 - 1.설정

Zester; 2019. 3. 31. 21:47


Maven Project 생성

  • pom.xml 
 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.5.RELEASE</spring.version>
        <jackson2.version>2.8.6</jackson2.version>
 </properties>   

 

버전을 상수로 지정하기 위한 <properties> 설정(추후 버전이 바뀌면 이 부분만 수정하면 됨)

      <build>
            <plugins>
                  <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.6.1</version>
                        <configuration>
                              <source>1.8</source>
                              <target>1.8</target>
                        </configuration>
                  </plugin>
            </plugins>
      </build
사용하는 JDK에 맞는 플러그인 설정

 

            <!-- SPRING -->
            <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-context</artifactId>
                  <version>${spring.version}</version>
            </dependency>
            <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-tx</artifactId>
                  <version>${spring.version}</version>
            </dependency>
            <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-webmvc</artifactId>
                  <version>${spring.version}</version>
            </dependency>
            <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-jdbc</artifactId>
                  <version>${spring.version}</version>
            </dependency>

Spring 사용에 필요한 라이브러리들
( spring-context / spring-tx / spring-webmvc / spring-jdbc )

          <!-- Servlet JSP JSTL -->
            <dependency>
                  <groupId>javax.servlet</groupId>
                  <artifactId>javax.servlet-api</artifactId>
                  <version>3.1.0</version>
                  <scope>provided</scope>
            </dependency>
            <dependency>
                  <groupId>javax.servlet.jsp</groupId>
                  <artifactId>javax.servlet.jsp-api</artifactId>
                  <version>2.3.1</version>
                  <scope>provided</scope>
            </dependency>
            <dependency>
                  <groupId>javax.servlet</groupId>
                  <artifactId>jstl</artifactId>
                  <version>1.2</version>
            </dependency>

 

Servlet, JSP, JSTL 사용에 필요한 라이브러리들
( javax.servlet-api / javax.servlet.jsp-api / jstl )  

 

            <!-- MYSQL -->
            <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>5.1.45</version>
            </dependency>
            <!-- DATASOURCE -->
            <dependency>
                  <groupId>org.apache.commons</groupId>
                  <artifactId>commons-dbcp2</artifactId>
                  <version>2.1.1</version>
            </dependency>

DB 사용을 위한 라이브러리들
( mysql-connector-javacommons-dbcp2(datasource) )

            <!-- Jackson Module -->
            <dependency>
                  <groupId>com.fasterxml.jackson.core</groupId>
                  <artifactId>jackson-databind</artifactId>
                  <version>${jackson2.version}</version>
            </dependency>
            <dependency>
                  <groupId>com.fasterxml.jackson.datatype</groupId>
                  <artifactId>jackson-datatype-jdk8</artifactId>
                  <version>${jackson2.version}</version>
            </dependency
JSON 사용을 위한 라이브러리들
( jackson-databind / jackson-datatype-jdk8
※ 기타 설정


pom.xml 설정이 끝난 후, Maven Update 잊지말 것
 


Navigator 탭에서 facet.xml 파일 확인


 
java 버전을 현재 사용하는 jdk 버전으로(플러그인 설정 빼먹으면 1.5가 기본)
jst.web(Servlet) 버전을 3.1(상황에 맞게)
변경한 후에 이클립스 재시작

Maven Update에서 플러그인 빼먹고 이후에 변경하면,  jst.web(Servlet) 버전을 3.1로 변경할 때 에러발생
메이븐 > jst.web(Servlet) 설정 순서 꼭 지킬 것!

  • WebMvcContextConfiguration


src > main 밑에 java 폴더 생성

 

java 폴더에 설정 파일들을 모아두는 config 패키지 생성


WebMvcConfigurerAdapter상속 받은 WebMvcContextConfiguration 클래스 생성

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

@Configuration : 설정 클래스임을 지정
@EnableWebMvc : 기본적인 mvc 설정을 자동으로
@ComponentScan(basePackages ={패키지 경로}) : 해당 패키지 경로에 있는 클래스의 Component들을 탐색

 

※ 아래 메소드들은 DispatcherServlet 설정을 위해, WebMvcConfigurerAdapter오버라이딩한 메소드들

 

 //URL 요청이 css, img, js인 경우를 처리

 @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);
 }

 

 

 // Mapping 정보가 없는 URL요청이 들어왔을 때, 
 // Spring의 DefaultServletHttpRequestHandler가 처리
 // (WAS의 default
servlet이 static 한 자원을 읽어서 보여줌)

 @Override

public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){

     configurer.enable();
}

 

 

 // 특정 URL에 대한 처리를 Controller를 작성하지 않고, Mapping할 수 있도록 하는 부분
 // ("/"라고 요청이 들어오면(특정 URL이 없다면) "index.jsp"가 보여짐)

 @Override
 public void addViewControllers(final ViewControllerRegistry registry) {
      System.out.println("addViewControllers가 호출됩니다. ");
      registry.addViewController("/").setViewName("index");
 }
     

 

 // ViewResolver를 생성하여, setPrefixsetSuffix를 통해 정확한 경로를 지정함
   (/WEB-INF/views/index.jsp)
 @Bean
 public InternalResourceViewResolver getInternalResourceViewResolver() {
       InternalResourceViewResolver resolver = new InternalResourceViewResolver();
       resolver.setPrefix("/WEB-INF/views/");
       resolver.setSuffix(".jsp");
       return resolver;
 }

 


  • DBConfig


TransactionManagementConfigurer인터페이스로 하는 DBConfig 클래스 생성

 

public
class DBConfig3 implements TransactionManagementConfigurer {
      
 private String driverClassName = "com.mysql.jdbc.Driver";

 private String url = "jdbc:mysql://localhost:3306/DB이름?useUnicode=true&characterEncoding=utf8";

 private String username = "이름";
 private String password = "비밀번호"; 

 

DataSource 객체 생성을 위한, DB 접속 정보

 @Bean
 public DataSource dataSource() {
       BasicDataSource dataSource = new BasicDataSource();
       dataSource.setDriverClassName(driverClassName);
       dataSource.setUrl(url);
       dataSource.setUsername(username);
       dataSource.setPassword(password);
       return dataSource;

 }

      
 @Override
 public PlatformTransactionManager annotationDrivenTransactionManager() {
       return transactionManager();
 }
      
 @Bean
 public PlatformTransactionManager transactionManager() {
       return new DataSourceTransactionManager(dataSource());
 }

 

}

 

DB 접속 정보를 담은 DataSource 객체를 transactionManager를 통해 전달


  • ApplicationConfig
@Configuration
@ComponentScan(basePackages={"kr.or.connect.guestbook3.dao3","kr.or.connect.guestbook3.service3"})
@Import({DBConfig3.class})
public class ApplicationConfig3 {
}

@Configuration : 설정 클래스임을 지정
@ComponentScan(basePackages={"패키지 경로"}) : Component로 참조할 패키지 경로를 지정
@Import({DBConfig3.class}) : DBConfig 클래스의 설정도 ApplicationConfig 클래스의 설정이 적용될 때 함께 적용

 

  • web.xml
<servlet>

 

<servlet-name>mvc</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

 

      <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.guestbook3.config.WebMvcContextConfiguration3

              </param-value>

      </init-param>      

 

      <load-on-startup>1</load-on-startup>

 

</servlet>

     
<servlet-mapping>
      <servlet-name>mvc</servlet-name>
      <url-pattern>/</url-pattern>
</servlet-mapping>

<url-pattern>/</url-pattern> 에 따라 "/"가 URL로 입력되면
<servlet-name>mvc</servlet-name>에 해당하는
<servlet>을 찾아
서블릿의 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 사용
<param-name>contextClass</param-name>과
<param-name>contextConfigLocation</param-name> 설정을
DispatcherServlet에 적용

 

<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.guestbook3.config.ApplicationConfig3
     </param-value>
</context-param>
      
<listener>
     <listener-class>
        org.springframework.web.context.ContextLoaderListener
     </listener-class>
</listener>

 

서버를 실행시킬 때, ContextLoading이 일어나면 이를 감지하고
<context-param>에 해당하는 설정들(contextClass, contextConfigLocation - ApplicationConfig)을 적용

      <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>

URL 입력/변경 시에 UTF-8, 한글입력에 문제가 없도록
어떤 URL을 입력해도(<url-pattern>/*</url-pattern>) 필터로 처리해주는 설정

'Spring' 카테고리의 다른 글

Spring Framework를 활용한 방명록 - 3. Service/Controller/JSP  (0) 2019.04.05
Spring Framework를 활용한 방명록 - 2. DB/DTO/DAO(Repository)  (0) 2019.04.04
Spring MVC  (0) 2019.03.25
Spring JDBC  (0) 2019.03.22
Java Config를 통한 IoC/DI  (0) 2019.03.21
Comments