Spring 흐름도



Shop만들기 환경설정


SpringMVC와 pom.xml을 똑같이 해주고 project maven update project 해준다.

DataSource를 등록하는 방법

JNDI로 룩업하여 사용하는 방법 : Tomcat서버에 등록된 DataSource 이름으로 찾기
HikariCP 커넥션 풀을 이용하는 방법

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd">
	<!-- 네임스페이스 context, mybatis-spring 추가하였음 -->
	<!--[1] DataSource 빈을 등록
			(1) DriverManagerDataSource 빈을 등록
			(2) server.xml에 설정되어 있는 DBCP를 JNDI로 찾아쓰도록 등록하는 방법
			(3) HikariCP커넷견 풀을 이용하는 방법 [교재176p]
	  -->
 	<!-- (1) DriverManagerDataSource -->
	  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	  	  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
	  	  <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
	  	  <property name="username" value="scott"/>
	  	  <property name="password" value="tiger"/>
	  </bean>
	<!-- (2) JNDI로 룩업하여 사용하는 방법: Tomcat서버에 등록된 DataSource를 이름으로 찾아 빈으로 등록 -->
	  <bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
	  		<property name="jndiName" value="java:comp/env/jdbc/myshop"/>
	  </bean>
	<!-- [2] SqlSessionFactoryBean 등록 -->
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	 	  <property name="dataSource" ref="jndiDataSource"/>
	 	  <property name="configLocation" value="classpath:spring/config/mybatis-config.xml"/>
	 </bean>
	 
	 <!-- (3) HikariCP 커넥션 풀을 이용하는 방법 -->
	 <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
	 		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
	 		<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:XE"/>
	 		<property name="username" value="myshop"/>
	 		<property name="password" value="tiger"/>
	 </bean>
	 
	 <bean id="hikariDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
	 		<constructor-arg ref="hikariConfig"/>
	 </bean>
	 <!-- [3] SqlSessionTemplate빈 등록 -->
	 <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
	    <constructor-arg index="0" ref="sqlSessionFactory"/>
	 </bean>	
</beans>

POJO객체

MVC2.5이후 생긴 방식이고 현재 많이 사용중이다.
(Plaing Old Java Object)객체

***
servlet-context에
<context:component-scan base-package="com.tis.myshop"/>
을 붙이면 annotation이 붙은 것들을 사용할 수 있다.

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 -->
	<!-- 정적인 파일을 (css,js,image)를 dispatcher servlet이 매핑정보를 찾아 컨트롤러를 실행시키지 못하도록 리소스로 등록 -->
	<resources mapping="/resources/**" location="/resources/" />
	<resources mapping="/images/**" location="/images/" />
	<resources mapping="/css/**" location="/css/" />
	<resources mapping="/js/**" location="/js/" />

	<!-- 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.tis.myshop,com.tis.test,com.tis.service,com.tis.persistence" />
	
	
	
</beans:beans>

IndexController.java

package com.tis.myshop;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
	
	@RequestMapping("/top")
	public void showTop() {
		//뷰네임을 문자열로 반환하지 않을 경우
		//요청 매핑 "/top" 앞에 접두어를 붙이고, 뒤에는 접이머를 붙여 이동한다.
		//WEB-INF/views/top.jsp
	}
	
	// /index로 요청이 오면 home()메소드가 실행되고 index.jsp를 보여줌
	@RequestMapping(value="/index")
	public String home(Model model) {
		
		model.addAttribute("msg","From IndexController");
		model.addAttribute("cr","green");
		return "index";//뷰이름을 반환
		//WEB-INF/views/index.jsp를 찾아감
	}
	
	@RequestMapping("/carousel")
	public void showCarousel() {
		
	}
	
	@RequestMapping("/foot")
	public void showFoot() {
		
	}
	
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:import url="/top"/>
<c:import url="/carousel"/>

		<h1>안녕 MVC 스프링</h1>
		<h2 style='color:${cr}'>${msg}</h2>

<c:import url="/foot"/>


Controller에 Service 생성하고 주입 MyBatis 작동 확인


SampleService

package com.tis.service;

public interface SampleService {
	
	int getTableCount();
	
}

SampleServiceImpl

package com.tis.service;
import javax.inject.Inject;

//비즈니스 계층
import org.springframework.stereotype.Service;

import com.tis.persistence.SampleDao;

@Service("sampleServiceImpl")
public class SampleServiceImpl implements SampleService{
	
	@Inject
	private SampleDao sDao;
	
	
	@Override
	public int getTableCount() {
		return sDao.getTotalCount();
	}
}

TestController

package com.tis.test;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tis.service.SampleServiceImpl;

@Controller
public class TestController {
	
	//@Autowired//by type으로 주입함 SampleService타입의 객체가 있으면 주입해줌
	@Resource(name="sampleServiceImpl")
	private SampleServiceImpl sampleService;
	
	
	@RequestMapping(value="/test")
	public String test(Model model) {
		int tabCnt = sampleService.getTableCount();
		model.addAttribute("msg","MyShop계정의 테이블 수 "+tabCnt);
		model.addAttribute("cr","green");
		return "index";
	}
}

SampleDao

package com.tis.persistence;

public interface SampleDao {
	int getTotalCount();
}


SampleDaoMyBatis

package com.tis.persistence;
//영속성 계층

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

@Repository("sampleDaoMyBatis")
public class SampleDaoMyBatis implements SampleDao {

	private final String NS="common.base.SampleMapper";
	
	@Resource(name="sqlSessionTemplate")
	private SqlSessionTemplate session;
	
	@Override
	public int getTotalCount() {
		int cnt = session.selectOne(NS+".tableCount");
		return cnt;
	}

}

+ Recent posts