상세 컨텐츠

본문 제목

Spring - 미니 게시판 만들기

Develop/JAVA

by 에스프리터 2018. 4. 9. 17:59

본문





늘은 Spring 구조를 사용하여 미니 게시판을 만들려고 합니다. 지난번에 게시판을 구혀할 때에는 단순히 JSP로만 구현을 했었죠. 아래 예시에서 Spring controller 가 어떻게 사용되는지 확인해보세요.

파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.




pack.controller 패키지

** BoardBean.java **
package kr.co.controller;

public class BoardBean {
    private int num, readcnt;
    private String author, title, content, bwrite;
    private String searchName, searchValue; //검색용
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getReadcnt() {
        return readcnt;
    }
    public void setReadcnt(int readcnt) {
        this.readcnt = readcnt;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getBwrite() {
        return bwrite;
    }
    public void setBwrite(String bwrite) {
        this.bwrite = bwrite;
    }
    public String getSearchName() {
        return searchName;
    }
    public void setSearchName(String searchName) {
        this.searchName = searchName;
    }
    public String getSearchValue() {
        return searchValue;
    }
    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }
    
    
    
}


** DeleteController.java **
package kr.co.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import kr.co.model.BoardInter;

@Controller
public class DeleteController {
    @Autowired
    private BoardInter inter;
    
    @RequestMapping("delete")
    public String delete(BoardBean bean) {
        boolean b = inter.delete(String.valueOf(bean.getNum()));
        
        if(b)
            return "redirect:/list";
        else
            return "err";
        
    }
}


** DetailController.java **
package kr.co.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import kr.co.model.BoardDto;
import kr.co.model.BoardInter;

@Controller
public class DetailController {
    @Autowired
    private BoardInter inter;
    
    @RequestMapping
    public ModelAndView list(@RequestParam("num")String num) {
        BoardDto dto = inter.detail(num);
        return new ModelAndView("detail","dto",dto);
    }
    
}


** ListController.java **
package kr.co.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import kr.co.model.BoardDto;
import kr.co.model.BoardInter;

@Controller
public class ListController {
    
    @Autowired
    @Qualifier("boardDao")
    private BoardInter boardInter;
    
    @RequestMapping("list")
    public ModelAndView list() {
        List<BoardDto> list = boardInter.list();
        return new ModelAndView("list", "list", list);
    }
    
}


** SearchController.java **
package kr.co.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import kr.co.model.BoardDto;
import kr.co.model.BoardInter;

@Controller
public class SearchController {
    @Autowired
    @Qualifier("boardDao")
    private BoardInter boardInter;
    
    @RequestMapping("search")
    public ModelAndView search(BoardBean bean) {
        System.out.println(bean.getSearchValue());
        List<BoardDto> list = boardInter.search(bean.getSearchName(), bean.getSearchValue());
        return new ModelAndView("list", "list", list);
    }
}


** UpdateController.java **
package kr.co.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import kr.co.model.BoardInter;

@Controller
public class UpdateController {
    @Autowired
    private BoardInter inter;
    
    @RequestMapping("update")
    public String update(BoardBean bean) {
        boolean b = inter.update(bean);
        if(b)
            return "redirect:/list";
        else
            return "err";
    }
}


** WriterController.java **
package kr.co.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import kr.co.model.BoardInter;

@Controller
public class WriterController {
    @Autowired
    @Qualifier("boardDao")
    private BoardInter boardInter;
    
    @RequestMapping(value="write", method=RequestMethod.GET)
    public String write() {
        return "insform";
    }
    
    @RequestMapping(value="write", method=RequestMethod.POST)
    public String submit(BoardBean bean) {
        boolean b = boardInter.writeData(bean);
        if(b)
            return "redirect:/list";
        else
            return "err";
    }
    
}



pack.model 패키지

** BoardDao.java **
package kr.co.model;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

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

import kr.co.controller.BoardBean;

@Repository
public class BoardDao implements BoardInter{
    private DataSource ds;
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    
    @Autowired
    public BoardDao(MyDataSource dataSource) {
        try {
            ds = dataSource;
            
        } catch (Exception e) {
            System.out.println("MyDataSource err" + e);
        }
        
    }
    
    public List<BoardDto> list() {
        ArrayList<BoardDto> list = new ArrayList<BoardDto>();
        try {
            String sql ="select * from miniboard order by num desc";
            conn = ds.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while(rs.next()) {
                BoardDto dto = new BoardDto();
                dto.setNum(rs.getInt("num"));
                dto.setAuthor(rs.getString("author"));
                dto.setTitle(rs.getString("title"));
                dto.setContent(rs.getString("content"));
                dto.setBwrite(rs.getString("bwriter"));
                dto.setReadcnt(rs.getInt("readcnt"));
                list.add(dto);
                
            }
            
        } catch (Exception e) {
            System.out.println("list err : " + e);
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }

        return list;
    }
    
    public List<BoardDto> search(String name, String value) {
        ArrayList<BoardDto> list = new ArrayList<BoardDto>();
        try {
            String sql ="select * from miniboard" + " where " + name + " like '%" + value + "%'" + " order by num desc";
            System.out.println(value);
            conn = ds.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while(rs.next()) {
                BoardDto dto = new BoardDto();
                dto.setNum(rs.getInt("num"));
                dto.setAuthor(rs.getString("author"));
                dto.setTitle(rs.getString("title"));
                dto.setContent(rs.getString("content"));
                dto.setBwrite(rs.getString("bwriter"));
                dto.setReadcnt(rs.getInt("readcnt"));
                list.add(dto);
            }            
        } catch (Exception e) {
            System.out.println("list err : " + e);
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return list;
    }
    
    public BoardDto detail(String num) {
        BoardDto dto = null;
        try {
            // 상세보기 시 조회수 증가
            String sql = "update miniboard set readcnt=readcnt + 1 where num=?";
            conn = ds.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, num);
            pstmt.executeUpdate();
            
            sql = "select * from miniboard where num=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, num);
            rs = pstmt.executeQuery();
            if(rs.next()) {
                dto = new BoardDto();
                dto.setNum(rs.getInt("num"));
                dto.setAuthor(rs.getString("author"));
                dto.setTitle(rs.getString("title"));
                dto.setContent(rs.getString("content"));
                dto.setBwrite(rs.getString("bwriter"));
                dto.setReadcnt(rs.getInt("readcnt"));
                
            }
            
        } catch (Exception e) {
            System.out.println("detail err " + e);
        }finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return dto;
    }
    
    public boolean writeData(BoardBean bean) {
        boolean b = false;
        try {
            conn = ds.getConnection();
            String sql ="insert into miniboard(author,title,content)values(?,?,?);";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bean.getAuthor());
            pstmt.setString(2, bean.getTitle());
            pstmt.setString(3, bean.getContent());
            if(pstmt.executeUpdate() > 0) b = true;            
        } catch (Exception e) {
            System.out.println("writeData err " + e);
        }finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        
        return b;
    }
    
    public boolean update(BoardBean bean) {
        boolean b = false;
        try {
            String sql = "update miniboard set author=?, title=?, content=? where num=?";
            conn = ds.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bean.getAuthor());
            pstmt.setString(2, bean.getTitle());
            pstmt.setString(3, bean.getContent());
            pstmt.setInt(4, bean.getNum());
            if(pstmt.executeUpdate() > 0) b = true;
            
        } catch (Exception e) {
            System.out.println("update err " + e);
        }finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return b;
    }
    
    public boolean delete(String num) {
        boolean b = false;
        try {
            String sql = "delete from miniboard where num=?";
            conn= ds.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, num);
            if(pstmt.executeUpdate() > 0) b = true;
            
        } catch (Exception e) {
            System.out.println("update err " + e);
        }finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return b;
    }
    
    
    
}


** BoardDto.java **
package kr.co.model;

public class BoardDto {
    private int num, readcnt;
    private String author, title, content, bwrite;
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getReadcnt() {
        return readcnt;
    }
    public void setReadcnt(int readcnt) {
        this.readcnt = readcnt;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getBwrite() {
        return bwrite;
    }
    public void setBwrite(String bwrite) {
        this.bwrite = bwrite;
    }
    
    
}


** BoardInter.java **
package kr.co.model;

import java.util.List;

import kr.co.controller.BoardBean;

public interface BoardInter {
    List<BoardDto> list();
    boolean writeData(BoardBean bean);
    List<BoardDto> search(String name, String value);
    BoardDto detail(String num);
    boolean update(BoardBean bean);
    boolean delete(String num);
}


** MyDataSource.java **
package kr.co.model;

import org.springframework.jdbc.datasource.DriverManagerDataSource; //BasicDataSource
import org.springframework.stereotype.Repository;

@Repository("dataSource")
public class MyDataSource extends DriverManagerDataSource {
    public MyDataSource() {
        setDriverClassName("org.mariadb.jdbc.Driver");
        setUrl("jdbc:mysql://localhost:3306/test");
        setUsername("root");
        setPassword("123");

    }

}



webapp 폴더

** detail.jsp **
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload= function() {
    document.getElementById("btnList").onclick = function(){
        location.href="list";
    };
    
    document.getElementById("btnUpdate").onclick = function(){
        if(confirm("정말 수정?")){
            // 입력자료 오류 검사 생략
            frm.action = "update";
            frm.submit();
        }
    };
    
    document.getElementById("btnDelete").onclick = function(){
        if(confirm("정말 삭제?")){
            //frm.action="delete?num=" + frm.num.value;
            frm.action = "delete";
            frm.submit();            
        }
    };
    
}

</script>

</head>
<body>
* 상세보기 *<p/>
<form name="frm" method="post">
글 번호 : ${dto.num}
<input type="hidden" name="num" value="${dto.num}">
<br>
작성자 : <input type="text" name="author" value="${dto.author}"><br>
글제목 : <input type="text" name="title" value="${dto.title}"><br>
글내용 : <textarea rows="5" cols="50" name="content">${dto.content}</textarea><br>
작성일 : ${dto.bwrite}<br>
조회수 : ${dto.readcnt}<br>
<input type="button" value="목록" id="btnList">
<input type="button" value="수정" id="btnUpdate">
<input type="button" value="삭제" id="btnDelete">
</form>
</body>
</html>

** insform.jsp **
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
** 글쓰기 ** <p/>
<form action="write" method="post">
글제목 : <input type="text" name="title"><br>
작성자 : <input type="text" name="author"><br>
글내용 : <textarea rows="5" cols="30" name="content"></textarea>
<br><br>
<input type="submit" value="저장">
</form>
</body>
</html>

** list.jsp **
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
* 미니 게시판(DB는 전통적인 방식) *<p/>
<a href="write">글쓰기</a>
<table border="1">
    <tr>
        <th>번호</th><th>제목</th><th>작성자</th><th>조회수</th>
        <c:forEach var="b" items="${list}">
        <tr>
            <td>${b.num}</td>
            <td><a href="detail?num=${b.num}">${b.title}</a></td>
            <td>${b.author}</td>
            <td>${b.readcnt}</td>
        </tr>
        </c:forEach>
        <!-- 검색 -->
        <tr>
            <td colspan="4">
            <form action="search" method="post">
                <select name="searchName">
                <option value="author">작성자</option>
                <option value="title">제목</option>
                </select>
                <input type="text" name="searchValue">
                <input type="submit" value="검색하기">
            </form>
    </tr>
</table>
</body>
</html>

** mvc-config.xml **
<?xml version="1.0" encoding="UTF-8"?>



         <context:component-scan
            base-package="kr.co.controller"/>
            <context:component-scan
            base-package="kr.co.model"/>


    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>


** web.xml **
<?xml version="1.0" encoding="ISO-8859-1"?>
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    id="WebApp_ID" version="2.5">

    <display-name>sweb18_miniboard</display-name>

    <!-- - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener. -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!-- - Servlet that dispatches request to registered handlers (Controller
        implementations). -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>


** inde.jsp **
<!DOCTYPE html>

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

<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head>
    <body>
        <a href="list">미니게시판</a>
    </body>
</html>
    

그 외

** pom.xml **
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples.service.service</groupId>
  <artifactId>sweb18_miniboard</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <properties>
      <!-- Generic properties -->
      <java.version>1.8</java.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      
      <!-- Web -->
      <jsp.version>2.2</jsp.version>
      <jstl.version>1.2</jstl.version>
      <servlet.version>2.5</servlet.version>

      <!-- Spring -->
      <spring-framework.version>4.3.11.RELEASE</spring-framework.version>

      <!-- Logging -->
      <logback.version>1.0.13</logback.version>
      <slf4j.version>1.7.5</slf4j.version>
   </properties>
   
   <dependencies>
      <!-- Spring MVC -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>${spring-framework.version}</version>
      </dependency>
      
      <!-- Other Web dependencies -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>${jstl.version}</version>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>servlet-api</artifactId>
         <version>${servlet.version}</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>javax.servlet.jsp</groupId>
         <artifactId>jsp-api</artifactId>
         <version>${jsp.version}</version>
         <scope>provided</scope>
      </dependency>
   
      <!-- Spring and Transactions -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-tx</artifactId>
         <version>${spring-framework.version}</version>
      </dependency>

      <!-- Logging with SLF4J & LogBack -->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>${slf4j.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>ch.qos.logback</groupId>
         <artifactId>logback-classic</artifactId>
         <version>${logback.version}</version>
         <scope>runtime</scope>
      </dependency>
      
          <!-- RDBMS : MariaDb driver -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.2.3</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>  
    
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    
    
        <!-- Mybatis -->
        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
        </dependency>

        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
        </dependency>
      
   </dependencies>   
</project>



결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.







태그

관련글 더보기

댓글 영역