-
자바 웹 개발 개발환경 세팅(9) Spring Project 3Spring Legacy/개발 환경 2020. 11. 26. 17:12
1. JAR 파일 적용하기 (mariadb-java-client-2.6.2.jar)
- src > main > webapp > resources에 lib 폴더를 생성합니다.
- mvnrepository.com에 접속 후 mariadb-java-client 검색
- 맨 위에 있는 mariaDB Java Client 클릭
- 2.6.2 버전 클릭 후 Files의 jar(606KB)를 다운로드
- 다운로드 받은 jar파일을 lib폴더에 넣습니다.
- 해당 jar파일을 우클릭 > Build Path > Add to Build Path 클릭합니다.
2. DB 연결 테스트
- src/main/resourrces > log4j.xml 파일 우클릭 > Refactor > Rename 클릭 후 log4j2.xml로 이름 변경합니다.
- log4j2.xml에 아래의 코드를 복사하여 붙입니다.
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN" monitorInterval="30"> <Properties> <Property name="baseDir">C:/_spring/workspace/logs</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS}[%t]%-5level %logger{36}-%msg%n" /> </Console> <RollingFile name="RollingFile" fileName="${baseDir}/app.log" filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.zip"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="20 MB" /> </Policies> <DefaultRolloverStrategy max="20" /> </RollingFile> </Appenders> <Loggers> <Logger name="java.sql" level="INFO" additivity="false"> <AppenderRef ref="Console" /> </Logger> <Logger name="jdbc.sqltiming" level="INFO" additivity="false"> <AppenderRef ref="Console" /> </Logger> <Logger name="com" level="INFO" additivity="false"> <AppenderRef ref="Console" /> </Logger> <Logger name="org.springframework" level="INFO" additivity="false"> <AppenderRef ref="Console" /> </Logger> <Root level="debug"> <AppenderRef ref="Console" /> <AppenderRef ref="RollingFile"/> </Root> </Loggers> </Configuration> <!-- http://logging.apache.org/log4j/2.x/manual/appenders.html#ConsoleAppender --> <!-- http://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender -->
- Spring폴더 > workspace안에 logs 폴더를 생성합니다. logs 폴더는 logger의 저장소입니다.
- src /test/java > com.project.ctrl에 클래스를 생성합니다.
- 클래스 명 : JDBCTest
- JDBCTest.java에 아래의 코드를 복사하여 붙입니다.
package com.project.ctrl; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DriverManager; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JDBCTest { private static Logger Log = LoggerFactory.getLogger(JDBCTest.class); static { try { Class.forName("org.mariadb.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Test public void testConnection() { try (Connection cn = DriverManager.getConnection( "jdbc:log4jdbc:mysql://localhost:3306/project","root","root")){ Log.info(">>>jdbc test ok :" +cn); }catch(Exception e) { fail(e.getMessage()); }; } }
- JDBCTest.java 우클릭 > Run As > JUnit Test 실행
- 오른쪽 아래와 같이 >>>jdbc test ok 로그가 뜨면 잘 테스트 완료입니다.
3. 로그 속도 향상
- 로그가 늦게찍일때 캐싱을 사용해 로그 속도를 좀 더 빠르게 해 줍니다.
- src/main/resources 에 File 생성합니다.
- File 명 : log4jdbc.log4j2.properties
- log4jdbc.log4j2.properties에 아래 코드를 복사하여 붙입니다.
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
4. Mybatis
- src/main/resources 에 xml 파일 생성
- 파일명 : MybatisConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.project.domain"/> </typeAliases> </configuration>
5. Web.xml Setting
- src > main > webapp > WEB-INF > web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" 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_3_1.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <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> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
6. 기본 패키지 생성
- src/main/resources에 mappers 패키지 생성
- src/main/java에 com.project.domain 패키지 생성
- src/main/java에 com.project.persistence 패키지 생성
- src/main/java에 com.project.service 패키지 생성
7. Root-context.xml Setting
- DB를 사용하기 위한 Mybatis 세팅입니다.
- src > main > webapp > WEB-INF > spring > root-context.xml
- jdbcUrl은 localhost: 포트번호/데이터베이스명, username과 passower는 디비 아이디와 비밀번호를 입력합니다.
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- Root Context: defines shared resources visible to all other web components --> <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close"> <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property> <property name="jdbcUrl" value="jdbc:log4jdbc:mysql://localhost:3306/project"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id ="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:/MybatisConfig.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> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven/> <context:component-scan base-package="com.project.persistence"></context:component-scan> <context:component-scan base-package="com.project.service"></context:component-scan> </beans>
8. Servlet-context Setting
- 컨트롤러에서 받은 리퀘스트를 재해석합니다.
- src > main > webapp > WEB-INF > spring > appServlet > servlet-context.xml
<?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 /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- 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"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="com.project.ctrl" /> </beans:beans>
9. 서버 실행 & 결과
톰캣 설치 및 적용 참고 페이지 : adimkim900.tistory.com/6
자바 웹 개발 개발환경 세팅(5) Tomcat 설치하기
1. tomcat.apache.org/ tomcat 홈페이지에 접속합니다. 2. tomcat 다운로드 페이지를 클릭합니다. 저는 tomcat8.5.55 버전을 받아 보겠습니다. 왼쪽 Download에서 Tomcat 8을 클릭합니다. Quick Navigation에서..
adimkim900.tistory.com
'Spring Legacy > 개발 환경' 카테고리의 다른 글
자바 웹 개발 개발환경 세팅(8) Spring Project 2 (0) 2020.11.24 자바 웹 개발 개발환경 세팅(7) Spring Project 1 (0) 2020.10.05 자바 웹 개발 개발환경 세팅(6) MariaDB 설치 (0) 2020.09.28 자바 웹 개발 개발환경 세팅(5) Tomcat 설치하기 (0) 2020.09.24 자바 웹 개발 개발환경 세팅(4) 이클립스 기본 세팅 (0) 2020.09.23