JAVA/SPRING
2009. 5. 6. 12:14
스프링 프레임워크의 프로세스는 대충 이해 했습니다.
스프링MVC에서 삽질 3일++ , 스프링JDBC에 도전해서 이틀동안 삽질한 결과 데이터베이스 연동을 할 수 있었네요..ㅋ
스프링.. 좋거나 혹은 나쁘거나 입니다. 제가 본 것은 빙산의 일각에 불과하지만 처음부터 너무 진을 빼놓네요.. 스트럿츠2가 그립습니다.
클래스를 많이 제공하는 것은 기호에 맞게 선택할 수 있는 폭이 넓어 좋지만, 반면 어떤 것을 적용해야 할지 어떤 것이 최선인가 하는데에 시간 투자를 많이 해야 합니다.
서블릿 설정파일에서도 시간을 많이 소비하였고 아직도 헷갈립니다. 톰캣과 궁합이 안좋은가...
JDBC연동 부분은 확실히 편하긴 하지만 커맨드,서비스,컨트롤러,DAO + servlet.xml 설정파일과 어떻게 연동이 되는가하는 부분에서도 하루를 날렸네요.
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dataSource.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>EUC-KR</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherJdbc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/boardService-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcherBank</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/sampleBankingServlet-servlet.xml , /WEB-INF/sampleBanking-services.xml
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherJdbc</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcherBank</servlet-name>
<url-pattern>/bank/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dataSource.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>EUC-KR</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherJdbc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/boardService-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcherBank</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/sampleBankingServlet-servlet.xml , /WEB-INF/sampleBanking-services.xml
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherJdbc</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcherBank</servlet-name>
<url-pattern>/bank/*</url-pattern>
</servlet-mapping>
최범균님 책에 나와있는데로 다시 web.xml을 설정을 해보았다.. 잘 될 줄 알았는데... 역시나 에러... 어플 하나는 꼭 안되더군..
TestDAO.java
public class TestDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Object insert(TestCommand test) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DataSourceUtils.getConnection(dataSource);
pstmt = conn.prepareStatement("insert into member(id,name,password) values(?,?,?)");
pstmt.setString(1, test.getId());
pstmt.setString(2, test.getName());
pstmt.setString(3, test.getPassword());
pstmt.executeUpdate();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
DataSourceUtils.releaseConnection(conn, dataSource);
}
return dataSource.getConnection();
}
}
public class TestDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Object insert(TestCommand test) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DataSourceUtils.getConnection(dataSource);
pstmt = conn.prepareStatement("insert into member(id,name,password) values(?,?,?)");
pstmt.setString(1, test.getId());
pstmt.setString(2, test.getName());
pstmt.setString(3, test.getPassword());
pstmt.executeUpdate();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
DataSourceUtils.releaseConnection(conn, dataSource);
}
return dataSource.getConnection();
}
}
DAO파일은 dataSource객체만 선언해 준 것 빼고 거의 비슷하게 했다. 스프링의 jdbc템플릿을 쓰지 않았다.
Controller
public class JoinController extends SimpleFormController{
public JoinController(){}
//서비스 객체 생성
private TestService service;
public TestService getService() {
return service;
}
public void setService(TestService service) {
this.service = service;
}
public ModelAndView onSubmit(Object command) throws Exception{
TestCommand test = (TestCommand) command;
//서비스를 호출
service.insertMemeber(test);
//직접 DAO접근
//to.insert(test);
return new ModelAndView(getSuccessView(), "success" , service.insertMemeber(test));
}
}
public class JoinController extends SimpleFormController{
public JoinController(){}
//서비스 객체 생성
private TestService service;
public TestService getService() {
return service;
}
public void setService(TestService service) {
this.service = service;
}
public ModelAndView onSubmit(Object command) throws Exception{
TestCommand test = (TestCommand) command;
//서비스를 호출
service.insertMemeber(test);
//직접 DAO접근
//to.insert(test);
return new ModelAndView(getSuccessView(), "success" , service.insertMemeber(test));
}
}
컨트롤러는 간단하다. 서비스는 DAO와 연결해주는 빈이고.. 이것을 컨트롤러에서 실행한다.. 이상하게도 DAO에 직접 접근하면 에러가 나더라..
boardService-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id = "testDao"
class = "sboard.DAO.TestDAO">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/testjoin.htm">joinController</prop>
</props>
</property>
</bean>
<bean id="testService"
class="sboard.services.TestService"
p:tdao-ref="testDao" />
<bean id="joinController"
class="sboard.controller.JoinController">
<property name="sessionForm">
<value>true</value>
</property>
<property name="commandName">
<value>joinCommand</value>
</property>
<property name="commandClass">
<value>sboard.commands.TestCommand</value>
</property>
<property name="formView">
<value>join</value>
</property>
<property name="successView">
<value>memberlist</value>
</property>
<property name="service">
<ref bean="testService" />
</property>
</bean>
<!--뷰리졸버 세팅 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/test/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id = "testDao"
class = "sboard.DAO.TestDAO">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/testjoin.htm">joinController</prop>
</props>
</property>
</bean>
<bean id="testService"
class="sboard.services.TestService"
p:tdao-ref="testDao" />
<bean id="joinController"
class="sboard.controller.JoinController">
<property name="sessionForm">
<value>true</value>
</property>
<property name="commandName">
<value>joinCommand</value>
</property>
<property name="commandClass">
<value>sboard.commands.TestCommand</value>
</property>
<property name="formView">
<value>join</value>
</property>
<property name="successView">
<value>memberlist</value>
</property>
<property name="service">
<ref bean="testService" />
</property>
</bean>
<!--뷰리졸버 세팅 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/test/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
dataSource는 dataSource.xml에 정의 되어 있다. 그것을 가져와서 testDao에 담고,,, 서비스 클래스에 선언된 tdao객체를 초기화하기 위해 testService선언.. 파라미터로 testDao객체를 넘겨준다. 컨트롤러에서 사용할 서비스객체를 초기화하기 위해서 컨트롤러 빈 내에
service프로퍼티에 testService빈을 파라미터로 넘겨준다.(복잡하다...)
삽질한 만큼 끝내 결과를 보게 되서 다행입니다.;;