**인터셉터 

게시글쓰기, 상세보기, 수정, 삭제 등은 로그인 되어 있지 않은 유저는 작업을 수행할 수 없도록 하고자 하는 경우 이러한 코드를 Controller, Service, Dao 등에 작성하는 것은 이상합니다.

스프링에서는 Interceptor 나 AOP 등을 이용해서 구현 할 수 있습니다.

Interceptor는 URL을 설정해서 URL 요청이 왔을 때 메소드를 호출하도록 할 수 있습니다.


1. 로그인이 되어 있지 않으면 로그인 페이지로 이동시키고 로그인을 하면 작업을 할 수 있는 페이지로 이동하도록 만들어봅시다. 


=> Interceptor : url 요청이 왔을 때 Controller 보내기 전이나 Controller가 작업한 후에 수행할 내용을 작성할 수 있는 Spring이

제공하는 기능 

=>HandlerInterceptor 인터페이스나 HandlerInterceptorAdapter 클래스를 상속받는 클래스를 만들어서 메소드를 재정의 하고 

dispatcher-servlet(Servlet-Context.xml)에 interceptors 태그를 이용해서 설정하면 됩니다.

=> HandlerInterceptorAdapter인터페이스는 모든 메소드가 추상메소드라서 전부 재정의 해야하고 

HandlerInterceptorAdapter 클래스는 모든 메소드가 내용이 없는 상태로 구현되어 있어서 필요한 메소드만 재정의 하면 되는데 

메소드 이름을 기억하기 어려우므로 인터페이스를 이용합시;다. 



2.HandlerInterceptorAdapter를 implements 한 클래스 안의 재정의 된 메소드 설명 

=> com.seunghoo.na.AuthenticationInerceptor


1. preHandle 메소드 : Controller가 처리하기 전에 호출되는 메소드 


2. postHandle 메소드 : Controller가 사용자의 요청을 정상적으로 처리하고 난 후 호출되는 메소드 


3. afterCompletion메소드 :  Controller에서 예외 발생여부에 상관없이 호출되는 메소드 



3.HandlerInterceptorAdapter를 implements 한 클래스를 생성 

@Component

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception {


// 로그인을 확인하기 위해서 session 가져오기

HttpSession session = request.getSession();

// 로그인 정보는 session의 user 속성에 저장되어 있습니다.

if (session.getAttribute("user") == null) {

// 사용자의 요청을 session에 dest라는 속성에 저장

// 로그인이 되면 원래의 요청을 처리하기 위해서

// 클라이언트 요청 전체 주소

String requestURI = request.getRequestURI();

// 현재 프로젝트 경로 가져오기

String contextPath = request.getContextPath();

String uri = requestURI.substring(contextPath.length() + 1);

// 주소 뒤에 파라미터를 가져오기

String query = request.getQueryString();

System.out.println("쿼리"+query);

System.out.println("URI"+uri);

// 실제 주소만들기

if (query == null || query.equals("null")) {

query = "";

} else {

query = "?" + query;

}

//세션에 주소 저장하기 

session.setAttribute("dest", uri+query);

//세션에 메시지 저장하기 

session.setAttribute("msg","로그인을 하셔야 이용할 수 있는 서비스 입니다.");


response.sendRedirect(contextPath + "/user/login");

return false;

}

// 로그인된 경우에는 Controller가 처리합니다.


return true;

}

4. UserController 에서 로그인을 처리하는 메소드를 수정 

=> 이전에는 무조건 시작 페이지로 가도록 되어 있었지만 요청이 있는 경우 그페이지로 이동하도록 코드를 수정 

session.setAttribute("user", user);

//이전 요청을 가져오기 

Object dest = session.getAttribute("dest");

//이전 요청이 없으면 시작페이지로 이동 

if(dest==null) {

return "redirect:/";

//이전 요청이 있으면 그 페이지로 이동 

}else {

return "redirect:/"+dest.toString();

}

**게시물 삭제

1.detail.jsp 파일에 삭제를 위한 UI 와 이벤트를 작성

=>jquery ui의 dialog 기능을 이용

1)삭제 버튼(deletebtn)을 눌렀을 때 수행되는 코드가 있으면 제거


2)파일의 하단에 대화상자로 사용할 내용 만들기

<c:if test="${user.email == vo.email}">

<link rel="stylesheet"

href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


<div id="dialog-confirm" title="정말로 삭제?" style="display: none">

<p>삭제하시면 복구할 수 없습니다. 그래도 삭제하실 건가요?</p>

</div>


<script>

//삭제 버튼을 눌렀을 때 처리

document.getElementById("deletebtn").addEventListener(

"click", function(){

$("#dialog-confirm").dialog({

      resizable: false,

      height: "auto",

      width: 400,

      modal: true,

      buttons: {

        "삭제": function() {

          $(this).dialog("close");

          location.href="delete?bno=${vo.bno}";

        },

        "취소": function() {

          $(this).dialog("close");

        }

      }

    });

});

</script>

</c:if>


2.board.xml 파일에 게시글을 삭제하는 SQL을 작성

<!-- 게시글 삭제를 위한 SQL -->

<delete id="delete" parameterType="java.lang.Integer">

delete from springboard

where bno=#{bno}

</delete>


3.BoardDao 클래스에 게시글을 삭제하는 메소드를 생성

//글번호에 해당하는 데이터를 삭제를 하는 메소드

public void delete(int bno) {

sqlSession.delete("board.delete", bno);

}


4.BoardService 인터페이스에 게시글을 삭제하는 메소드를 선언

//게시글 삭제를 처리해 줄 메소드를 선언

public void delete(HttpServletRequest request);


5.BoardServiceImpl 클래스에 게시글을 삭제하는 메소드를 구현

@Override

public void delete(HttpServletRequest request) {

//파라미터 읽기

String bno = request.getParameter("bno");

//Dao 메소드 호출

boardDao.delete(Integer.parseInt(bno));

}


6.Controller 에 게시물 삭제를 처리해주는 메소드 생성 


@RequestMapping(value = "board/delete", method = RequestMethod.GET)

public String delete(HttpServletRequest request, RedirectAttributes attr) {

boardService.delete(request);

attr.addFlashAttribute("msg", "삭제");

return "redirect:list";

}

















 게시글 수정 

상세보기를 작업할 때는 글번호를 가지고 이미 데이터를 찾아오는 방법이 있기 때문에 Service부터작업하면 됩니다.


1. BoardService 인터페이스에 게시글을 가져와서 수정보기에 사용할 메소드스를 선언 

//게시물 수정 보기를 위한 메소드 

public Board updateView(HttpServletRequest request);


2. BoardServiceImpl 클래스에 게시글을 가져와 수정보기에 사용할 메소드를 구현 


@Override

public Board updateView(HttpServletRequest request) {

String bno = request.getParameter("bno");

return boardDao.detail(Integer.parseInt(bno));}

3. BoardController 클래스에 게시글을 가져와서 수정보기 화면에 출력하는 메소드를 구현 

@RequestMapping(value = "board/update", method=RequestMethod.GET)

public String update(HttpServletRequest request ,Model model){

Board board = boardService.detail(request);

model.addAttribute("vo", board);

return "board/update";


}


4.Board디렉토리에 update.jsp 파일을 만들고 수정화면을 작성 

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

pageEncoding="UTF-8"%>

<%@include file="../include/header.jsp"%>

<section class="content">

<div class="box-header">

<h3 class="box-title">게시판 수정</h3>

</div>


<form role="form" method="post">

<!-- 데이터 수정을 할 때 기본키의 값이 있어야 해서 필요하고

작업이 끝나고 결과 페이지로 이동할 때

상세보기로 이동하려면 글번호가 필요합니다. -->

<input type="hidden" name="bno" value="${vo.bno}" />

<div class="box-body">

<div class="form-group">

<label>제목</label> <input type="text" name='title'

class="form-control" value="${vo.title}">

</div>

<div class="form-group">

<label>내용</label>

<textarea class="form-control" name="content" rows="5">${vo.content}</textarea>

</div>


<div class="form-group">

<label>작성자</label> <input type="text" name="nickname"

value="${user.nickname}" class="form-control" readonly="readonly">

</div>

</div>


<div class="box-footer">

<button type="submit" class="btn btn-primary">작성완료</button>

</div>

</form>

</section>

<%@include file="../include/footer.jsp"%>


5. board.xml 파일에 게시글 수정을 위한 SQL 작성 

<update id="update" parameterType="Board">


update springboard

set

title=#{title}, content=#{content}, regdate=sysdate

where bno=#{bno}


</update>

6. BoardDao 클래스에 게시글 수정을 위한 메소드 생성 

public void update(Board board) {

sqlSession.update("board.update",board);

}


7.게시글 수정을 처리해 줄 메소드를 선언 

public void update(HttpServletRequest request);


8.BoardServiceImpl 클래스에 게시글 수정을 처리해 줄 메소드를 구현 

@Override

public void update(HttpServletRequest request) {

// 파라미터 읽기

// 파라미터를 이용해서 수행할 작업이 있으면 수행

String title = request.getParameter("title");

String content = request.getParameter("content");

String ip = request.getRemoteAddr();

String bno = request.getParameter("bno");


// Dao 메소드를 호출

Board board = new Board();

board.setIp(ip);

board.setContent(content);

board.setTitle(title);

board.setBno(Integer.parseInt(bno));

boardDao.update(board);


}


9. BoardController에서 게시물 수정을 처리해줄 메소드  

@RequestMapping(value = "board/update", method=RequestMethod.POST)

public String update(HttpServletRequest request , RedirectAttributes attr){

boardService.update(request);

attr.addFlashAttribute("msg","게시글 수정");

return "redirect:list";


}

+ Recent posts