데일리로그C:
article thumbnail
Published 2023. 4. 28. 16:23
스프링 Board 구현 JAVA/spring

새 프로젝트 만들때

1. 설정(11버전으로 수정, junit 4 적용)

2. 복사

 1) src/main/java

    - domain package

    - persistence package

 2) src/main/resources

    - mappers

    - mybatis-config.xml

 3) src > main > webapp > WEB-INF > spring > appServlet

    - servlet-context.xml

    - root-context.xml

 4) src > main > webapp > WEB-INF > view

     - web.xml

 5) pom.xml

 

3. index.jsp 생성

  - 그 후 homecontroller.java에서 return "index" 수정

  - home.jsp 삭제

 

 

 

* 찾는 순서 : jsp -> servlet

*

webapp 안에 include 만들거나 --> include/header

view 안에 include 만들기 --> 

 

* controller 안에 다 넣을 거임 (ex) member 관련은 membercontroller 안에 다 넣기


1. table 생성 & insert

create table tbl_board (
	bno int not null auto_increment,
	title varchar(255) not null,
	content text null,
	writer varchar(50) not null,
	regdate TIMESTAMP not null default now(),
	viewcnt int default 0,
	primary key(bno) 
);


insert into tbl_board (title, content, writer) values ("제목 이란다.","내용이란다.","1111");

 

2. index.jsp 만들기

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<table width=100% height=100 border=0>
	<tr>
		<td align=center>index 내용</td>
	</tr>
</table>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

3. view > include 폴더 

 - header.jsp

<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Spring MVC 패턴</title>
<link rel="stylesheet" href="/css/basic.css">
</head>
<body>

<table width=100% height=50 border=0>
	<tr>
		<td><a href="/"><img src="/img/cry.jpg" width=90></a></td>
		<td align=right>
			<a href="">[로그인]</a>
			<a href="">[회원가입]</a>
		</td>
	</tr>
</table>

<hr>

 - footer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<hr>

<table width=100% height=50 border=0>
	<tr>
		<td align=center>카피라이터</td>
	</tr>
</table>
</body>

</html>

 

4. webapp > resources

 > css 폴더

  - basic.css

@charset "UTF-8";

* {
	margin:0px;
	padding:0px;
	font-size:11px; 
}

table, td {
	border-collapse:collapse;
}

a:link, a:visited {
	color:black; text-decoration:none;
}

a:hover, a:focus, a:active {
	color:black; text-decoration:none;
}

 > img 폴더 : 이미지 c+c , c+v

 

 > js 폴더

 

5. BoardVO.java  --> domain에

package org.zerock.domain;

import java.util.Date;

import lombok.Data;

@Data
public class BoardVO {

	private Integer bno;
	private String title;
	private String content;
	private String writer;
	private Date regdate;
	private int viewcnt;

}

 

6. BoardDAO.java  --> persistence에

package org.zerock.persistence;

import java.util.List;

import org.zerock.domain.BoardVO;

public interface BoardDAO {

	public void create(BoardVO vo) throws Exception;
	public BoardVO read(Integer bno) throws Exception;
	public void update(BoardVO vo) throws Exception;
	public void delete(Integer bno) throws Exception;
	public List<BoardVO> listAll() throws Exception;
}

 

7. boardMapper.xml --> mappers에

  ㄴ> select, insert, update, delete 구문이 추가될때 마다 mapper에 추가하기

<?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="org.zerock.mapper.BoardMapper">
	<insert id="create">
		insert into tbl_board (title, content, writer) values (#{title},#{content}, #{writer})
	</insert>

	<select id="read" resultType="org.zerock.domain.BoardVO">
		select * from tbl_board where bno = #{bno}
	</select>

	<update id="update">
		update tbl_board set title =#{title}, content =#{content} where bno = #{bno}
	</update>

	<delete id="delete">
		delete from tbl_board where bno = #{bno}
	</delete>

	<select id="listAll" resultType="org.zerock.domain.BoardVO">
	<!-- <![CDATA[ ]] 쓰는 이유 -->
	<!-- sql 구문안에 비교 연산자가 들어갈 경우(특수문자) 문자열로 인식하게 하기 위해서 ... -->
	<![CDATA[
		select * from tbl_board where bno > 0 order by bno desc
	]]>
	</select>

</mapper>

한건 데이터 --> selectOne

여러개 데이터(목록) --> selectlist 

 

<! [CDATA[ sql 구문 안에 있는 비교연산자, 특수문자 등등 있어도 이건 sql구문이다 라고 알려주는 선언임 ]]> 

 

8. BoardDAOImpl.java --> persistence에

* session객체는 SqlSession session; 으로 함!

package org.zerock.persistence;

import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import org.zerock.domain.BoardVO;

@Repository
public class BoardDAOImpl implements BoardDAO {

	@Inject
	private SqlSession session;
	private static String namespace = "org.zerock.mapper.BoardMapper"; // 변수처리

	@Override
	public void create(BoardVO vo) throws Exception {  // 리턴값이 없으므로 실행
		session.insert(namespace+".create", vo);
		// 변수 namespace+"id값" --> id : boardMapper.xml에 있음
	}

	@Override
	public BoardVO read(Integer bno) throws Exception { // 있다면
		return session.selectOne(namespace+".read", bno); // 한건의 데이터
	}

	@Override
	public void update(BoardVO vo) throws Exception {
		session.update(namespace+".update", vo);
	}

	@Override
	public void delete(Integer bno) throws Exception {
		session.delete(namespace+".delete", bno);
	}

	@Override
	public List<BoardVO> listAll() throws Exception { 
		// arraylist or vectorlist와 같지만 스프링에서는 인터페이스를 적극 활용해 list 사용하는걸 추천!
		return session.selectList(namespace+".listAll"); //목록
	}
	
}

 

9. BoardDAOTest.java

* 참고

int bno

integer bno --> 객체로 보내는거임

package org.zerock.controller;

import java.util.List;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.zerock.domain.BoardVO;
import org.zerock.persistence.BoardDAO;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/**/root-context.xml" })
public class BoardDAOTest {

	@Inject
	private BoardDAO dao; //부모 클래스 타입으로 객체 선언

	private static Logger logger = LoggerFactory.getLogger(BoardDAOTest.class);
	
	@Test //글쓰기
	public void testCreate() throws Exception {	

		BoardVO board = new BoardVO();		

		board.setTitle("새로운 글 제목");
		board.setContent("내용이다.");
		board.setWriter("1111");
		//dao.create(board); // insert

		//logger.info("글쓰기");
	}
	
	@Test //읽기
	public void testRead() throws Exception {
		//logger.info(dao.read(2).toString());
	}
	
	@Test //수정
	public void testUpdate() throws Exception{
		
		BoardVO board = new BoardVO();		

		board.setBno(2);
		board.setTitle("수정된 글이다.");
		board.setContent("수정된 내용이다.");
		//dao.update(board);
		
		//logger.info("수정하기");
	}
	
	@Test //목록
	public void testList() throws Exception{		
		List<BoardVO> list = dao.listAll();
		
		for(BoardVO v: list) { 
			// 객체를 담은 list객체가 한단계 아래의 객체인 class 타입인 v에 담아서
			//logger.info(v.toString());
		}
	}
	
	@Test //삭제
	public void testDelete() throws Exception{
		dao.delete(2);
		
		logger.info("삭제");
	}
	
}

 

10. BoardService.java --> service에

* 참고

void --> 리턴값 없음

BoardVO --> 리턴값 있음

List<BoardVO> --> 리턴값 있음

package org.zerock.service;

import java.util.List;

import org.zerock.domain.BoardVO;

public interface BoardService {

	public void regist(BoardVO board) throws Exception;
	public BoardVO read(Integer bno) throws Exception;
	public void modify(BoardVO board) throws Exception;
	public void remove(Integer bno) throws Exception;
	public List<BoardVO> listAll() throws Exception;
}

 

11. BoardServiceImpl.java

package org.zerock.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.zerock.domain.BoardVO;
import org.zerock.persistence.BoardDAO;

@Service //스프링 빈으로 인식되기 위해 선언(@repository와 같은데 붙이는 곳이 다름)
public class BoardServiceImpl implements BoardService{

	@Inject
	private BoardDAO dao; // DAO를 이용

	@Override
	public void regist(BoardVO board) throws Exception {
		dao.create(board);
	}

	@Override
	public BoardVO read(Integer bno) throws Exception {
		return dao.read(bno);
	}

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

	@Override
	public void remove(Integer bno) throws Exception {
		dao.delete(bno);
	}

	@Override
	public List<BoardVO> listAll() throws Exception {
		return dao.listAll();
	}
	
}

 

12. BoardController.java 

package org.zerock.controller;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.zerock.domain.BoardVO;
import org.zerock.service.BoardService;

@Controller
@RequestMapping("/board/*") // 부모에 해당
public class BoardController {

	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);

	@Inject
	private BoardService service; //인스턴스 변수의 선언으로 BoardService 객체를 주입 받을 수 있게 설계 처리
	
	@RequestMapping(value = "/register", method = RequestMethod.GET) // get방식이라면 아래메소드 실행
	public void registerGET(BoardVO board) throws Exception { // void이므로 forward
		logger.info("register get ...........");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST) // post방식이라면 아래 메소드 실행
	public String registPOST(BoardVO board, Model model) throws Exception {
		logger.info("regist post ...........");
		logger.info(board.toString());

		service.regist(board);

		model.addAttribute("result", "success"); // success라는 문자열을 result로 전달

		return "/board/success";
	}
}

 

13. view > board 폴더 

 1) register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<center>
<h3>WRITER PAGE</h3>

<form method="post">
<table>
	<tr>
		<td>제목</td>
		<td><input name="title"></td>
	</tr>
	<tr>
		<td>내용</td>
		<td><textarea name="content" rows="3"></textarea></td>
	</tr>
	<tr>
		<td>작성자</td>
		<td><input name="writer"></td>
	</tr>
	<tr>
		<td></td>
		<td><button>Submit</button></td>
	</tr>
</table>
</form>

</center>


<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

 2) success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
result : ${result}
</body>
</html>

 

14. BoardController.java --> listAll 추가

package org.zerock.controller;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.service.BoardService;

@Controller
@RequestMapping("/board/*") // 부모에 해당
public class BoardController {

	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);

	@Inject
	private BoardService service; //인스턴스 변수의 선언으로 BoardService 객체를 주입 받을 수 있게 설계 처리
	
	@RequestMapping(value = "/register", method = RequestMethod.GET) // get방식이라면 아래메소드 실행
	public void registerGET(BoardVO board) throws Exception { // void이므로 forward
		logger.info("register get ...........");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST) // post방식이라면 아래 메소드 실행
	public String registPOST(BoardVO board, RedirectAttributes rttr) throws Exception { // 변수명 칼럼명과 동일하게 해야 자동으로 set,get처리 됨
		logger.info("regist post ...........");
		logger.info(board.toString());

		service.regist(board);

		rttr.addFlashAttribute("msg","register");
		
		//return "/board/success";
		return "redirect:/board/listAll";
	}
	
	//목록
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	public void listAll(Model model) throws Exception {
		logger.info("show all list......................");

		model.addAttribute("list", service.listAll());
	}

}

 

15. listAll.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<center>
<h3>LIST PAGE</h3>

<table border=1 width=700>
	<tr>
		<th style="width:10px">BNO</th>
		<th>TITLE</th>
		<th>WRITER</th>
		<th>REGDATE</th>
		<th style="width: 40px">VIEWCNT</th>
	</tr>
</table>

<br>

<table border=0 width=700>
	<tr>
		<td align=right><a href="register">[글쓰기]</a></td>
	</tr>
</table>

</center>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

listAll.jsp  --> script, foreach 구문 추가

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<script>
	var result = "${msg}";

	if(result == "register"){ // alert 뜬 후 새로고침하면 없어지므로 다시 뜨진 않음
		alert("작성 완료!");
	}
</script>

<center>
<h3>LIST PAGE</h3>

<table border=1 width=700>
	<tr>
		<th style="width:10px">BNO</th>
		<th>TITLE</th>
		<th>WRITER</th>
		<th>REGDATE</th>
		<th style="width: 40px">VIEWCNT</th>
	</tr>
	
	<c:forEach var="boardVO" items="${list}">
	<tr>
		<td>${boardVO.bno }</td>
		<td><a href="/board/read?bno=${boardVO.bno }">${boardVO.title }</a></td>
		<td>${boardVO.writer }</td>
		<!-- <td>${boardVO.regdate }</td>  --> 
		<td><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${boardVO.regdate }"/></td>
		<td>${boardVO.viewcnt }</td>
	</tr>
	</c:forEach>
</table>

<br>

<table border=0 width=700>
	<tr>
		<td align=right><a href="register">[글쓰기]</a></td>
	</tr>
</table>

</center>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

16.header.jsp --> [게시판]

<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Spring MVC 패턴</title>
<link rel="stylesheet" href="/css/basic.css">
</head>
<body>

<table width=100% height=50 border=0>
	<tr>
		<td><a href="/"><img src="/img/cry.jpg" width=90></a></td>
		<td align=right>
			<a href="">[로그인]</a>
			<a href="">[회원가입]</a>
		</td>
	</tr>
	<tr>
		<td colspan=2 align=center><a href="/board/listAll">[게시판]</a></td>
	</tr>
</table>

<hr>

 

17. BoardController.java (206) - read 추가

package org.zerock.controller;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.service.BoardService;

@Controller
@RequestMapping("/board/*") // 부모에 해당
public class BoardController {

	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);

	@Inject
	private BoardService service; //인스턴스 변수의 선언으로 BoardService 객체를 주입 받을 수 있게 설계 처리
	
	@RequestMapping(value = "/register", method = RequestMethod.GET) // get방식이라면 아래메소드 실행
	public void registerGET(BoardVO board) throws Exception { // void이므로 forward
		logger.info("register get ...........");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST) // post방식이라면 아래 메소드 실행
	public String registPOST(BoardVO board, RedirectAttributes rttr) throws Exception { // 변수명 칼럼명과 동일하게 해야 자동으로 set,get처리 됨
		logger.info("regist post ...........");
		logger.info(board.toString());

		service.regist(board);

		rttr.addFlashAttribute("msg","register");
		
		//return "/board/success";
		return "redirect:/board/listAll";
	}
	
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	public void listAll(Model model) throws Exception {
		logger.info("show all list......................");

		model.addAttribute("list", service.listAll());
	}
	
	@RequestMapping(value = "/read", method = RequestMethod.GET)
	public void read(@RequestParam("bno") int bno, Model model) throws Exception { // void이므로 read.jsp로 forward
		logger.info("read get ...........");

		model.addAttribute(service.read(bno));
		//model.addAttribute("전달할 객체명",service.read(bno));
		//처리를 하지 않아 jsp페이지에서는 boardVO 객체명을 사용하게 된다.
	}
	
}

 

18. read.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<center>
<h3>READ PAGE</h3>

<table border=1 width=570>
	<tr>
		<td width=70>제목</td>
		<td width=500>${boardVO.title }</td>
	</tr>
	<tr>
		<td>내용</td>
		<td>${boardVO.content }</td>
	</tr>
	<tr>
		<td>작성자</td>
		<td>${boardVO.writer }</td>
	</tr>
</table>

<br>

<table border=0 width=570>
	<tr>
		<td width=50%><a href="listAll">[리스트]</a></td>
		<td width=50% align="right">
			<a href="/board/modify?bno=${boardVO.bno }">[수정]</a> 
			<a href="/board/remove?bno=${boardVO.bno }">[삭제]</a>
		</td>
	</tr>
</table>


</center>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

19. BoardController.java --> remove 구문추가

get 방식 param으로 넘어왔으니 @RequestParam("bno") int bno

or

model.addAttribute(service.read(bno));  // 객체를 return

로 해도됨

package org.zerock.controller;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.service.BoardService;

@Controller
@RequestMapping("/board/*") // 부모에 해당
public class BoardController {

	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);

	@Inject
	private BoardService service; //인스턴스 변수의 선언으로 BoardService 객체를 주입 받을 수 있게 설계 처리
	
	@RequestMapping(value = "/register", method = RequestMethod.GET) // get방식이라면 아래메소드 실행
	public void registerGET(BoardVO board) throws Exception { // void이므로 forward
		logger.info("register get ...........");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST) // post방식이라면 아래 메소드 실행
	public String registPOST(BoardVO board, RedirectAttributes rttr) throws Exception { // 변수명 칼럼명과 동일하게 해야 자동으로 set,get처리 됨
		logger.info("regist post ...........");
		logger.info(board.toString());

		service.regist(board);

		rttr.addFlashAttribute("msg","register");
		
		//return "/board/success";
		return "redirect:/board/listAll";
	}
	
	//목록
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	public void listAll(Model model) throws Exception {
		logger.info("show all list......................");

		model.addAttribute("list", service.listAll());
	}
	
	//read
	@RequestMapping(value = "/read", method = RequestMethod.GET)
	public void read(@RequestParam("bno") int bno, Model model) throws Exception { // void이므로 read.jsp로 forward
		logger.info("read get ...........");

		model.addAttribute(service.read(bno));
		//model.addAttribute("전달할 객체명",service.read(bno));
		//처리를 하지 않아 jsp페이지에서는 boardVO 객체명을 사용하게 된다.
	}
	
	
	//삭제
	@RequestMapping(value = "/remove", method = RequestMethod.GET)
	public String remove(@RequestParam("bno") int bno, RedirectAttributes rttr) throws Exception {

		service.remove(bno);

		rttr.addFlashAttribute("msg", "delete"); // delete 라는 문자열을 msg라는 객체에 담아 한번만 전달.
		
		return "redirect:/board/listAll";
	}
	
}

 

20. BoardController.java --> 수정 추가

package org.zerock.controller;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.service.BoardService;

@Controller
@RequestMapping("/board/*") // 부모에 해당
public class BoardController {

	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);

	@Inject
	private BoardService service; //인스턴스 변수의 선언으로 BoardService 객체를 주입 받을 수 있게 설계 처리
	
	@RequestMapping(value = "/register", method = RequestMethod.GET) // get방식이라면 아래메소드 실행
	public void registerGET(BoardVO board) throws Exception { // void이므로 forward
		logger.info("register get ...........");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST) // post방식이라면 아래 메소드 실행
	public String registPOST(BoardVO board, RedirectAttributes rttr) throws Exception { // 변수명 칼럼명과 동일하게 해야 자동으로 set,get처리 됨
		logger.info("regist post ...........");
		logger.info(board.toString());

		service.regist(board);

		rttr.addFlashAttribute("msg","register");
		
		//return "/board/success";
		return "redirect:/board/listAll";
	}
	
	//목록
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	public void listAll(Model model) throws Exception {
		logger.info("show all list......................");

		model.addAttribute("list", service.listAll());
	}
	
	//read
	@RequestMapping(value = "/read", method = RequestMethod.GET)
	public void read(@RequestParam("bno") int bno, Model model) throws Exception { // void이므로 read.jsp로 forward
		logger.info("read get ...........");

		model.addAttribute(service.read(bno));
		//model.addAttribute("전달할 객체명",service.read(bno));
		//처리를 하지 않아 jsp페이지에서는 boardVO 객체명을 사용하게 된다.
	}
	
	
	//삭제
	@RequestMapping(value = "/remove", method = RequestMethod.GET)
	public String remove(@RequestParam("bno") int bno, RedirectAttributes rttr) throws Exception {

		service.remove(bno);

		rttr.addFlashAttribute("msg", "delete"); // delete 라는 문자열을 msg라는 객체에 담아 한번만 전달.
		
		return "redirect:/board/listAll";
	}
	
	
	// 수정 (버튼누르면 post)
	@RequestMapping(value = "/modify", method = RequestMethod.GET)
	public void modifyGET(int bno, Model model) throws Exception { // 리턴 없으므로 전달하면 끝

		model.addAttribute(service.read(bno));
	}

	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public String modifyPOST(BoardVO board, RedirectAttributes rttr) throws Exception {
		logger.info("mod post............");

		service.modify(board);

		rttr.addFlashAttribute("msg", "modify");
		return "redirect:/board/listAll";

	}

	
	
}

 

21. listAll.jsp - script 수정

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<script>
	var result = "${msg}";

	if(result == "register"){ // alert 뜬 후 새로고침하면 없어지므로 다시 뜨진 않음
		alert("작성 완료!");
	}else if(result == "delete"){
		alert("삭제 완료!");
	}else if(result == "modify"){
		alert("수정 완료!");
	}
</script>

<center>
<h3>LIST PAGE</h3>

<table border=1 width=700>
	<tr>
		<th style="width:10px">BNO</th>
		<th>TITLE</th>
		<th>WRITER</th>
		<th>REGDATE</th>
		<th style="width: 40px">VIEWCNT</th>
	</tr>
	
	<c:forEach var="boardVO" items="${list}">
	<tr>
		<td>${boardVO.bno }</td>
		<td><a href="/board/read?bno=${boardVO.bno }">${boardVO.title }</a></td>
		<td>${boardVO.writer }</td>
		<!-- <td>${boardVO.regdate }</td>  --> 
		<td><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${boardVO.regdate }"/></td>
		<td>${boardVO.viewcnt }</td>
	</tr>
	</c:forEach>
</table>

<br>

<table border=0 width=700>
	<tr>
		<td align=right><a href="register">[글쓰기]</a></td>
	</tr>
</table>

</center>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

23. read.jsp --> 제이쿼리 사용

  ㄴ> header.jsp 에 jQuery 추가

<head>
<!-- jQuery 사용추가 --> 
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>
</head>

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/WEB-INF/views/include/header.jsp" %>

<center>
<h3>READ PAGE</h3>

<table border=1 width=570>
	<tr>
		<td width=70>제목</td>
		<td width=500>${boardVO.title }</td>
	</tr>
	<tr>
		<td>내용</td>
		<td>${boardVO.content }</td>
	</tr>
	<tr>
		<td>작성자</td>
		<td>${boardVO.writer }</td>
	</tr>
</table>

<br>

<table border=0 width=570>
	<tr>
		<td width=50%><a href="listAll">[리스트]</a></td>
		<td width=50% align="right">
			<a href="/board/modify?bno=${boardVO.bno }">[수정]</a> 
			<a href="/board/remove?bno=${boardVO.bno }">[삭제]</a>
		</td>
	</tr>
</table>


<!-- ajax 이용 -->
<form role="pkt" name="pkt" method="get">
	<!-- role은 장애인을 위한 웹 접근성 -->
	<input type="hidden" name="bno" value="${boardVO.bno }">
</form>

<button class="btn-modify">수정</button>
<button class="btn-delete">삭제</button>
<button class="btn-list">리스트</button>



</center>

<%@ include file="/WEB-INF/views/include/footer.jsp" %>

 

* 참고

인터페이스 사용 안할거면 implement 없애기, override 빼기

 

'JAVA > spring' 카테고리의 다른 글

스프링 Board 구현_넘버링, 검색  (0) 2023.05.03
스프링 Board 구현_예외처리, 페이징  (1) 2023.05.02
스프링 페이지 이동(변수 전달)  (0) 2023.04.28
스프링 프로젝트 생성  (0) 2023.04.27
스프링 설치 및 설정  (0) 2023.04.27
profile

데일리로그C:

@망밍

포스팅이 도움됐다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...