Java Spring JSP웹페이지 만들기9 (뒤로 가기, 게시글 수정 기능)

호연지기·2023년 6월 2일
0
post-thumbnail

이제 거의 다 만들어진건가...? 하면 계속 늘어나는 것들..

그동안 생각없이 사용해왔던 모든 웹 서비스에게 무한히 감사드립니다...
지금 사용하고 있는 벨로그 서비스도 넘 감사해요..

💞 게시글 기능 추가하기 (수정, 뒤로가기)

U 버튼 : 게시글 수정하기
B 버튼 : 뒤로가기(글 목록 페이지로 이동)

//버튼 영역
<div class="btn-area">
  <button class="btn-write" id="upbtn" onclick="upboard('${board.b_num}')">U</button>
  <button class="btn-write" id="delbtn" onclick="delCheck('${board.b_num}')">D</button>
  <button class="btn-sub" onclick="backbtn()">B</button>
</div>

버튼 영역에서 #upbtnbackbtn() 처리!

✏ 작업 순서

  1. backbtn()이 간단하니까 먼저 처리
    ( boardContents , SearchDto )
  2. U 버튼을 누르면 수정용 updateForm 페이지를 불러와서 수정할 내용을 작성하게끔 만들어준다.
    ( boardContents , boardController , updateForm )
  3. 글 내용 영역 수정 및 데이터베이스 업로드
    ( updateForm , boardController , BoardService , BoardDao )
  4. 파일을 추가하거나 삭제도 가능하게끔 파일 수정 기능 만들기
    ( updateForm , boardController , BoardService , BoardDao )

🔻 뒤로가기 기능

💻 BoardContents 소스

function backbtn(){
let urlstr = "/list?";
let col = "${sdto.colname}";
let keyw = "${sdto.keyword}";

if(col == null || col == ''){//검색을 수행하지 않은 경우
  urlstr += "pageNum=${pageNum}";
} else{//검색을 한 경우
  urlstr += "colname=${sdto.colname}&keyword=${sdto.keyword}&pageNum=${sdto.pageNum}";
}
console.log(urlstr);
location.href = urlstr;
}

list urlstr에서 참조하는 sdto.colname과 sdto.keyword를 확인하고 검색 여부에 따라 이동하는 페이지가 달라진다.

💻 BoardController 소스

@GetMapping("list")
public ModelAndView boardList(SearchDto sdto, HttpSession session){
    log.info("boardList()");
    mv = bServ.getBoardList(sdto,session); //서비스에서 데이터 삽입 및 목적페이지 지정
    return mv;
}

💻 SearchDto 소스

@Data
public class SearchDto {
    private String colname;
    private String keyword;
    private int pageNum;//보여질 페이지 번호
    private int listCnt;//페이지 당 출력할 게시글 개수
}

검색을 하지 않은 상태에서 게시글 상세보기 페이지의 B 버튼을 누르면 원래 사용자가 원래 있던 페이지로 이동한다.

만약 이런식으로 검색창에 검색을 한 뒤 게시글을 클릭했다가 B 버튼을 누른다면 urlstr
http://localhost/list?colname=b_title&keyword=페이지&pageNum=1 로 저장되어 해당 페이지로 그대로 돌아오게 된다.

🔻 게시글 수정하기 (JSP 만들기)

게시글 수정용 updateForm jsp 페이지를 만든다.

💻 BoardContents 소스

  function upboard(bnum) {
    location.href ="/updateForm?b_num=" +bnum;
  }

BoardContents에서 수정 버튼을 누르면 해당 글 번호의 updateForm으로 이동한다.

💻 updateForm 소스 (글쓰기 영역)

<h2 class="login-header">글수정</h2>
<!-- 로그인한 id(숨김), 제목, 내용 -->
<input type="hidden" name="b_id" value="${mb.m_id}">
<input type="hidden" name="b_num" value="${board.b_num}">
<input type="text" class="write-input" name="b_title"
       autofocus placeholder="제목" required value="${board.b_title}">
<textarea name="b_contents" class="write-input ta" rows="15" placeholder="내용을 적어주세요.">${board.b_contents}</textarea>

글쓰기 페이지인 writeForm과 비슷하지만 updateForm은 사용자가 기존에 입력했었던 데이터들이 페이지에 미리 입력되어 있다.
(수정하기 위한 페이지이므로)

💻 BoardController 소스

@GetMapping("updateForm")
public ModelAndView updateForm(Integer b_num){
    log.info("updateForm()");
    mv = bServ.updateForm(b_num);
    return mv;
}

💻 BoardService 소스

public ModelAndView updateForm(Integer b_num){
    log.info("updateForm()");
    //게시글 내용 가져오기
    BoardDto board = bDao.selectBoard(b_num);

    //파일 목록 가져오기
    List<BfileDto> fList = bDao.selectFiles(b_num);

    //mv에 추가.
    mv = new ModelAndView();
    mv.addObject("board", board);
    mv.addObject("fList", fList);

    //view 지정
    mv.setViewName("updateForm");
    return mv;
}

💻 BoardDao.java 소스

@Mapper
public interface BoardDao {
    //게시글 1개 가져오는 메소드 선언
    BoardDto selectBoard(Integer b_num);
}

💻 BoardDao.xml 소스

<select id="selectBoard" resultType="BoardDto" parameterType="Integer">
    select * from blist where b_num=#{b_num}
</select>

수정할 게시글 데이터를 가져오는 쿼리문

🔻 파일 수정

💻 updateForm 소스 (파일처리 영역)

<div class="filebox">
    <!--첨부된 파일 목록 출력-->
    <div id="bfile" style="margin-bottom: 10px;">
        <c:if test="${empty fList}">
            <label style="width: 100%;">첨부파일 없음</label>
        </c:if>
        <c:if test="${!empty fList}">
            <c:forEach var="f" items="${fList}">
                <label style="width: 100%;" onclick="del('${f.bf_sysname}')">
                    ${f.bf_oriname}
                </label>
            </c:forEach>
        </c:if>
    </div>
    <!--새로운 파일 첨부-->
    <label for="file">파일 추가</label>
    <input type="file" name="files" id="file" multiple>
    <input type="text" class="upload-name" value="파일선택" readonly>
</div>

💻 updateForm 소스 (script 소스)

//파일 제목 처리용 함수
$("#file").on("change",function(){
    //파일 선택 창에서 업로드할 파일을 선택한 후 '열기' 버튼을 누르면 change 이벤트가 발생.
    console.log($("#file"));

    let files = $("#file")[0].files;
    console.log(files);

    let fileName = "";
    if(files.length > 1){
        fileName = files[0].name + " 외 " + (files.length -1) + "개";
    } else if(files.length == 1){
        fileName = files[0].name;
    } else {
        fileName = "파일선택";
    }
    $(".upload-name").val(fileName);
});

💻 BoardController 소스

@PostMapping("updateProc")
public String updateProc(@RequestPart List<MultipartFile> files
                         , BoardDto board
                         , HttpSession session
                         , RedirectAttributes rttr){
    log.info("updateProc()");
    String view = bServ.updateBoard(files, board, session, rttr);
    return view;
}

파일 제목 처리용 함수로 파일 추가를 하면 fileName 영역에 추가한 파일 이름이 노출된다.

글 수정 페이지

123.jpg 파일을 추가한 모습

🔻 수정 처리가 다 되었다면 데이터베이스에 수정한 게시글 저장까지 하자!

💻 BoardController 소스

@PostMapping("updateProc")
public String updateProc(@RequestPart List<MultipartFile> files
                         , BoardDto board
                         , HttpSession session
                         , RedirectAttributes rttr){
    log.info("updateProc()");
    String view = bServ.updateBoard(files, board, session, rttr);
    return view;
}

💻 BoardDao.java 소스

 //게시글 수정 메소드 선언
void updateBoard(BoardDto board);

💻 BoardDao.xml 소스

<update id="updateBoard" parameterType="BoardDto">
    update board set b_title=#{b_title}, b_contents=#{b_contents}
    where b_num=#{b_num}
</update>

🔻 파일 삭제

💻 updateForm 소스 (script 소스)

//파일 삭제 처리 함수
function del(sysname) {
    //alert(sysname);
    let con = confirm("파일을 삭제할까요?");

    if(con == true){
        //삭제할 파일명
        let objdata = {"sysname":sysname};
        //파일 목록을 다시 불러오기 위해 게시글 번호 추가
        objdata.bnum = ${board.b_num};
        console.log(objdata);

        $.ajax({
            url:"delFile",
            type: "post",
            data: objdata,
            success: function (res) {
                console.log(res);
                console.log(res.length);

                let flist = "";
                if(res.length == 0){
                    flist += '<label style="width: 100%;">첨부파일 없음</label>';
                }
                else {
                    for(let f of res){
                        flist += '<label style="width: 100%;"token operator">+ f.bf_sysname + '\')">'
                                 + f.bf_oriname + '</label>';
                    }
                }
                $("#bfile").html(flist);
            },
            error: function (err) {
                console.log(err);
                alert("삭제 실패");
            }
        });
    }
}

기존에 업로드 해뒀던 파일을 삭제하는 함수로 파일을 클릭하면 삭제 확인용 알림창이 뜨면서 삭제 처리를 할 수 있다.

💻 BoardController 소스

@PostMapping("delFile")
@ResponseBody
public List<BfileDto> delFile(String sysname, Integer bnum, HttpSession session){

    log.info("delFile()");
    List<BfileDto> fList = bServ.fileDelete(sysname, bnum, session);

    return fList;
}

💻 BoardService 소스

public List<BfileDto> fileDelete(String sysname, Integer bnum, HttpSession session){
    log.info("fileDelete()");
    List<BfileDto> fList = null;

    //파일 삭제를 위한 실제 경로 구하기
    String realpath = session.getServletContext().getRealPath("/");
    realpath += "upload/" + sysname;

    try{
        //파일 삭제
        File file = new File(realpath);
        if(file.exists()){
            if(file.delete()){
                //파일 정보 삭제(파일 삭제 성공 시)
                bDao.deleteSingleFile(sysname);
                //나머지 파일 목록 다시 가져오기
                fList = bDao.selectFiles(bnum);
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    return fList;
}

💻 BoardDao.java 소스

//파일 삭제 메소드 선언(개별 파일)
void deleteSingleFile(String sysname);
//파일 목록 가져오는 메소드 선언
List<BfileDto> selectFiles(Integer b_num);

선택한 파일을 삭제 후 삭제한 파일 목록을 다시 가져온다.

💻 BoardDao.xml 소스

<delete id="deleteSingleFile" parameterType="String">
    delete from boardfile where bf_sysname=#{sysname}
</delete>

<select id="selectFiles" resultType="BfileDto" parameterType="Integer">
    select * from boardfile where bf_bnum=#{b_num}
</select>

📅 DATE

2023.06.02 작성

profile
사람의 마음에 차 있는 너르고 크고 올바른 기운

0개의 댓글