Maven-web project 생성

jeongwoo·2022년 6월 16일
0

Java 프로젝트

목록 보기
2/9
post-thumbnail

Maven-web(app) project 생성

1. eGovFrame 선택

2. 우클릭 - [new] - [project]

  • [Maven] - [Maven Project] 선택 후 Next 클릭

  • Next 클릭

  • Filter에서 web 검색 후 org.apache.maven.archetypes(Group Id) 선택

  • Group Id와 Artifact Id를 작성 후 Finish
    • Group Id: 프로젝트를 식별하는 유일한 값으로 보통 네이밍 룰(회사 도메인을 거꾸로 작성)을 따를 것을 권장한다.
    • Artifact Id: 버전이 없는 jar 파일의 이름으로 프로젝트 이름으로 사용된다.
  • cf) Package는 Group Id + "." + Artifact Id로 자동완성된다.

project 셋팅

1. [godgamez] - JRE System Library [J2SE - 1.5] 우클릭 - [Properties]

  • J2SE-1.5 (jdk)를 JavaSE-1.8 (jdk)로 변경 후 Apply and Close

2. 프로젝트(godgamez) 우클릭 - [Build path] - [Configure Build Path...]

  • Source 탭에 있는 (missing)표시 된 두 폴더를 제거(Remove)

  • [Add Folder...] - main 클릭 후 [Create New Folder...]

  • Folder name에 java 입력 후 Finish
    • src/main 밑에 java코드로 작성한 Class를 둘 java소스폴더

  • OK 클릭

  • Apply and Close 클릭

3. src/main/webapp에 위치한 index.jsp파일 제거

4. MYBOX > 코딩 > spring > web에서 web.xml, pom.xml, context.xml, app.xml, sqlMapConfig.xml 다운

  • src/main/webapp/WEB-INF에 위치한 기존 web.xml에 덮어쓰기
  • 기존 pom.xml에 덮어쓰기

  • src/main/webapp에 META-INF폴더를 만들고 그 아래 context.xml파일을 둔다.

  • src/main/java와 src/main/resources 밑에 songjeongwoo.godgamez 루트 패키지를 만든다.
  • scr/main/resources/songjeongwoo/godgamez 아래 config 패키지 생성 후 app.xml파일과 sqlMapConfig.xml파일을 둔다.
    • cf) app.xml은 Spring Container에서, sqlMapConfig.xml은 mybatis-spring에서 사용할(읽을) 것이다.
    • cf2) mybatis-spring마이바티스와 스프링을 편하고 간단하게 연동해주는 연동모듈이다.

5. pom.xml 추가 및 변경

  • groupId와 artifactId를 프로젝트 생성 시 썼던 것으로 작성
  • properties와 dependecies 추가
<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 
  		http://maven.apache.org/maven-v4_0_0.xsd'>
	<modelVersion>4.0.0</modelVersion>
	<groupId>songjeongwoo</groupId>
	<artifactId>godgamez</artifactId>
	<packaging>war</packaging> <!-- webapp에선 war파일로 패키징한다(약속). -->
	<version>0.0.1-SNAPSHOT</version>
	<name>spring.web Maven Webapp</name>
	<url>http://maven.apache.org</url>
	
	<properties>
		<spring.ver>5.3.4</spring.ver>
	</properties>
	
	<dependencies>
		<dependency> 
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.ver}</version> <!-- 확장성을 위해 EL로 표시 -->
			<!-- <scope>의 디폴트는 compile이다. -->
		</dependency>
		<dependency> <!-- 앱에서 servlet을 쓰기 위한 dependency, 이게 없을 경우 *.jsp에서 컴파일에러 발생 -->
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope> <!-- compile동안 쓰고 runtime 시에는 WAS의 servlet lib(dependency)를 쓰겠다. -->
		</dependency>
		<dependency> <!--lombok lib -->
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.18</version>
			<scope>provided</scope>
		</dependency>
		<dependency> <!-- 액션태그 c, jstl lib -->
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency> <!-- mybatis-spring -->
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.6</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId> <!-- jdbc: DB연결관련 -->
			<version>${spring.ver}</version>
		</dependency>
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<version>19.8.0.0</version>
		</dependency>
		<dependency> <!-- hibernate-validator -->
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.1.5.Final</version>
		</dependency>
		<dependency> <!--(ajax를 위한)json -->
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-jsr310</artifactId>
			<version>2.11.1</version>
		</dependency>
		<dependency> <!-- 첨부파일 -->
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency> <!-- 메일 -->
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.ver}</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.6.2</version>
		</dependency>
	</dependencies>
</project>

6. src/main/webapp/WEB-INF에 있는 web.xml에서 < servlet>이후를 작성

<?xml version='1.0' encoding='utf-8'?>
<web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
	xmlns='http://xmlns.jcp.org/xml/ns/javaee' 
	xsi:schemaLocation='http://xmlns.jcp.org/xml/ns/javaee 
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd' version='3.1'>	
	<servlet>
		<servlet-name>dispatcher</servlet-name> <!-- servlet으로서 http통신을 주로 담당하고, 이는 결국 Spring Container이다. -->
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextClass</param-name> <!-- Spring Container, 즉 spring.core모듈과 달리 직접 Container를 만들 필요가 없다. -->
			<!-- configuration Class(즉, AppConfig클래스 파일)를 읽게 해준다. -->
			<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
		</init-param>
		<init-param>
			<param-name>contextConfigLocation</param-name> <!-- Spring Container가 사용할 AppConfig --> 
			<param-value>songjeongwoo.godgamez.config.AppConfig</param-value> <!-- Config(설정) Class파일 위치를 적는다. -->
		</init-param>
		<!-- 선택사항으로, servlet 생성의 우선순위를 요청한다. 단, 요청대로 할 지는 Tomcat의 선택 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<!-- context path 후 패턴을 "/"로 해서 default servlet으로 갈 url을 가로챈다. -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter> <!-- request를 필터링해서 encoding한다. -->
		<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> <!-- 필터에 필터링할 url을 알려준다. -->
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern> <!--  context path 후 "/"로 시작하는 request 전부를 뜻한다. -->
	</filter-mapping>
</web-app>

7. src/main/resources/songjeongwoo/godgamez/config에 app.properties, app.xml, sqlMapConfig.xml을 작성한다.

  • app.xml, sqlMapConfig.xml은 MYBOX에서 다운받은 것을 붙여놓은 후 작성한다.

  • app.xml를 작성한다.

<?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:mvc='http://www.springframework.org/schema/mvc' 
    xmlns:mybatis='http://mybatis.org/schema/mybatis-spring'   
    xmlns:context='http://www.springframework.org/schema/context'
    xmlns:tx='http://www.springframework.org/schema/tx'
    xsi:schemaLocation='http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://mybatis.org/schema/mybatis-spring
	http://mybatis.org/schema/mybatis-spring.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd'>
    
    <mvc:resources mapping='/res/**' location='/res/'/>
   
	<bean id='dataSource' class='org.springframework.jndi.JndiObjectFactoryBean'>
      	<!-- hr은 DB스키마 명으로, src/main/webapp/META-INF/context.xml에도 그대로 써야한다 -->
		<property name='jndiName' value='java:comp/env/jdbc/hr'/>
		<property name='resourceRef' value='true'/>
	</bean>
	
	<bean id='sqlSessionFactory' class='org.mybatis.spring.SqlSessionFactoryBean'>
		<property name='dataSource' ref='dataSource'/>
		<property name='configLocation' value='classpath:songjeongwoo/godgamez/config/sqlMapConfig.xml'/>
		<property name='mapperLocations'>
			<array>
				<value>classpath:songjeongwoo/godgamez/dao/map/**/*Map.xml</value>
			</array>
		</property>
	</bean>
	
	<mybatis:scan base-package='songjeongwoo.godgamez.dao.map.**'/>
	
	<bean id='multipartResolver' class='org.springframework.web.multipart.commons.CommonsMultipartResolver'>
		<property name='maxUploadSize' value='5242880'/><!-- 단위: 바이트, 5MB -->
		<property name='maxInMemorySize' value='5242880'/>
		<property name='defaultEncoding' value='utf-8'/>
	</bean>
	<context:property-placeholder location='classpath:songjeongwoo/godgamez/config/app.properties'/>
	
    <bean id='mailSender' class='org.springframework.mail.javamail.JavaMailSenderImpl'>
    	<property name='username' value=''/>
    	<property name='password' value=''/>
    	<property name='javaMailProperties'>
    		<props>
    			<prop key='mail.smtp.starttls.enable'>true</prop>
    			<prop key='mail.smtp.host'>smtp.gmail.com</prop>
    			<prop key='mail.smtp.port'>465</prop>
    			<prop key='mail.smtp.socketFactory.class'>javax.net.ssl.SSLSocketFactory</prop>
    			<prop key='mail.smtp.socketFactory.port'>465</prop>
    			<prop key='mail.smtp.socketFactory.fallback'>false</prop>
    			<prop key='mail.smtp.auth'>true</prop>
    		</props>
    	</property>
    </bean>
	
	<!-- service단에서도 transaction을 관리-->
	<bean id='transactionManager' class='org.springframework.jdbc.datasource.DataSourceTransactionManager'>
		<property name='dataSource' ref='dataSource'/>
	</bean>
	<tx:annotation-driven/> <!-- @Transactional을 사용가능 -->
</beans>
  • src/main/webapp/META-INF/context.xml에서 DB스키마명 확인할 것!
<?xml version='1.0' encoding='utf-8'?>
<Context>
	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<Resource name='jdbc/hr'
		auth='Container'
		type='javax.sql.DataSource'
		username=''
		password=''
		driverClassName='oracle.jdbc.driver.OracleDriver'
		factory='org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory'
		url='jdbc:oracle:thin:@127.0.0.1:1521:xe'/>
</Context>
  • src/main/webapp에 res 폴더를 만든다.
  • src.main.java.songjeongwoo.god.gamez에 dao, dao.map, domain, service, web 패키지를 만든다.
  • sqlMapConfig.xml에서 < settings>와 < typeAiases>를 작성한다.
<?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>
	<settings>
		<setting name='cacheEnabled' value='false'/>
		<setting name='localCacheScope' value='STATEMENT'/>
	</settings>
	<typeAliases>
		<package name='songjeongwoo.godgamez.domain'/> 
	</typeAliases>
</configuration>
  • app.properties를 작성한다.
attachDir=/res

8. src/main/resources/songjeongwoo/config 에 log4j2.xml을 작성한다.

<?xml version='1.0' encoding='UTF-8'?>
<Configuration>
	<Appenders>
		<Console name='console' target='SYSTEM_OUT'>
			<PatternLayout />
		</Console>
		<RollingFile name='file' fileName='C:/DEV/songjeongwoo.godgamez.log'
			filePattern='C:/DEV/songjeongwoo.godgamez.%d{yyyy-MM-dd-HH-mm-ss}.log' append='true'>
			<patternLayout pattern='[%-5p: %d{yyyy/MM/dd HH:mm:ss}] %m%n'/>
			<Policies>
				<TimeBasedTriggeringPolicy interval='86400'/>
			</Policies>
		</RollingFile>
	</Appenders>
		
	<Loggers>		
		<Root level='info'>
			<AppenderRef ref='console'/>
			<AppenderRef ref='file'/>									
		</Root>
	</Loggers>
</Configuration>

9. src/main/resources/songjeongwoo 에 dao/map 폴더를 만든다.

10. src/main/java/songjeongwoo.godgamez에 AppConfig 작성

package songjeongwoo.godgamez.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan("songjeongwoo.godgamez")
@ImportResource("classpath:songjeongwoo/godgamez/config/app.xml")
public class AppConfig implements WebMvcConfigurer {
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
	
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.jsp("/WEB-INF/view/", ".jsp");
	}
	
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("main");
	}
}

11. src/main/webapp/WEB-INF에 view 폴더를 만든다.

  • view 폴더 아래 main.jsp를 만든다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	Hello, world!
</body>
</html>

12. 잘 실행되는 지 확인

0개의 댓글