<BoardMainController.java>
package kr.board.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/main.do")
public class BoardMainController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/board/templete.jsp");
rd.forward(request, response);
}
}
<templete.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 lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
listLoad()
});
function listLoad() {
$.ajax({
url : "boardList.do",
type : "get",
//data:{},
dataType : "json",
success : listView,
error : function() {
alert("error")
}
});
}
function listView(data) { // [{ },{ },{ },{ }]
//반복문->view(동적인뷰)
var list = "<table class='table'>";
list += "<tr>";
list += "<td>번호</td>";
list += "<td>제목</td>";
list += "<td>작성자</td>";
list += "<td>작성일</td>";
list += "<td>조회수</td>";
list += "</tr>";
$.each(data, function(index, obj) { //obj-> {"idx":1, "title":"aa~"}
list += "<tr>";
list += "<td>" + obj.idx + "</td>";
list += "<td id='t"+obj.idx+"'><a href='javascript:goView("+obj.idx+")'>" + obj.title + "</a></td>";
list += "<td>" + obj.writer + "</td>";
list += "<td>" + obj.indate + "</td>";
list += "<td id='cnt"+obj.idx+"'>" + obj.count + "</td>";
list += "</tr>";
list += "<tr id='c"+obj.idx+"' style='display:none'>";
list += "<td>내용</td>";
list += "<td colspan='4'>";
list += "<textarea id='ta"+obj.idx+"' rows='7' readonly class='form-control'>"+obj.content+"</textarea>"
list += "<br><span id='u"+obj.idx+"'><button class='btn btn-info btn-sm' onclick='goUpdate("+obj.idx+")'>수정</button></span>";
list += " <button class='btn btn-warning btn-sm' onclick='goDel("+obj.idx+")'>삭제</button>";
list += "</td>";
list += "</tr>";
});
if(${!empty mem}){ // 로그인 안하면 글쓰기 안보이게! 로그인 성공했을시 글쓰기 보여야함
list += "<tr>";
list += "<td colspan='5'>";
list += "<button class='btn btn-primary btn-sm' onclick='goForm()'>글쓰기</button>";
list += "</td>";
list += "</tr>";
}
list += "</table>"
$("#view").html(list);
$("#view").css("display", "block");
$("#bfrm").css("display", "none");
}
function goForm() {
$("#view").css("display", "none");
$("#bfrm").css("display", "block");
}
function goInsert(){
var fData=$("#frm").serialize(); //직렬화: title,content,writer
$.ajax({
url:"boardInsert.do",
type:"post",
data:fData,
success: listLoad,
error:function(){alert("error");}
});
$("#reset").trigger("click");
}
function goView(idx){
if($("#c"+idx).css("display")=="none"){
$("#c"+idx).css("display","table-row");
// 조회수 누적
$.ajax({
url : "boardCount.do",
type : "get",
data : {"idx":idx},
dataType : "json",
success : function(data){ // data={ ,"count": 5}
$("#cnt"+idx).text(data.count);
},
error : function(){alert("error");}
});
}else{
$("#c"+idx).css("display","none");
}
}
function goDel(idx){
$.ajax({
url : "boardDelete.do",
type : "get",
data : {"idx":idx},
success : listLoad,
error : function(){alert("error");}
});
}
function goUpdate(idx){
var title=$("#t"+idx).text();
var newInput="<input type='text' id='nt"+idx+"' class='form-control' value='"+title+"'>";
$("#t"+idx).html(newInput);
$("#ta"+idx).attr("readonly",false);
var newButton="<button class='btn btn-success btn-sm' onclick='update("+idx+")'>수정하기</button>"
$("#u"+idx).html(newButton);
}
function update(idx){
//idx, title, content
var title=$("#nt"+idx).val();
var content=$("#ta"+idx).val();
$.ajax({
url : "boardUpdate.do",
type : "post",
data : {"idx":idx,"title":title,"content":content},
success : listLoad,
error : function(){alert("error");}
});
}
</script>
</head>
<body>
<div class="container">
<!-- 헤더 불러오기 -->
<jsp:include page="header.jsp" />
<h2>MVC Framework02</h2>
<div class="panel panel-default">
<div class="panel-heading">
<c:if test="${empty mem}">
<form class="form-inline" action="login.do" method="post">
<div class="form-group">
<label for="memID">아이디:</label> <!-- for랑 name 동일하게 맞춰주기 -->
<input type="text" class="form-control" name="memID">
</div>
<div class="form-group">
<label for="memPwd">비밀번호:</label>
<input type="password" class="form-control" name="memPwd">
</div>
<button type="submit" class="btn btn-default">로그인</button>
</form>
</c:if>
<c:if test="${!empty mem }">
<form class="form-inline" action="logout.do" method="post">
<div class="form-group">
<label>${mem.memName}님 방문을 환영합니다.</label>
</div>
<button type="submit" class="btn btn-default">로그아웃</button>
</form>
</c:if>
</div>
<div class="panel-body" id="view">게시판 리스트</div>
<div class="panel-body" id="bfrm" style="display: none;">
<form id="frm">
<table class="table">
<tr>
<td>제목</td>
<td><input type="text" id="title" name="title" class="form-control"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea rows="7" cols="20" id="content" name="content"
class="form-control"></textarea></td>
</tr>
<tr>
<td>작성자</td>
<td><input type="text" id="writer" name="writer" class="form-control"></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="button" class="btn btn-info btn-sm" onclick="goInsert()">등록</button>
<button type="reset" class="btn btn-warningbtn-sm" id="reset">취소</button>
</td>
</tr>
</table>
</form>
</div>
<div class="panel-footer">지능형 IoT_유경</div>
</div>
</div>
</body>
</html>
<BoardCountController.java>
package kr.board.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import kr.board.dao.BoardDAO;
import kr.board.domain.Board;
@WebServlet("/boardCount.do")
public class BoardCountController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int idx=Integer.parseInt(request.getParameter("idx"));
BoardDAO dao = new BoardDAO();
dao.boardCount(idx); // 조회수 수정
Board vo = dao.boardContent(idx); // 수정된 조회수
Gson g = new Gson();
String json = g.toJson(vo); //{ }
PrintWriter out = response.getWriter();
out.println(json);
}
}
<BoardDAO.java>
package kr.board.dao;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import kr.board.domain.Board;
import kr.board.domain.Member;
// JDBC -> MyBatis(Connection POOL) ->ORM(HIbernate) -> JPA
public class BoardDAO {
// 1. Connection POOL -> SqlSessionFactory
// SqlSessionFactoryBuilder
// SqlSessionFactory
// SqlSession
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "kr/board/dao/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}//_db_
public List<Board> getAllList(){
// BoardMapper.xml(SQL)
// MemberMapper.xml(SQL)
SqlSession session = sqlSessionFactory.openSession();
List<Board> list = session.selectList("getAllList");
session.close(); // 반납(*)
return list;
}
public void boardInsert(Board vo) {
SqlSession session=sqlSessionFactory.openSession();
session.insert("boardInsert", vo);
session.commit(); // insert, delete, update : db내용 바뀜
session.close();
}
public Board boardContent(int idx){
SqlSession session=sqlSessionFactory.openSession();
Board vo = session.selectOne("boardContent", idx);
session.close(); // select : db내용 안바뀌니 commit 안해줘도 됨
return vo;
}
public void boardDelete(int idx) {
SqlSession session=sqlSessionFactory.openSession();
session.delete("boardDelete", idx);
session.commit();
session.close();
}
public void boardUpdate(Board vo) {
SqlSession session=sqlSessionFactory.openSession();
session.update("boardUpdate", vo);
session.commit();
session.close();
}
public void boardCount(int idx) {
SqlSession session=sqlSessionFactory.openSession();
session.update("boardCount",idx);
session.commit();
session.close();
}
public Member checkLogin(Member m) {
SqlSession session=sqlSessionFactory.openSession();
Member mem = session.selectOne("checkLogin", m);
session.close();
return mem;
}
}
<BoardMapper.xml>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.board.dao.BoardDAO" >
<select id="getAllList" resultType="Board">
select * from mboard order by idx desc
</select>
<insert id="boardInsert" parameterType="Board">
insert into mboard(idx, memId, title, content, writer)
values(mboard_idx.nextval,#{memId},#{title},#{content},#{writer})
</insert>
<select id="boardContent" resultType="Board">
select * from mboard where idx=#{idx}
</select>
<delete id="boardDelete">
delete from mboard where idx=#{idx}
</delete>
<update id="boardUpdate" parameterType="Board">
update mboard set title=#{title}, content=#{content} where idx=#{idx}
</update>
<update id="boardCount">
update mboard set count=count+1 where idx=#{idx}
</update>
<select id="checkLogin" resultType="Member" parameterType="Member">
select * from memTbl where memId=#{memId} and memPwd=#{memPwd}
</select>
</mapper>
<Board.java>
package kr.board.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Board {
private int idx;
private String memId;
private String title;
private String content;
private String writer;
private String indate;
private int count;
}
<Member.java>
package kr.board.domain;
import lombok.Data;
@Data
public class Member {
private String memId;
private String memPwd;
private String memName;
}
<Mybatis-config.xml>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- Mapper.xml 파일안에 parameterType, resultType 지정하게 될때
alias를 줘서 보다 간단하게 코드를 작성할 수 있게 도와주는 방법 -->
<typeAliases>
<typeAlias type="kr.board.domain.Board" alias="Board"/>
<typeAlias type="kr.board.domain.Member" alias="Member"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- DB연결설정 -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="hr"/>
<property name="password" value="hr"/>
<!-- url, username, password 프로젝트시 바꿔주기 -->
</dataSource>
</environment>
</environments>
<!-- Mapper 파일(SQL 쿼리문을 가지고 있는 파일) 설정하기 -->
<!-- 파일이 여러개 생성될 수 있다. -->
<mappers>
<mapper resource = "kr/board/dao/BoardMapper.xml"/>
</mappers>
</configuration>
<LoginController.java>
package kr.board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.board.dao.BoardDAO;
import kr.board.domain.Member;
@WebServlet("/login.do")
public class LoginController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String memId=request.getParameter("memID");
String memPwd=request.getParameter("memPwd");
Member m=new Member();
m.setMemId(memId);
m.setMemPwd(memPwd);
BoardDAO dao = new BoardDAO();
Member mem = dao.checkLogin(m);
if(mem!=null) {
// 회원인증 성공!
HttpSession session = request.getSession();
session.setAttribute("mem", mem);
}
// 다시 메인페이지로...
response.sendRedirect("main.do");
}
}
<BoardFrontController.java>
package kr.board.frontcontroller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("*.do")
public class BoardFrontController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.command 구하기
String reqUrl = request.getRequestURI(); // /MVC2/main.do
String ctx = request.getContextPath(); // /MVC2
String command=reqUrl.substring(ctx.length()); // /main.do
}
}
'Maven Project' 카테고리의 다른 글
게시판 Front-Controller command방식 조회수 추가 (0) | 2022.06.01 |
---|---|
HandlerMapping (0) | 2022.05.31 |
게시판 FrontController-command 방식 (0) | 2022.05.30 |
FrontController-command 방식 (0) | 2022.05.30 |
MVC Framework 게시판 (0) | 2022.05.27 |