Dev/Spring

Spring2.5/iBatis 셋팅

창문닦이 2019. 4. 5. 14:57

1. 실습진행을 위해 Dynamic Web Project 생성

2. 라이브러리 추가 

스프링 프레임워크를 다운받으면 모듈에 지원하는 라이브러리 jar파일들이 있음.

스프링 2.5의 spring.jar

spring-aspects.jar, spring-test.jar, spring-webmvc.jar, spring-webmvc-portlet.jar, spring-webmvc-struts.jar을 제외한 나머지 모듈

webmvc 추가.

3. log4j 사용을 위해서 프로퍼티 파일 추가

4. 공통으로 사용하는 util패키지에 클래스 추가

 

FileManager 클래스

스프링에서는 file클래스를 사용하지 않고 inputStream클래스를 사용한다.

파일업로드 작업. 저장된 파일의 경로를 지정해주면 스프링이 알아서 업로드를 시켜준다.

FileCopyUtils.copy(is,new FileOutputStream(fullFilePath));

CommonDAOImpl 클래스 - applicationContext.xml를 통해 트랜잭션 객체를 생성하므로 삭제함.

package com.util.dao;

import java.sql.SQLException;

import java.util.List;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.orm.ibatis.SqlMapClientTemplate;

import org.springframework.stereotype.Repository;

@Repository("dao")

public class CommonDAOImpl implements CommonDAO {

 

//자동으로 applicationContext.xml에 있는 bean중 id가 동일한 객체를 가져오라는 어노테이션

//Autowired가 작성되었기 때문에 setter를 생략할 수 있다.

@Autowired

private SqlMapClientTemplate sqlMapClientTemplate;

 

@Override

public void insertData(String id, Object value) throws SQLException {

try {

sqlMapClientTemplate.insert(id, value);

} catch (Exception e) {

System.out.println(e.toString());

} finally {

}

}

@Override

public int updateData(String id, Object value) throws SQLException {

int result = 0;

try {

//트랜잭션매니저 bean에서 트랜잭션을 생성하고 끝내므로 작성할 필요없음

result = sqlMapClientTemplate.update(id, value);

} catch (Exception e) {

System.out.println(e.toString());

}

return result;

}

@Override

public int updateData(String id, Map<String, Object> map)

throws SQLException {

int result = 0;

try {

result = sqlMapClientTemplate.update(id, map);

} catch (Exception e) {

System.out.println(e.toString());

}

return result;

}

@Override

public int deleteData(String id) throws SQLException {

int result = 0;

try {

result = sqlMapClientTemplate.delete(id);

} catch (Exception e) {

System.out.println(e.toString());

}

return result;

}

@Override

public int deleteData(String id, Object value) throws SQLException {

int result = 0;

try {

result = sqlMapClientTemplate.delete(id, value);

} catch (Exception e) {

System.out.println(e.toString());

}

return result;

}

@Override

public int deleteData(String id, Map<String, Object> map)

throws SQLException {

int result = 0;

try {

result = sqlMapClientTemplate.delete(id, map);

} catch (Exception e) {

System.out.println(e.toString());

}

return result;

}

@Override

public Object getReadData(String id) {

return sqlMapClientTemplate.queryForObject(id);

}

@Override

public Object getReadData(String id, Object value) {

return sqlMapClientTemplate.queryForObject(id,value);

}

@Override

public Object getReadData(String id, Map<String, Object> map) {

return sqlMapClientTemplate.queryForObject(id,map);

}

@Override

public int getIntValue(String id) {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id)).intValue();

return num;

}

@Override

public int getIntValue(String id, Object value) {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id,value)).intValue();

return num;

}

@Override

public int getIntValue(String id, Map<String, Object> map) {

int num = 0;

num = ((Integer)sqlMapClientTemplate.queryForObject(id,map)).intValue();

return num;

}

@SuppressWarnings("unchecked")

@Override

public List<Object> getListData(String id) {

List<Object> lists = (List<Object>)sqlMapClientTemplate.queryForList(id);

return lists;

}

@SuppressWarnings("unchecked")

@Override

public List<Object> getListData(String id, Object value) {

List<Object> lists = (List<Object>)sqlMapClientTemplate.queryForList(id,value);

return lists;

}

@SuppressWarnings("unchecked")

@Override

public List<Object> getListData(String id, Map<String, Object> map) {

List<Object> lists = (List<Object>)sqlMapClientTemplate.queryForList(id,map);

return lists;

}

}

5. sqlMapconfig 폴더 생성 - (iBatis)

sqlMapConfig.xml

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

<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

<settings

cacheModelsEnabled="false"

useStatementNamespaces="true"/>

 

<sqlMap resource="com/util/sqlMap/temp_sqlMap.xml"/>

</sqlMapConfig>

6. applicationContext.xml, dispatcher-servlet.xml, web.xml 파일 생성

① applicationContext.xml - iBatis 셋팅

지금 당장은 어노테이션을 사용하지 않을 것이므로 작성하지 않음.
  <!-- 어노테이션 사용 설정 -->
  <context:component-scan base-package="*" scoped-proxy="no"/>

<?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:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation=

"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

 <!-- 스프링에 의해 iBatis 사용할 것이므로 설정. DB를 찾아가는 기본적인 경로 -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>

<property name="url" value="jdbc:oracle:thin:@192.168.16.16:1521:TestDB"/>

<property name="username" value="SUZI"/>

<property name="password" value="A123"/>

</bean>

<!-- 트랜잭션 처리를 진행하는 객체 -->

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<!-- iBatis 사용을 위해 팩토리빈을 만들어야함 -->

<bean id="sqlMapClient"

class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"

p:dataSource-ref="dataSource"

p:configLocation="WEB-INF/sqlMapConfig/sqlMapConfig.xml"/>

<!-- sqlMapClient를 통해 만드는 개별로 적용되는 템플릿 -->

<bean id="sqlMapClientTemplate"

class="org.springframework.orm.ibatis.SqlMapClientTemplate"

p:sqlMapClient-ref="sqlMapClient"/>

</beans>

② dispatcher-servlet.xml - Spring 셋팅

Struts에서 action-Context.xml 환경설정 파일의 역할을 front controller가 진행한다.

 

<!-- View로 넘겨야되는 jsp페이지를 찾는 역할을 하는 객체 → 뷰리졸버 : 사용자에게 결과를 랜더링하여 보여주기 위하여 사용 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean>

<?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:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation=

"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/"/>

<property name="suffix" value=".jsp"/>

</bean>

</beans>

③ web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<display-name>spring</display-name>

<welcome-file-list>

  <welcome-file>index.html</welcome-file>

  <welcome-file>index.htm</welcome-file>

  <welcome-file>index.jsp</welcome-file>

  <welcome-file>default.html</welcome-file>

  <welcome-file>default.htm</welcome-file>

  <welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<!-- 모든 주소는 인코딩 필터를 거치도록 설정 -->

<filter>

<filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<servlet>

<servlet-name>dispatcher</servlet-name>

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

</servlet>

<!-- 스프링의 기본확장자도 action임 -->

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>*.action</url-pattern>

</servlet-mapping>

 

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

</web-app>


 

프로젝트가 잘 실행되는지 확인하기 위해 index.jsp를 생성해보자

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<h1>Spring2.5 Framework</h1>

</body>

</html>

실행 화면

 

이상없이 스프링 2.5 프레임워크를 세팅하였다 !