영보의 SystemOut.log

[Spring] CRUD 게시판 만들기 - Spring MVC구조와 동적쿼리 사용(with IntelliJ, MySQL) -1 본문

Spring

[Spring] CRUD 게시판 만들기 - Spring MVC구조와 동적쿼리 사용(with IntelliJ, MySQL) -1

영보로그 2021. 1. 22. 09:33
반응형

 환경 설정

 

 

qh5944.tistory.com/136

 

[spring] STS과 Mysql로 CRUD 게시판 만들기-(1)

 환경설정 1. 개발환경 : STS / Mysql / Tomcat8.5 / jdk1.8 2. 라이브러리 추가 mvnrepository.com/artifact/javax.servlet/jstl/1.2 Maven Repository: javax.servlet » jstl » 1.2 Professional Java Data:..

qh5944.tistory.com

↑↑↑↑↑

여기서 jstl-1.2.jar 파일 가져와서 라이브러리 폴더에 넣어줍니다.

 

 

위 링크와 같은 CRUD를 만드는데,

이번엔 Annotation을 사용하지 않고 동적쿼리로 Mapper을 구현했습니다.

어노테이션 사용이 더 편리하지만 때에 따라 동적쿼리도 필요하기 때문에..

 

Tomcat 8.5.46  /  jdk 1.8  / IntelliJ  /  MariaDB(MySQL)

 

 

 

 

 

 코드

 

# MySQL 테이블 생성

CREATE TABLE project1_board(
        boardnumber int          NOT NULL PRIMARY KEY,
        name        varchar(20)  NOT NULL,
        subject     varchar(100) NOT NULL,
        `pwd`       VARCHAR(10)  NOT NULL,
        content     TEXT         NOT NULL,
        mobile      char(8)      NULL,
        hit         INT DEFAULT 0
 )ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

 

# 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.sist</groupId>
	<artifactId>web</artifactId>
	<name>SpringAOPProject3</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<!-- Spring 5 -->
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.5.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	

	
	<repositories>
		<repository>
			<id>mesir-repo</id>
			<url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url>
		</repository>
	</repositories>
	<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>
		<!-- Jsoup -->
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.12.1</version>
		</dependency>
		<!-- JSON -->
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!-- JAXB -->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- AspectJ -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.8</version>
			<scope>provided</scope>
		</dependency>
		<!-- websocket -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-websocket</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>

		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> 
			<version>5.1.5.RELEASE</version> </dependency> -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-instrument</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> 
			<version>5.1.5.RELEASE</version> </dependency> -->

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.nuiton.thirdparty</groupId>
			<artifactId>Rserve</artifactId>
			<version>1.7-3</version>
		</dependency>
		<dependency>
			<groupId>org.nuiton.thirdparty</groupId>
			<artifactId>REngine</artifactId>
			<version>1.7-3</version>
		</dependency>
		<!-- @Select("<script>SELECT~~ <if test="">") -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.13.0-rc1</version>
		</dependency>
		<dependency>
			<groupId>org.nuiton.thirdparty</groupId>
			<artifactId>JRI</artifactId>
			<version>0.9-6</version>
		</dependency>
		<dependency>
			<groupId>com.github.lucarosellini.rJava</groupId>
			<artifactId>JRIEngine</artifactId>
			<version>0.9-7</version>
		</dependency>
		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm</artifactId>
			<version>3.3.1</version>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.2-GA</version>
		</dependency>

		<dependency>
			<groupId>org.nuiton.thirdparty</groupId>
			<artifactId>Rserve</artifactId>
			<version>1.7-3</version>
		</dependency>
		<dependency>
			<groupId>org.nuiton.thirdparty</groupId>
			<artifactId>REngine</artifactId>
			<version>1.7-3</version>
		</dependency>
		<dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-core</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-stream</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>

		<!-- End -->
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>
		<!-- AOP -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.5</version>
		</dependency>
		<!-- AOP -->
		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>
		<!-- AOP -->
		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm</artifactId>
			<version>3.1</version>
		</dependency>
		<!-- tiles -->
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-core</artifactId>
			<version>3.0.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-jsp</artifactId>
			<version>3.0.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-api</artifactId>
			<version>3.0.8</version>
		</dependency>

		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-servlet</artifactId>
			<version>3.0.8</version>
		</dependency>

		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.2</version>
		</dependency>

		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
			<version>2.1</version>
		</dependency>

		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>antlr-runtime</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- XML -->
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-core</artifactId>
			<version>2.2.11</version>
		</dependency>
		<dependency>
			<groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-impl</artifactId>
			<version>2.2.11</version>
		</dependency>

		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.2.11</version>
		</dependency>

		<!-- JSON -->
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</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>
		<!-- 유효성 검사 (12장) -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>2.0.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.1.6.Final</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 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- MySQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.16</version>
		</dependency>

		<!-- Apache Commons-DBCP -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.4.0</version>
		</dependency>

		<!-- MyBatis 3.4.1 -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.1</version>
		</dependency>


		<!-- MyBatis-Spring -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>

		<!-- Spring-jdbc -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<!-- <version>${org.springframework-version}</version> -->
			<version>4.3.8.RELEASE</version>
		</dependency>

		<!-- Spring-test -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</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>
				<!-- Spring 5 -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</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>

 

 

 

# 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 http://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>classpath*:spring/context-*.xml</param-value>
    <!-- <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>classpath*:/spring/context-servlet.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>

  <!-- encoding filter -->
  <filter>
    <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

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

  <filter>
    <filter-name>multipartFiter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
  </filter>

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

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

  <session-config>
    <session-timeout>120</session-timeout>
  </session-config>
  
</web-app>

 

 

 

# application-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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
	<context:component-scan base-package="com.*" />
	<!-- 자신의 PC(로컬)에 MySql을 설치했을 경우 -->


	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="kr.ac.knu.iphak.base.vo" />
		<property name="mapperLocations" value="classpath*:mapper/*.xml" />
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
	</bean>

	<!-- <bean id="mapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
		p:sqlSessionFactory-ref="sqlSessionFactory" p:mapperInterface="com.sist.mapper.board-Mapper.xml" /> -->

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/" p:suffix=".jsp" />

	<mybatis-spring:scan base-package="com.sist" />

</beans>

 - sql, mybatis 연동을 위해 꼭 써야하는 부분이다.

 - 마찬가지로 본인 파일과 경로에 맞게 vo와 mapper경로 수정해줘야 한다.

 

 

 

# BoardVO.java

package com.sist.dao;
import java.util.*;

public class BoardVO {
	private int boardnumber,hit, reply;
	  private String name,subject,content,pwd;
	  private Date regdate;
	public int getBoardnumber() {
		return boardnumber;
	}
	public void setBoardnumber(int boardnumber) {
		this.boardnumber = boardnumber;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Date getRegdate() {
		return regdate;
	}
	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}
	public int getReply() {
		return reply;
	}

	@Override
	public String toString() {
		return "BoardVO{" +
				"boardnumber=" + boardnumber +
				", hit=" + hit +
				", reply=" + reply +
				", name='" + name + '\'' +
				", subject='" + subject + '\'' +
				", content='" + content + '\'' +
				", pwd='" + pwd + '\'' +
				", regdate=" + regdate +
				'}';
	}

	public void setReply(int reply) {
		this.reply = reply;
	}
}

 

 

 

# BoardDAO.java

package com.sist.dao;

import java.util.*;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;


@Repository
public  class BoardDAO {
	/*private static SqlSessionFactory ssf;*/

	@Autowired
	@Qualifier(value = "sqlSession")
	protected SqlSession sqlSession;

	// 게시판 목록 읽기
	public List<BoardVO> boardListData(Map map) {
		return sqlSession.selectList("boardListData",map);
	}

	// 게시판 총페이지 읽기
	public int boardTotalPage() {
		int i = sqlSession.selectOne("boardTotalPage");
		return i;
	}

	// 게시판 상세보기
	public BoardVO boardDetailData(int no) {
		return sqlSession.selectOne("boardDetailData", no);
	}

	// 게시판 추가
	public int boardInsert(BoardVO vo) {
		return sqlSession.insert("boardInsert", vo);
	}

	// 게시판 수정
	public BoardVO boardUpdate(int no) {
		return sqlSession.selectOne("boardDetailData", no);
	}
		
	public int boardUpdate_ok(Map map) {
		return sqlSession.update("boardUpdate_ok", map);
	}

	// 게시판 삭제
	public int boardDelete(int no) {
		return sqlSession.delete("boardDelete", no);
	}

	// 검색
	public List<BoardVO> boardList_search(Map map){
		return sqlSession.selectList("boardList_search");
	}

	// 검색 총 페이지 읽기
	public int searchTotalPage() {
		int j = sqlSession.selectOne("searchTotalPage");
		return j;
	}
}

 

 

 

# 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.sist.mapper.board-mapper">
	<!-- 리스트-->

	<select id="boardListData" resultType="com.sist.dao.BoardVO" parameterType="hashmap">
		SELECT boardnumber,name,subject,pwd,content,hit,regdate FROM project1_board
		where 1=1
		<if test="searchType != null">
			<if test="searchType.equal('t')">
				and name like concat('%', #{keyword}, '%')ㅅ
			</if>
			<if test="searchType.equal('c')">
				and subject like concat('%', #{keyword}, '%')
			</if>
			<if test="searchType.equal('w')">
				and content like concat('%', #{keyword}, '%')
			</if>
			<if test="searchType.equal('tc')">
				and (subject like concat('%', #{keyword}, '%')
				or content like concat('%', #{keyword}, '%'))
			</if>
			<if test="searchType.equal('all')">
				and (subject like concat('%', #{keyword}, '%')
				or content like concat('%', #{keyword}, '%')
				or name like concat('%', #{keyword}, '%'))
			</if>
		</if>
	</select>

	<!--리스트 총페이지-->
	<select id="boardTotalPage" resultType="int">
   		SELECT CEIL(COUNT(*)/8.0) FROM project1_board
  	</select>

	<!--상세보기-->
	<select id="boardDetailData" resultType="com.sist.dao.BoardVO" parameterType="int">
		SELECT * FROM project1_board WHERE boardnumber=#{boardnumber}
	</select>

	<!--상세보기 조회수 증가-->
	<update id="boardHitIncrement" parameterType="int">
		UPDATE project1_board SET hit = hit + 1 WHERE boardnumber = #{boardnumber}
	</update>

	<!--게시글 글번호 자동 증가-->
	<select id="boardnumber" resultType="int">
		SELECT NVL(MAX(boardnumber)+1,1) as boardnumber FROM project1_board
	</select>

	<!--글쓰기 추가-->
	<insert id="boardInsert" parameterType="com.sist.dao.BoardVO">
		INSERT INTO project1_board(boardnumber,name,subject,pwd,content) "
			+"VALUES(#{boardnumber},#{name},#{subject},#{pwd},#{content})
	</insert>

	<!--게시글 수정하기-->
	<update id="boardUpdate" parameterType="hashmap">
		UPDATE project1_board SET content=#{content}, subject=#{subject}
		WHERE boardsnumber=#{boardnumber} AND pwd=#{pwd}
	</update>

	<!--게시글 삭제하기-->
	<delete id="boardDelete" parameterType="int">
	DELETE FROM project1_board WHERE boardnumber=#{boardnumber}

</mapper>

 - 여기서 중요한 것은 첫번째 <select>문 안의 <if>문에서 문자열 비교시에는 equal을 써야한다는 것이다. String에서 지원하는 equals 문자열 비교 메서드를 사용하면 주소 값이 아닌 data값을 비교하기 때문에 원하는 결과를 가져온다.

(이것도 모르고 ==으로 했다가 몇시간동안 왜안되지 했었음..)

 

 

 

# DBConnection.java

package com.sist.dao;

import java.sql.Connection;
import java.sql.DriverManager;

import com.mysql.cj.jdbc.CallableStatement;

public class DBConnection {
	private Connection conn;
    private CallableStatement cs;
    private String driver,url,username,password;
    public DBConnection(String driver,String url,String username,String password)
    {
        this.driver=driver;
        this.url=url;
        this.username=username;
        this.password=password;
        
        try
        {
            Class.forName(driver);
        }catch(Exception ex){}
    }
    public void getConnection()
    {
        try
        {
            conn=DriverManager.getConnection(url,username,password);
        }catch(Exception ex){}
    }
    public void disConnection()
    {
        try
        {
            if(conn!=null) conn.close();
            if(cs!=null) cs.close();
        }catch(Exception ex){}
    }
    public Connection getConn() {
        return conn;
    }
    public void setConn(Connection conn) {
        this.conn = conn;
    }
    public CallableStatement getCs() {
        return cs;
    }
    public void setCs(CallableStatement cs) {
        this.cs = cs;
    }
}

 

 

 

# BoardController.java

package com.sist.web;

import com.sist.dao.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("board/")
public class BoardController {

	@Autowired
	private BoardDAO dao;

	// 리스트
	// =========================================================================================================/=========================================
	@RequestMapping("list.do")
	public String board_list(Model model, String page, HttpSession session, HttpServletRequest request, String searchType,

							 @RequestParam( defaultValue="",name="searchType") String searchType2,
							 @RequestParam( defaultValue="",name="keyword") String keyword
	) {
		try {
			if (page == null) {
				page = "1";
			}
			int currpage = Integer.parseInt(page); // 현재 페이지
			int totalpage = dao.boardTotalPage(); // 총 페이지
			int rowSize = 8; // 한번에 출력될 게시글
			int start = (rowSize * currpage) - (rowSize - 1);
			int end = (rowSize * currpage);
			int block = 5; // 페이지 블록
			int startpage = ((currpage - 1) / block * block) + 1;
			int endpage = ((currpage - 1) / block * block) + block;
			if (endpage > totalpage) {
				endpage = totalpage;
			}

			// 해쉬맴에 시작 / 꿀 변수 담기
			// ------------------------------------------------------

			Map map = new HashMap();
			map.put("start", start);
			map.put("end", end);
			map.put("searchType", searchType);
			map.put("keyword", keyword);
			System.out.println(map.get("searchType"));
			System.out.println(map.get("keyword"));

			List<BoardVO> list = dao.boardListData(map); // DAO의 메소드 리턴값을 받는 List 변수

			System.out.println(list);

			model.addAttribute("list", list);
			model.addAttribute("block", block);
			model.addAttribute("currpage", currpage);
			model.addAttribute("totalpage", totalpage);
			model.addAttribute("startpage", startpage);
			model.addAttribute("endpage", endpage);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "board/list";
	}

	// 상세보기
	// ====================================================================================================================================================
	@RequestMapping("detail.do")
	public String board_detail(String no, Model model) {
		BoardVO vo = dao.boardDetailData(Integer.parseInt(no));
		model.addAttribute("vo", vo);
		return "board/detail";
	}

	// 작성 페이지만
	// ===========================================================================================================================================================
	@RequestMapping("insert.do")
	public String board_insert(HttpSession session, HttpServletRequest request) {
		session = request.getSession();
		// String id=(String)session.getAttribute("id");
		// System.out.println("id : " + id);
		return "board/insert";
	}

	// 작성 수행
	// ===========================================================================================================================================================
	@RequestMapping("insert_ok.do")
	public String board_insert_ok(@ModelAttribute("vo") BoardVO vo, HttpSession session, HttpServletRequest request,
								  MultipartFile file) {
		try {
			session = request.getSession();
			String id = (String) session.getAttribute("id");
			// System.out.println("id : " + id);
			// vo.setId(id);

			dao.boardInsert(vo);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return "redirect:../board/list.do";
	}

	// 삭제
	// ===========================================================================================================================================================
	@RequestMapping("delete.do")
	public String boardDelete(String no) {

		dao.boardDelete(Integer.parseInt(no));

		return "redirect:../board/list.do";
	}

	//수정 전 내용 가져오기
	// ========================================================================================================================================================
	@RequestMapping("update.do")
	public String boardUpdate(String no, Model model) {

		BoardVO board_vo = dao.boardDetailData(Integer.parseInt(no));

		model.addAttribute("board_vo", board_vo);

		return "board/update";
	}

	// 수정 수행
	// =====================================================================================================================================================
	@RequestMapping("update_ok.do")
	public String boardUpdate_ok(Integer boardnumber, String content, String subject) {

		Map map = new HashMap();
		map.put("boardnumber", boardnumber);
		map.put("content", content);
		map.put("subject", subject);

		dao.boardUpdate(boardnumber);

		System.out.println("���� OK");

		return "redirect:../board/detail.do?boardnumber=" + boardnumber;
	}

	// 검색
	// ==================================================================================================================================================
	@RequestMapping("search.do")
	public String boardList_search(Model model, String page, HttpSession session, HttpServletRequest request,
								   String search_keyword) {
		try {
			if (page == null) {
				page = "1";
			}
			int currpage = Integer.parseInt(page); // 현재 페이지
			int totalpage = dao.searchTotalPage(); // 총 페이지
			int rowSize = 8; // 한번에 출력될 게시글
			int start = (rowSize * currpage) - (rowSize - 1);
			int end = (rowSize * currpage);
			int block = 5; // 페이지 블록
			int startpage = ((currpage - 1) / block * block) + 1;
			int endpage = ((currpage - 1) / block * block) + block;
			if (endpage > totalpage) {
				endpage = totalpage;
			}

			// 해쉬맵에 시작 / 끝 변수 담기
			// ------------------------------------------------------
			Map map = new HashMap();
			map.put("start", start);
			map.put("end", end);
			map.put("search_keyword", search_keyword);

			List<BoardVO> list = dao.boardList_search(map); // DAO 메소드 리턴값을 받는
			// List 변수

			// 페이지로 보낼 파라미터들
			// -----------------------------------------------------------
			model.addAttribute("list", list);
			model.addAttribute("block", block);
			model.addAttribute("currpage", currpage);
			model.addAttribute("totalpage", totalpage);
			model.addAttribute("startpage", startpage);
			model.addAttribute("endpage", endpage);
			model.addAttribute("search_keyword", search_keyword);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "board/search";
	}
}

 

 


# context-common.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
	
	<!-- mybatis SessionFactoryBean -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="com.sist.dao.vo" />
		<property name="mapperLocations" value="classpath*:mapper/board-mapper.xml" />

	</bean>
	
	<!-- sqlSession -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
    </bean>
    <task:annotation-driven/>
    
</beans>

 

 

 

# context-datasource.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:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://210.92.76.29:3306/test?useSSL=false&amp;serverTimezone=UTC" />
		<property name="username" value="root"/>
		<property name="password" value="1234"/>
		<property name="validationQuery" value="SELECT 1" />
	</bean>

</beans>

 

 

 

# context-servlet.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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://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/" />

	<resources mapping="/**" location="/" />

	<!-- 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="/" />
		<beans:property name="suffix" value=".jsp" />
		<beans:property name="order" value="1" />
	</beans:bean>
	
	<context:component-scan base-package="com.sist" />
	
	<beans:bean id="filterMultipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="defaultEncoding" value="UTF-8" />
		<beans:property name="maxUploadSize" value="-1" />
		<beans:property name="resolveLazily" value="true" />
	</beans:bean>
	
	<beans:bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <beans:property name="dataSource" ref="dataSource"/>
    </beans:bean>
	
	<aop:aspectj-autoproxy />

</beans:beans>

 

반응형