organize/프로젝트

justBoard3 xml설정, 프로그램 설치

001cloudid 2024. 9. 21. 13:55
728x90

프로그램 설치(Maven), JDBC, xml 설정하기

 

xml 설정

들어가기 앞서 프로젝트의 구조에 대해 정리, 사실 매 번 정리하지만 할 때마다 새롭고 익숙해지지 않는 것인지 모르겠음 

  • src/main/java : 작성되는 코드의 경로
  • src/main/resource : 실행할 때 참고하는 기본 경로(주로 설정 파일들을 넣음)
  • src/test/java : 테스트 코드를 넣는 경로
  • src/test/resources : 테스트 관련 설정 파일 보관 경로
  • servlet-context.xml : 웹과 관련된 스프링 설정 파일
  • root-context.xml : 스프링 설정파일
  • views : 템플릿 프로젝트의 jsp 파일 경로
  • web.xml : Tomcat의 web.xml 파일
  • pom.xml : Maven이 사용

 

xml파일을 설정하기 앞서 각각의 xml파일에 대해서 깊게 정리해야할 필요가 있는 것 같음

  • web.xml
    배포 서술자(Deployment Descriptor, DD) Java 웹 애플리케이션의 기본적인 설정을 위해 작성하는 파일
    JSP와 서블릿으로만 구성된 경우에 web.xml을 사용
    web.xml은 WAS에서 톰캣이 최초로 구성될 때 WEB-INF 폴더에 존재하는 web.xml 파일을 읽고 그에 해당하는 웹 애플리케이션을 설정
<?xml version="1.0" encoding="UTF-8"?> <!-- xml 파일이고, 버전 1.0, UTF-8로 인코딩 -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- web.xml의 루트 엘리먼트. 모든 웹 애플리케이션 설정은 web-app 태그 사이에 존재해야함 -->

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param> <!-- context는 이름이나 객체를 바인딩하는 집합의 역할을 담당. 어떠한 객체를 핸들링하기 위한 접근 수단. 사용자가 직접 컨트롤하는 xml파일을 지정해주는 역할 --> <!-- context-param 태그에 설정되어 있는 root-context.xml은 모든 서블릿 필터에서 사용되는 루트 스프링 컨테이너 설정 -->
		<param-name>contextConfigLocation</param-name> <!-- param-name 파라미터 이름 -->
		<param-value>/WEB-INF/spring/root-context.xml</param-value> <!-- param-value 파라미터 값 -->
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener> <!-- 모든 서블릿과 필터에 의해 공유되는 스프링 컨테이너를 생성 -->
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <!-- ContextLoaderListener 클래스가 생성하는 WebApplicationContext는 웹 애플리케이션에서 루트 컨텍스트가 되며, 자식은 루트가 제공하는 객체(bean)을 사용할 수 있음 -->
	</listener>

	<!-- Processes application requests -->
	<servlet> <!-- 애플리케이션의 요청을 처리. 클라이언트가 요청을 보내면 그에 따라 요청을 처리할 수 있는 곳으로 넘겨주고, 결과를 서버쪽 응답을 통해 클라이언트에게 넘겨주는 곳을 지정. 이를 진행하는 것이 DispatcherServlet -->
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 추가 -->
	<filter> <!-- filter 웹 애플리케이션 전반에 걸쳐 특정 URL이나 파일 요청 시 미리 로딩되어 사전에 처리할 작업을 필터링하고 해당 요청을 처리 -->
		<filter-name>encoding</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> <!-- 필터를 적용할 name,servlet, url-pattern등을 지정 -->
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


</web-app>

 

  • root-context.xml
    스프링 MVC 설정과 관련된 여러 처리를 담당
    JSP와는 관련없는 객체(Bean)을 설정
    DB에 접속하기 위한 설정
<?xml version="1.0" encoding="UTF-8"?> <!-- 스프링 MVC설정과 관련된 여러 처리를 담당. JSP와 관련 없는 객체(Bean)을 설정. 비즈니스 로직을 위한 설정을 하고 공통 Bean을 설정. DB에 접속하기 위한 설정 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Seoul"></property>
		<property name="username" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
		<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
	</bean>
		
</beans>

 

위와 같이 작성함. 현재 Maven 프로그램이 설치가 안되어 있어 에러가 뜸. pom.xml에 Maven을 추가해두면 없어질 듯

 

  • servlet-context.xml
    web.xml에서 DispatcherServlet의 설정을 기록
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		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">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven /> <!-- 스프링 MVC에서 @사용가능하게 함 -->

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" /> <!-- 정적 html 문서 리소스들의 정보를 기술 -->

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- InternalResourceViewResolver : JSP와 name을 매핑시켜주는 여할 -->
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.mystory001.justboard" /> <!-- context:component-scan : 해당 패키지에 있는 파일들의 어노테이션을 스캔해서 빈으로 등록하는 역할 -->
	
	
	
</beans:beans>

 

xml 정리 참고 : https://m.blog.naver.com/zzang9ha/222069787161, https://kijuk.tistory.com/142

 

솔직히 정리를 한다고해서 머리속에 정리가 되는 느낌을 받지는 못하는 것 같다. 반복적으로 읽는고 이해하려고 하자.

 

어느 정도 xml 설정이 끝난 것 같다. servlet-context에 클래스 파일 context:component-scan으로 추가해주는 것만 남은 것 같은데, 하다보면 또 추가해야할 게 많을 수도 있을 것 같음. 설정이 더 필요한 부분은 하면서 추가하도록 할 예정

 

프로그램 설치

https://mvnrepository.com/ 여기서 필요한 리파지토리를 복사해서 pom..xml에 붙여주면 된다. 교육 받을 때 분명히 스프링 버전마다 지원하는 것이 조금씩 다르다고 했던 것 같은데... 아무튼 확인이 필요함 대표적으로 사용할 mybatis의 경우

https://mybatis.org/spring/

스프링과 mybatis 버전, java버전도 다 함께 맞춰줘야함.

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mystory001</groupId>
	<artifactId>justboard</artifactId>
	<name>justBoard</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>4.3.8.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
		<dependency>
		   	<groupId>com.mysql</groupId>
		   	<artifactId>mysql-connector-j</artifactId>
		   	<version>8.0.33</version>
		</dependency>
			
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
			
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.1</version>
		</dependency>
					
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.3.1</version>
		</dependency>

		<!-- 데이터를 json 형태로 변경하는 프로그램 jackson-databind 설치 -->
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
    		<groupId>com.fasterxml.jackson.core</groupId>
    		<artifactId>jackson-databind</artifactId>
    		<version>2.15.2</version>
		</dependency>
				
	(...생략...)

 

pom.xml에 추가한 것들이 Maven Dependencies에 추가됨을 알 수 있음

 

+ root-context를 다시 확인해보면 에러가 없어짐

 

동작하는지 확인을 위해 실행 시켜봄

프로젝트하면서 워낙 많이 본 화면인데, 이는 전체 스캔? 확인하면서 xml에 적혀진 파일이 누락되어 있어서 발생하는 경우가 많았다. 아마 root-context.xml에서 Mapper가 있어서 문제가 생긴걸로 판단됨

<?xml version="1.0" encoding="UTF-8"?> <!-- 스프링 MVC설정과 관련된 여러 처리를 담당. JSP와 관련 없는 객체(Bean)을 설정. 비즈니스 로직을 위한 설정을 하고 공통 Bean을 설정. DB에 접속하기 위한 설정 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Seoul"></property>
		<property name="username" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>

<!-- 	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> -->
<!-- 		<property name="dataSource" ref="dataSource"></property> -->
<!-- 		<property name="configLocation" value="classpath:/mybatis-config.xml"></property> -->
<!-- 		<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property> -->
<!-- 	</bean> -->

<!-- 	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache"> -->
<!-- 		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> -->
<!-- 	</bean> -->
		
</beans>

주석 처리 함.

역시 맞았음.. 교육 받은 거 많이 잊어버렸지만.. 진짜 너무 접해본 상황이라 그런지 아직도 기억하고 있네...

 

설정에 맞는 파일을 생성

 

 

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 
</configuration>

이거 없으면 안된 걸로 기억함. 이에 대해 자세히 알아보자

 

mybatis에서 사용될 DB를 연동하기 위한 설정값을 작성. mybatis 실행 시 필요한 설정 정보를 담고 있으며, mybatis 프로젝트에서 가장 기본적인 설정파일임.

→ DB 연동은 root-context에서 설정해뒀기 때문에 따로 해줄 필요가 없는 것 같아보임

 

이제 본격적으로 페이지 만들고 주소 매핑하는 작업을 하면 될 듯..

늘 그렇지만 처음부터 완벽한 웹 애플리케이션이면 좋겠지만, 나 같은 초심자에겐 너무 어렵기도 하고 매 번 수정할 일이 생겨서.. 일단은 차근차근해보도록하자..

src/main/java안의 클래스도 하나하나 수정해야함! 일단 만들어 두기만 했음

 

728x90

'organize > 프로젝트' 카테고리의 다른 글

justBoard6 member  (2) 2024.09.25
justBoard5 화면(view)2  (0) 2024.09.24
justBoard4 화면(view)1  (0) 2024.09.23
justBoard2 DB구축  (0) 2024.09.20
justBoard1 아주 간단한 기능 명세서, 스프링 버전 설정, 화면 구성  (0) 2024.09.19