728x90
728x90

선수학습 내용

 

Spring MVC 패턴 스프링 게시판 만들기

이번에는 Spring MVC 패턴을 이용하여 게시판을 만들어보도록 하겠습니다. 우선 로직과 파일의 폴더 구성은 아래와 같습니다. 작업 순서도 1. DB작성 2. 프로젝트 생성 3. pom.xml, web.xml 수정 1. 테이블, 시..

coding-restaurant.tistory.com

 


 

Mybatis란?

 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크
 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해 줌
 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해
XML과 애노테이션을 사 용할 수 있음

 

스프링 + MyBatis 연동 설정

1. 필수 라이브러리

• MyBatis 라이브러리 • mybatis-spring 라이브러리 • MySQL JDBC 드라이버

• 개발 전 테스트

• MySQL의 연결 테스트 • Spring 프로젝트의 SqlSessionFactory 연결 테스트

 


 

 

 

XML

(server) context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <!-- driver, xe 수정 : 서버에 이부분을 뺀다 -->
     	 <!-- <Resource name="jdbc/myoracleDB" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/> -->
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

context.xml

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <!-- driver, xe 수정 -->
     	 <!-- <Resource name="jdbc/myoracleDB" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.0.78:1521:xe"
              username="mvc" password="1234" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/> -->
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

web.xml

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.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>
	</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>

	</filter>

	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

 

 

라이브러리 추가

 

 

Pom.xml 수정

mybatis 저는 신버전을 붙였습니다.

 

 

mybatis-spring도 붙입니다.

 

pom.xml

...더보기
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.lje</groupId>
	<artifactId>springboard</artifactId>
	<name>SpringMVCBoard01</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- 단위 Test를 하기 위한 junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.2</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

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.lje.springboard" />
	
	
	
</beans:beans>

 

root-context.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="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">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="url" value="jdbc:oracle:thin:@192.168.0.78:1521:xe"></property>
			<property name="username" value="mvc"></property>
			<property name="password" value="1234"></property>
		</bean>
		
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<!-- 설정파일 -->
			<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
			<!-- 파일위치.name에 s주의. resources 밑에 mappers라는 폴더를 생성, 그 아래 모두 -->
			<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml"></property>
		</bean>
		<!-- 실제 DB 사용 시 이것만 부른다 -->
		<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
		</bean>
		<!-- <bean id="dao" class="com.lje.spring.dao.BDao" /> 이거 일일히 쓰는 대신 아래 한줄로 끝!-->
		<context:component-scan base-package="com.lje.springboard"></context:component-scan>
</beans>

 

코드 완성 후 해야 할 작업이 있다. 
root-context.xml에 Namespaces 탭을 클릭, context 부분의 체크박스에 체크한다.

 

*오라클이 아닌 mySQL을 사용할 때는?

<?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"
	xsi:schemaLocation="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">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<!-- 오라클DB -->
		<!-- 
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
			<property name="url" value="jdbc:oracle:thin:@192.168.0.78:1521:xe"></property>
			<property name="username" value="mvc"></property>
			<property name="password" value="1234"></property>
		</bean>
		 -->
		 <!-- mySQLDB 6.0 이상 -->
		<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
			<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
			<property name="url" value="jdbc:mysql://127.0.0.1:3306/mvcdb?useSSL=false&amp;serverTimezone=Asia/Seoul" />
			<property name="username" value="mvc" />
			<property name="password" value="1234" />
		</bean> -->
		
		 <!-- mySQLDB 5.0 ver -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
			<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
			<property name="url" value="jdbc:mysql://127.0.0.1:3306/mvcdb" />
			<property name="username" value="mvc" />
			<property name="password" value="1234" />
		</bean>
		 
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<!-- 설정파일 -->
			<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
			<!-- 파일위치.name에 s주의. resources 밑에 mappers라는 폴더를 생성, 그 아래 모두 -->
			<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml"></property>
		</bean>
		<!-- 실제 DB 사용 시 이것만 부른다 -->
		<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
		</bean>
		<!-- <bean id="dao" class="com.lje.spring.dao.BDao" /> 이거 일일히 쓰는 대신 아래 한줄로 끝!-->
		<context:component-scan base-package="com.lje.springboard"></context:component-scan>
</beans>

  

 

아까 선언한 파일이름들에 해당하는 xml파일들을 만들어준다.

 

 

BoardMapper.xml : DAO 의 역할을 대신 한다.

MyBatis 홈페이지 > 시작 부분에서 매핑된 SQL 구문 살펴보기 아래의 코드를 복사해온다.

 

 

MyBatis – 마이바티스 3 | 시작하기

XML에서 SqlSessionFactory 빌드하기 모든 마이바티스 애플리케이션은 SqlSessionFactory 인스턴스를 사용한다. SqlSessionFactory인스턴스는 SqlSessionFactoryBuilder를 사용하여 만들수 있다. SqlSessionFactoryBuilder는 XML설정파일에서 SqlSessionFactory인스턴스를 빌드할 수 있다. XML파일에서 SqlSessionFactory인스턴스를 빌드하는 것은 매우 간단한다. 설

www.mybatis.org

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lje.boardex.BoardMapper">
  <select id="selectAll" resultType="Board">
    select * from mvc_board
  </select>
  <!-- com.lje.spring.dto.Board.이런식으로 다 적어야하나 mybatis-config.xml에서 코드를 적어주면 생략도 가능하다 -->
  <select id="selectOne" resultType="Board">
  	select * from mvc_board where bno=#{bno}
  </select>
  <!-- #을 쓰면 정수는 정수열, 문자는 문자열로, $는 String -->
  <insert id="create">
  	insert into mvc_board(bno, write, title, content)
  	values(mvc_board_seq.nextval, #{writer}, #{title}, #{content})
  </insert>
  <!-- insert, update는 리턴타입 없다. select만 --> 
  <update id="modify">
  	update mvc_board set writer=#{writer}, title=#{title}, content=#{content}
  	where bno=#{bno}
  </update>
  <delete id="remove">
  	delete from mvc_board where bno=#{bno}
  </delete>
  <update id="hitUpdate">
  	update mvc_board set hit=hit+1 where bno=#{bno}
  </update>
</mapper>
...더보기

mysql 사용 시 BoardMapper.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lje.boardex.BoardMapper">
  <select id="selectAll" resultType="Board">
    select * from mvc_board
  </select>
  <!-- com.lje.spring.dto.Board.이런식으로 다 적어야하나 mybatis-config.xml에서 코드를 적어주면 생략도 가능하다 -->
  <select id="selectOne" resultType="Board">
  	select * from mvc_board where bno=#{bno}
  </select>
  <!-- #을 쓰면 정수는 정수열, 문자는 문자열로, $는 String -->
  <insert id="create">
  	insert into mvc_board(write, title, content)
  	values(#{writer}, #{title}, #{content})
  </insert>
  <!-- insert, update는 리턴타입 없다. select만 --> 
  <update id="modify">
  	update mvc_board set writer=#{writer}, title=#{title}, content=#{content}
  	where bno=#{bno}
  </update>
  <delete id="remove">
  	delete from mvc_board where bno=#{bno}
  </delete>
  <update id="hitUpdate">
  	update mvc_board set hit=hit+1 where bno=#{bno}
  </update>
</mapper>

 


mybatis-config.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.lje.springboard.dto" />
		<!-- 여따 적으면 BoardMapper.xml의 mapper 태그에서 생략 가능하다. -->
	</typeAliases>
</configuration>

 

 

DAO

IDao.java (1)DAO 폴더에 Interface를 생성 (2)Class 생성

 

IDao.java

...더보기
package com.lje.springboard.dao;

import java.util.List;

import com.lje.springboard.dto.Board;

public interface IDao {
	public void create(Board board) throws Exception;
	//try-catch가 없기에 여기서는 예외를 DAO에서 써줘야함
	
	public List<Board> listAll() throws Exception;
	public Board read(int bno) throws Exception;
	public void update (Board board) throws Exception;
	public void delete (int bno) throws Exception;
	public void hitUpdate (int bno) throws Exception;
	
}

 

BDao.java

...더보기
package com.lje.springboard.dao;

import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.lje.springboard.dto.Board;

//root-context.xml에서 정의한 sqlSession를 사용할 것임
@Repository
public class BDao implements IDao {
	
	//어노테이션은 오토와이어드나 Inject를 쓸 수 있다
	@Inject
	private SqlSessionTemplate sqlSession;
	
	//BoardMapper.xml에서 정의한 namespace
	private static String namespace = "com.lje.boardex.BoardMapper";
	
	
	@Override
	public void create(Board board) throws Exception {
		//BoardMapper.xml의 id
		sqlSession.insert(namespace+".create", board);
		

	}

	@Override
	public List<Board> listAll() throws Exception {
		return sqlSession.selectList(namespace+".selectAll");
	}

	@Override
	public Board read(int bno) throws Exception {
		return sqlSession.selectOne(namespace+".selectOne", bno);
	}

	@Override
	public void update(Board board) throws Exception {
		sqlSession.update(namespace+".modify", board);

	}

	@Override
	public void delete(int bno) throws Exception {
		sqlSession.delete(namespace+".remove", bno);

	}

	@Override
	public void hitUpdate(int bno) throws Exception {
		sqlSession.update(namespace+".hitUpdate", bno);

	}

}

 

 

Service

BoardServiceImpl

package com.lje.springboard.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.lje.springboard.dao.BoardDao;
import com.lje.springboard.dao.IDao;
import com.lje.springboard.dto.Board;

@Service
public class BoardServiceImpl implements BoardService {
	@Inject
	private IDao dao;
	//private IDao dao=new BDao...를 하지 않는 이유는 BDao에 @repository라는 annotaion을 넣어두어서 root-context.xml
	//context:component-scan에서 읽어온당. 따라서 root-context에는 bean을 만들지 않아도 된다.
	
	
	@Override
	public List<Board> listAll()  throws Exception {
		// TODO Auto-generated method stub
		return dao.listAll();
	}

	@Override
	public void insert(Board board)  throws Exception {
		dao.create(board);
	}

	@Override
	public Board read(int bno)  throws Exception{
		// 조회 시 조회수 증가
		dao.hitUpdate(bno);
		return dao.read(bno);
	}

	@Override
	public void modify(Board board)  throws Exception{
		dao.update(board);

	}

	@Override
	public void delete(int bno)  throws Exception{
		dao.delete(bno);

	}

}

 

BoardService

package com.lje.springboard.service;

import java.util.List;

import com.lje.springboard.dto.Board;

public interface BoardService {
	public List<Board> listAll() throws Exception;
	public void insert (Board board) throws Exception;
	public Board read(int bno) throws Exception;
	public void modify(Board board) throws Exception;
	public void delete(int bno) throws Exception;
}

 

BoardController

package com.lje.springboard.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lje.springboard.dto.Board;
import com.lje.springboard.service.BoardService;
import com.lje.springboard.service.BoardServiceImpl;

@Controller
@RequestMapping("/board")
public class BoardController {
	
	@Inject
	BoardService service;
	
	@RequestMapping("/list")
	public String list(Model model) throws Exception {
		//service = new BoardServiceImpl(); 위에 inject로 서비스객체가 만들어져서 필요없음
		model.addAttribute("list", service.listAll());
		return "board/list";
	}
	@RequestMapping("/read")
	public String read(@RequestParam("bno") int bno, Model model) 
			throws Exception{
		//service = new BoardServiceImpl();
		model.addAttribute("board", service.read(bno));
		return "board/update";
	}
	@GetMapping("write")
	public String writeForm() {
		return "board/write";
	}
	
	@PostMapping("write")
	public String write(@ModelAttribute("board") Board board) throws Exception{
		//service = new BoardServiceImpl();
		System.out.println(board); //작업테스트
		service.insert(board);
		return "redirect:list";
	}
	
	@RequestMapping("update")
	public String modify(@ModelAttribute("board") Board board) throws Exception{
		//service = new BoardServiceImpl();
		service.modify(board);
		return "redirect:list";
	}
	
	@RequestMapping("delete")
	public String delete(@RequestParam("bno") int bno) throws Exception{ 
		//service = new BoardServiceImpl();
		service.delete(bno);
		return "board/view";
	}
}
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v