이 게시물은
http://www.wiz.center/246
http://www.wiz.center/247
http://www.wiz.center/248
http://www.wiz.center/249
http://www.wiz.center/250
해당 링크를 청취하고 작성한 글입니다.
본인 이해도 확인을 위해서 작성한 것이니
스프링에 대해서 알고 있다면 쑥 훝어보고 끝내시고
좀 깊게 알고 싶다면 위의 링크부터 시작해서
총 30개 강의로 이루어진 스프링 과정을 청취하세요
1. 게시판 설계
기본 진행 혹은 db 작업을 요청한 경우
: 사용자요청 -> dispatcher-> Controller
-> command(s) -> DAo -> DB
DB작업 후 혹은 db를 거치지 않는 요청
: Controller -> view(s) (jsp 파일)
* 데이터 객체는 DTO로 작성
2. DB 작성
예제는 Oracle 테이블 구축이지만 여기서는 Mysql 로 작성
Mysql 설치방법은 Oracle.com 에서 받는데 이중 mysqld 로
프로세스만 띄워서 진행하는 방법으로 (pc에 주는 부하가 싫어서)
진행함.
테이블 작성의 경우 Oracle과 다른점은 크게 없지만
bId 의 경우 AUTO_INCREMENT 설정을 줘서
자동으로 번호 부여가 가능하다
varchar2 -> varchar
sysdate -> current_timestamp or now() or 트리거 사용
으로 설정 가능 버전마다 상이함
CHARSET=utf8 인데 세부 옵션은 utf8_general_ci
CREATE TABLE IF NOT EXISTS `mvc_board` (
`bId` int(4) NOT NULL AUTO_INCREMENT,
`bName` varchar(20) CHARACTER SET latin1 DEFAULT NULL,
`bTitle` varchar(100) CHARACTER SET latin1 DEFAULT NULL,
`bContent` varchar(300) CHARACTER SET latin1 DEFAULT NULL,
`bDate` datetime DEFAULT CURRENT_TIMESTAMP,
`bHit` int(4) DEFAULT '0',
`bGroup` int(4) DEFAULT NULL,
`bStep` int(4) DEFAULT NULL,
`bIndent` int(4) DEFAULT NULL,
PRIMARY KEY (`bId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
복습 : 계층형 게시판 참고사항
bGroup <> 로 표시함
게시판 원글부터 시작하여 같은 글에 포함된 댓글 모두는
같은 번호를 가지게 된다.
원글 <1>
└답변 <1>
└답변 <1>
└답변 <1>
└답변 <1>
원글 <2>
└답변 <2>
└답변 <2>
bStep ()로 표시
몇번째 글인지를 표시
원글 <1> (1)
└답변 <1> (2)
└답변 <1> (3)
└답변 <1> (4)
└답변 <1> (5)
원글 <2> (1)
└답변 <2> (2)
└답변 <2> (3)
bIndent []로 표시
위에서 몇번째 들여쓰기 대상인가 (원본글의 댓글인가 댓글의 댓글인가)
원글 <1> (1) [1]
└답변 <1> (2) [2]
└답변 <1> (3) [2]
└답변 <1> (4) [3]
└답변 <1> (5) [2]
원글 <2> (1) [1]
└답변 <2> (2) [2]
└답변 <2> (3) [3]
3. 프로젝트 생성
1) spring Project - spring MVC Project 로 생성
프로젝트명은 : spring_pjt_board
패키지는 : com.javalec.spring_pjt_board
2) web.xml 에 다음 내용을 추가(한글 깨짐 방지)
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
3. list 페이지 작성
1) 패키지 및 클래스 생성
ps. 이때 BCommand 는
void execute(Model model);
함수를 가지는 interface고
나머지는 Command를 implements 할 것.
2) 컨트롤러를 인식하기 위한 servlet 셋팅
servlet-context.xml 의 context:component-scan base-package
를 아래와 같이 변경
3) 컨트롤러 작성 및 메소드별 유형
(3-1) 단순한 페이지 요청
- 작업 화면 지시
@RequestMapping("/write_view")
public String write_view(Model model){
System.out.println("write_view()");
//작성화면 호출이라 입력할수 있는 화면으로 이동만 담당
return "write_view";
}
(3-2) DB에서 자료를 가지고 화면에 보여줘야 되는 경우
- list
@RequestMapping("/list")
public String like(Model model){
System.out.println("list()");
command = new BListCommand();
command.execute(model);
return "list";
}
(3-3) form 객체를 받아 처리해야하는 경우
- 수정, 변경 작업 진행시
@RequestMapping("/content_view")
public String content_view(HttpServletRequest request, Model model){
System.out.println("content_view()");
model.addAttribute("request", request);
command = new BContentCommand();
command.execute(model);
return "content_view";
}
작업 환경에 따라 변경 적용 하여 진행
package com.javalec.spring_pjt_board.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.javalec.spring_pjt_board.command.BCommand;
import com.javalec.spring_pjt_board.command.BContentCommand;
import com.javalec.spring_pjt_board.command.BDeleteCommand;
import com.javalec.spring_pjt_board.command.BListCommand;
import com.javalec.spring_pjt_board.command.BModifyCommand;
import com.javalec.spring_pjt_board.command.BReplyCommand;
import com.javalec.spring_pjt_board.command.BReplyViewCommand;
import com.javalec.spring_pjt_board.command.BWriteCommand;
@Controller
public class BController {
BCommand command;
@RequestMapping("/list")
public String like(Model model){
System.out.println("list()");
command = new BListCommand();
command.execute(model);
return "list";
}
@RequestMapping("/write_view")
public String write_view(Model model){
System.out.println("write_view()");
//작성화면 호출이라 입력할수 있는 화면으로 이동만 담당
return "write_view";
}
@RequestMapping("/write")
public String write(HttpServletRequest request, Model model){
System.out.println("write()");
model.addAttribute("request", request);
command = new BWriteCommand();
command.execute(model);
return "redirect:list";
}
@RequestMapping("/content_view")
public String content_view(HttpServletRequest request, Model model){
System.out.println("content_view()");
model.addAttribute("request", request);
command = new BContentCommand();
command.execute(model);
return "content_view";
}
@RequestMapping(method=RequestMethod.POST, value="/modify")
public String modify(HttpServletRequest request, Model model){
System.out.println("modify");
model.addAttribute("request", request);
command = new BModifyCommand();
command.execute(model);
return "redirect:list";
}
@RequestMapping("/reply_view")
public String reply_view(HttpServletRequest request, Model model){
System.out.println("reply_view()");
model.addAttribute("request", request);
command = new BReplyViewCommand();
command.execute(model);
return "reply_view";
}
@RequestMapping("/reply")
public String reply(HttpServletRequest request, Model model){
System.out.println("reply()");
model.addAttribute("request", request);
command = new BReplyCommand();
command.execute(model);
return "redirect:list";
}
@RequestMapping("/delete")
public String delete(HttpServletRequest request, Model model){
System.out.println("delete()");
model.addAttribute("request", request);
command = new BDeleteCommand();
command.execute(model);
return "redirect:list";
}
}
3) DTO 객체 작성
- 테이블 구조와 같은 멤버변수를 지니도록 작성
, set 및 get 함수를 생성
, list() 라는 함수를 만들어 각 멤버변수가 들어가도록 생성
package com.javalec.spring_pjt_board.dto;
import java.sql.Timestamp;
public class BDto {
int bId;
String bName;
String bTitle;
String bContent;
Timestamp bDate;
int bHit;
int bGroup;
int bStep;
int bIndent;
public BDto(){
}
public BDto(int bId, String bName, String bTitle, String bContent, Timestamp bDate, int bHit, int bGroup, int bStep, int bIndent){
this.bId = bId;
this.bName = bName;
this.bTitle = bTitle;
this.bContent = bContent;
this.bDate = bDate;
this.bHit = bHit;
this.bGroup = bGroup;
this.bStep = bStep;
this.bIndent = bIndent;
}
public String getbContent() {
return bContent;
}
public void setbContent(String bContent) {
this.bContent = bContent;
}
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbTitle() {
return bTitle;
}
public void setbTitle(String bTitle) {
this.bTitle = bTitle;
}
public Timestamp getbDate() {
return bDate;
}
public void setbDate(Timestamp bDate) {
this.bDate = bDate;
}
public int getbHit() {
return bHit;
}
public void setbHit(int bHit) {
this.bHit = bHit;
}
public int getbGroup() {
return bGroup;
}
public void setbGroup(int bGroup) {
this.bGroup = bGroup;
}
public int getbStep() {
return bStep;
}
public void setbStep(int bStep) {
this.bStep = bStep;
}
public int getbIndent() {
return bIndent;
}
public void setbIndent(int bIndent) {
this.bIndent = bIndent;
}
}
3-1) DB설정을 Mysql로 하기위해 다음 작업을 추가
아래 링크 참고하여 작성
http://www.mkyong.com/tomcat/how-to-configure-mysql-datasource-in-tomcat-6/
4) DAO 작성
* query 작성시 주의
* 현재는 내용대로 불편한 방식으로 작성 후
차후 좀더 편한방식
(mybatis, ibatis, xml) 이나
사용목적에 따라 (ajax 등)
으로 변경예정
package com.javalec.spring_pjt_board.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//mysql 에서도 같은걸 제공하는데 그냥 sql꺼 쓸것.
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.javalec.spring_pjt_board.dto.BDto;
public class BDao {
@Resource(name="jdbc/mysql")
DataSource datasource;
public BDao(){
try {
Context context = new InitialContext();
datasource = (DataSource) context.lookup("java:comp/env/jdbc/mysql");
} catch (NamingException e) {
e.printStackTrace();
}
}
public ArrayList list(){
ArrayList dtos = new ArrayList();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
connection = (Connection) datasource.getConnection();
String query = "select bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from mvc_board order by bGroup desc, bStep asc";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
dtos.add(dto);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(resultSet != null)resultSet.close();
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
return dtos;
}
}
5) list를 가져올 list.jsp 작성
(jstl + 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 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>
<table width="500" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>히트</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
<a href="content_view?bId=${dto.bId}">${dto.bTitle}</a></td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5"> <a href="write_view">글작성</a> </td>
</tr>
</table>
</body>
</html>
6) 실행
4. write 작성
1) write_view.jsp 작성
controller 에 아래와 같이 작성되어 있는 상태인데
@RequestMapping("/write_view")
public String write_view(Model model){
System.out.println("write_view()");
//작성화면 호출이라 입력할수 있는 화면으로 이동만 담당
return "write_view";
}
이중 앞에 건 그대로 페이지만 이동하게끔 하면 됨
이에 따라서 write_view.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>
<table width="500" cellpadding="0" cellspacing="0" border="1">
<form action="write" method="post">
<tr>
<td> 이름 </td>
<td> <input type="text" name="bName" size = "50"> </td>
</tr>
<tr>
<td> 제목 </td>
<td> <input type="text" name="bTitle" size = "50"> </td>
</tr>
<tr>
<td> 내용 </td>
<td> <textarea name="bContent" rows="10" ></textarea> </td>
</tr>
<tr >
<td colspan="2"> <input type="submit" value="입력"> <a href="list.do">목록보기</a></td>
</tr>
</form>
</table>
</body>
</html>
2) write 라는 요청에 대해 대응 하기 위한 컨트롤러 작성 내용 확인
@RequestMapping("/write")
public String write(HttpServletRequest request, Model model){
System.out.println("write()");
model.addAttribute("request", request);
command = new BWriteCommand();
command.execute(model);
return "redirect:list";
}
그리고
BWriteCommand() 클래스 작성
package com.javalec.spring_pjt_board.command;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import com.javalec.spring_pjt_board.dao.BDao;
public class BWriteCommand implements BCommand {
@Override
public void execute(Model model) {
// TODO Auto-generated method stub
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bName = request.getParameter("bName");
String bTitle = request.getParameter("bTitle");
String bContent = request.getParameter("bContent");
BDao dao = new BDao();
dao.write(bName, bTitle, bContent);
}
}
여기에서 호출하는 DAO 의 함수 작성
mysql에서는 시퀀스 증가값을 테이블에 하나씩 밖에 줄수 없기
때문에 id max 값을 가져와서 group 를 짓도록 작성함
그냥 조회해서 write 했다고 생각하면 됨.
public void write(String bName, String bTitle, String bContent){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//mysql 추가분 group 의 경우 id와 같은 값이지만 (글 작성시)
// mysql에는 증가값이 테이블당 1개만 작성가능해서 따로 구해서 insert를 진행하기로 함
// 해당 예제는 처음 작성시에 대한 대응이 안되어 있음.
int maxid=0;
try{
connection = (Connection) datasource.getConnection();
String query = "select max(bId) as maxId from mvc_board";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
maxid = resultSet.getInt("maxId");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(resultSet != null)resultSet.close();
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
try{
connection = datasource.getConnection();
String query ="insert into test.mvc_board (bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent) "
+ " values (?,?,?,now(),0,? ,0,0)";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, bName);
preparedStatement.setString(2, bTitle);
preparedStatement.setString(3, bContent);
preparedStatement.setInt(4, maxid);
int rm = preparedStatement.executeUpdate();
System.out.println("insert number :"+rm);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
5. 게시글 보기 작성
1) 게시글에 대한 content_view.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>
<table width="500" cellpadding="0" cellspacing="0" border="1">
<form action="modify" method="post">
<input type="hidden" name="bId" value="${content_view.bId}">
<tr>
<td> 번호 </td>
<td> ${content_view.bId} </td>
</tr>
<tr>
<td> 히트 </td>
<td> ${content_view.bHit} </td>
</tr>
<tr>
<td> 이름 </td>
<td> <input type="text" name="bName" value="${content_view.bName}"></td>
</tr>
<tr>
<td> 제목 </td>
<td> <input type="text" name="bTitle" value="${content_view.bTitle}"></td>
</tr>
<tr>
<td> 내용 </td>
<td> <textarea rows="10" name="bContent" >${content_view.bContent}</textarea></td>
</tr>
<tr >
<td colspan="2"> <input type="submit" value="수정"> <a href="list">목록보기</a> <a href="delete?bId=${content_view.bId}">삭제</a> <a href="reply_view?bId=${content_view.bId}">답변</a></td>
</tr>
</form>
</table>
</body>
</html>
2) 컨트롤러에서는 BContentCommand() 클래스에서
작성토록 설정하였기 때문에 해당 클래스를 작성한다.
@Override
public void execute(Model model) {
// TODO Auto-generated method stub
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bId = request.getParameter("bId");
// after write
BDao dao = new BDao();
BDto dto = dao.contentView(bId);
model.addAttribute("content_view", dto);
}
3) BContentCommand() 에서 호출하는 dao.contentView(bId)
를 구현한다.
Content 가져올때 hit 숫자를 증가시키는 메소드를 포함하였음.
public BDto contentView(String strid){
upHit(strid);
BDto dto = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
connection = (Connection) datasource.getConnection();
String query = "select bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from mvc_board where bId=?";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
preparedStatement.setInt(1, Integer.parseInt(strid));
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(resultSet != null)resultSet.close();
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
System.out.println(dto.toString());
return dto;
}
private void upHit( String bId) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = (Connection) datasource.getConnection();
String query = "update test.mvc_board set bHit = bHit + 1 where bId = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, bId);
int rn = preparedStatement.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if(preparedStatement != null) preparedStatement.close();
if(connection != null) connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
6. 글 수정 하기
1) jsp는 content_view.jsp 에서 보내는 form 을 확인
modify - POST 방식으로 보내는걸 확인 가능함
2) BCommand 인터페이스를 implements 한 BModifyCommand
를 작성한다.
package com.javalec.spring_pjt_board.command;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import com.javalec.spring_pjt_board.dao.BDao;
import com.javalec.spring_pjt_board.dto.BDto;
public class BModifyCommand implements BCommand {
@Override
public void execute(Model model) {
// TODO Auto-generated method stub
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bId = request.getParameter("bId");
String bName = request.getParameter("bName");
String bTitle = request.getParameter("bTitle");
String bContent = request.getParameter("bContent");
BDao dao = new BDao();
dao.modify(bId, bName, bTitle, bContent);
}
}
3) dao 에 트렌젝션 처리를 위한 작업을 진행한다.
public void modify(String bId, String bName, String bTitle, String bContent){
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = (Connection) datasource.getConnection();
String query = "update mvc_board set bName =?, bTitle=?, bContent=? where bId = ?";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
preparedStatement.setString(1, bName);
preparedStatement.setString(2, bTitle);
preparedStatement.setString(3, bContent);
preparedStatement.setInt(4,Integer.parseInt(bId));
int rn=preparedStatement.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
7. 글 삭제 하기
1) Controller 는 그대로 진행
2) BModifyCommand .java 작성
package com.javalec.spring_pjt_board.command;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import com.javalec.spring_pjt_board.dao.BDao;
import com.javalec.spring_pjt_board.dto.BDto;
public class BModifyCommand implements BCommand {
@Override
public void execute(Model model) {
// TODO Auto-generated method stub
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bId = request.getParameter("bId");
String bName = request.getParameter("bName");
String bTitle = request.getParameter("bTitle");
String bContent = request.getParameter("bContent");
BDao dao = new BDao();
dao.modify(bId, bName, bTitle, bContent);
}
}
3) Dao 에 delete 함수 작성
public void delete(String bId) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = (Connection) datasource.getConnection();
String query = "delete from mvc_board where bId = ?";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
preparedStatement.setInt(1,Integer.parseInt(bId));
int rn=preparedStatement.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
8. 글 답변 페이지 만들기
1) 글에서 답변을 눌렀을때 뜨는 화면인 reply_view.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>
<table width="500" cellpadding="0" cellspacing="0" border="1">
<form action="reply" method="post">
<input type="hidden" name="bId" value="${reply_view.bId}">
<input type="hidden" name="bGroup" value="${reply_view.bGroup}">
<input type="hidden" name="bStep" value="${reply_view.bStep}">
<input type="hidden" name="bIndent" value="${reply_view.bIndent}">
<tr>
<td> 번호 </td>
<td> ${reply_view.bId} </td>
</tr>
<tr>
<td> 히트 </td>
<td> ${reply_view.bHit} </td>
</tr>
<tr>
<td> 이름 </td>
<td> <input type="text" name="bName" value="${reply_view.bName}"></td>
</tr>
<tr>
<td> 제목 </td>
<td> <input type="text" name="bTitle" value="${reply_view.bTitle}"></td>
</tr>
<tr>
<td> 내용 </td>
<td> <textarea rows="10" name="bContent">${reply_view.bContent}</textarea></td>
</tr>
<tr >
<td colspan="2"><input type="submit" value="답변"> <a href="list" >목록</a></td>
</tr>
</form>
</table>
</body>
</html>
2) 컨트롤러에서 해당 내용 확인 및 ReplyViewCommand.java 구현
package com.javalec.spring_pjt_board.command;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import com.javalec.spring_pjt_board.dao.BDao;
import com.javalec.spring_pjt_board.dto.BDto;
public class BReplyViewCommand implements BCommand {
@Override
public void execute(Model model) {
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bId = request.getParameter("bId");
BDao dao = new BDao();
BDto dto = dao.reply_view(bId);
model.addAttribute("replay_view", dto);
}
}
3) dto.reply_view(bID) 구현
public BDto reply_view(String bid) {
BDto dto = new BDto();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
connection = (Connection) datasource.getConnection();
String query = "select * from mvc_board where bId = ?";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
preparedStatement.setInt(1,Integer.parseInt(bid));
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(resultSet != null)connection.close();
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
return dto;
}
4) BReplyCommand.java 작성
package com.javalec.spring_pjt_board.command;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import com.javalec.spring_pjt_board.dao.BDao;
public class BReplyCommand implements BCommand {
@Override
public void execute(Model model) {
Map map = model.asMap();
HttpServletRequest request = (HttpServletRequest) map.get("request");
String bId = request.getParameter("bId");
String bName = request.getParameter("bName");
String bTitle = request.getParameter("bTitle");
String bContent = request.getParameter("bContent");
String bGroup = request.getParameter("bGroup");
String bStep = request.getParameter("bStep");
String bIndent = request.getParameter("bIndent");
BDao dao = new BDao();
dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);
}
}
5) dao 에 다음 두개 함수를 추가
public void reply(String bId, String bName, String bTitle, String bContent, String bGroup, String bStep, String bIndent) {
replyShape(bGroup, bStep);
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = (Connection) datasource.getConnection();
String query = "insert into test.mvc_board(bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent) values (?,?,?,now(),0,?,?,?)";
preparedStatement = (PreparedStatement) connection.prepareStatement(query);
preparedStatement.setString(1,bName);
preparedStatement.setString(2,bTitle);
preparedStatement.setString(3,bContent);
preparedStatement.setInt(4,Integer.parseInt(bGroup));
preparedStatement.setInt(5,Integer.parseInt(bStep)+1);
preparedStatement.setInt(6,Integer.parseInt(bIndent)+1);
int rn=preparedStatement.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(preparedStatement != null)preparedStatement.close();
if(connection != null)connection.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
private void replyShape( String strGroup, String strStep) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = datasource.getConnection();
String query = "update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, Integer.parseInt(strGroup));
preparedStatement.setInt(2, Integer.parseInt(strStep));
int rn = preparedStatement.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if(preparedStatement != null) preparedStatement.close();
if(connection != null) connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
9. 게시판 작성중 한글 처리 관련 오류 수정 방법
자세한 방법은 아래 링크를 참고할 것.
http://blog.naver.com/akrmak6/203238987
포인트는 db 설정을 바꿈 -> 컬럼, 테이블 설정 문자셋을 교체
(컬럼별로도로 문자셋이 있음) -> mysql 재시작
ok
Oracle 로 하면 잘되는데 Mysql, MariaDB 두가지는
위처럼 set 별, table, 컬럼별 설정이 동일해야
정상적으로 한글을 표현 할 수 있다.
그렇지만 결론은 플잭 초기에 확인되기 때문에 이것때문에
고생할 일은 없다.