영보의 SystemOut.log

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

Spring

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

영보로그 2021. 1. 19. 09:32
반응형

 환경설정

 

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: RDBMS, JDBC, SQLJ, OODBMS, JNDI, LDAP, Servlets, JSP, WAP, XML, EJBs, CMP2.0, JDO, Transactions, Performance, Scalability, Object and Data Modeling (2001)by Carl Calvert Bettis, Michael Bogovich, Sean Rhody, Mark Wilcox, Kelly Lin P

mvnrepository.com

먼저 위의 사이트에서 jstl-jar파일을 다운받아 라이브러리에 넣어주었다.

 

 

 

 

3. 경로 및 환경설정

 

빗금 그은 board-mapper.xml은 무시하면 됩니다 ㅎ.ㅎ

 

 

 코드

 

# 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.2.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>

 - 기존 포스팅에서는 oracle / ojbc로 환경설정을 해주었는데, 이번 포스팅에서는 mysql / jdbc로 환경설정을 해주었다.

 - 마찬가지로 위에 경로처럼 [lib] 폴더를 생성하여 jstl-1.2.jar 파일을 넣어줘야한다.

 

 

 

 

# 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 https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/application-*.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <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>
</web-app>

- 여기서 한글설정을 해주고 경로설정도 본인 경로에 따라 바꿔줘야 합니다.

 

 

 

# BoardVO.java

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

public class BoardVO {
	private int boardnumber,hit;
	  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;
	}
	  
}

- getter/setter 캡슐화 코딩 해줍니다.

 

 

 

# BoardDAO.java

package com.sist.dao;

import java.util.*;

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

import com.sist.mapper.BoardMapper;

@Repository
public class BoardDAO {
	
	@Autowired
	private BoardMapper mapper;
	
	// 게시판 목록 읽기
	public List<BoardVO> boardListData(Map map) {
		return mapper.boardListData(map);
	}

	// 게시판 총페이지 읽기
	public int boardTotalPage() {
		return mapper.boardTotalPage();
	}

	// 게시판 조회수증가,상세보기
	public BoardVO boardDetailData(int no) {
		mapper.boardHitIncrement(no);
		return mapper.boardDetailData(no);
	}

	// 게시판 추가
	public void boardInsert(BoardVO vo) {
		mapper.boardInsert(vo);
	}

	// 게시판 수정
	public void boardUpdate(Map map) {
		mapper.boardUpdate(map);
	}

	// 게시판 삭제
	public void boardDelete(int no) {
		mapper.boardDelete(no);
	}
	
	//  검색
	public List<BoardVO> boardList_search(Map map){
		return mapper.boardList_search(map);
	}
	
	// 검색 후 총페이지 읽기
	public int searchTotalPage() {
		return mapper.searchTotalPage();
	}
}

- CRUD + 검색 기능 

 

 

 

# 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;
    }
    
}

- db 연결해주는 부분

- 없어도 때때로 잘 돌아감

 

 

 

# BoardMapper.java (인터페이스로 생성)

package com.sist.mapper;

import java.util.*;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;

import com.sist.dao.BoardVO;


public interface BoardMapper {
	
	@Select("SELECT boardnumber,name,subject,pwd,content,hit,regdate FROM project1_board")
	public List<BoardVO> boardListData(Map map);
	
	// 게시판1 페이지당 8개로 잘랐을 때 총페이지 수
	@Select("SELECT CEIL(COUNT(*)/8.0) FROM project1_board")
	public int boardTotalPage();
	
	// 게시판1 글번호 자동증가, 글쓰기 데이터추가
	@SelectKey(keyProperty="boardnumber",resultType=int.class,before=true,
			statement="SELECT NVL(MAX(boardnumber)+1,1) as boardnumber FROM project1_board")
	@Insert("INSERT INTO project1_board(boardnumber,name,subject,pwd,content) "
			+"VALUES(#{boardnumber},#{name},#{subject},#{pwd},#{content})")
	public void boardInsert(BoardVO vo);
	
	// 게시판1 조회수증가
	@Update("UPDATE project1_board SET "
			+"hit=hit+1 "
			+"WHERE boardnumber=#{boardnumber}")
	public void boardHitIncrement(int boardnumber);
	
	// 게시판1 상세보기
	@Select("SELECT * FROM project1_board WHERE boardnumber=#{boardnumber}")
	public BoardVO boardDetailData(int boardnumber);
	
	// 게시판1 수정
	@Update("UPDATE project1_board SET content=#{content}, subject=#{subject} WHERE boardnumber=#{boardnumber} AND pwd=#{pwd}")
	public void boardUpdate(Map map);
	
	// 게시판1 삭제 
	@Delete("DELETE FROM project1_board "
			+"WHERE boardnumber=#{boardnumber}")
	public void boardDelete(int boardnumber);
	
	// 검색 
	@Select("SELECT boardnumber, name, subject, pwd, content, hit, regdate "
			+ "FROM project1_board "
			+ "WHERE subject LIKE '%${search_keyword}%' OR content LIKE '%${search_keyword}%' AND boardnumber BETWEEN #{start} AND #{end} ORDER BY boardnumber ")
	public List<BoardVO> boardList_search(Map map);
	
	// 검색 총 페이지 출력
	@Select("SELECT CEIL(COUNT(*) / 10.0) FROM project1_board WHERE #{finding} LIKE '%#{voca}%' AND root = 0")
	public int searchTotalPage(); 
	
}

 - 기존 sql에 만든 테이블안에 데이터가 들어갈 수 있도록 연결해 주는 부분이다.

 - 통상적으로 동적쿼리도 많이 사용하는데, 나는 이게 훨씬 편한 것 같아서 .. 

 

 

 

# BoardController.java

package com.sist.web;

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.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.sist.dao.*;

@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) {
		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);

			List<BoardVO> list = dao.boardListData(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);

		} 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(String boardnumber, String content, String subject) {

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

		dao.boardUpdate(map);

		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.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("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";
	}
}
반응형