Filter

(Interface)
JSP같은 경우 POST 방식으로 넘기경우 Encoding 처리를 항상 해줘야한다.
이것을 Filter을 통해서 해결해준다. - 로그인 체크도 가능

모든 요청이 들어올때마다 호출

package common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class EncodingFilter
 */
@WebFilter("/*")
public class EncodingFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
	}
	//사전 처리나 사후 처리할 일이 있으면 doFilter()메소드 안에서 구현한다.
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		//post방식일 때의 한글 처리를 여기서 사전에 처리하도록 하자
		//System.out.println("EncodingFilter doFilter()호출됨");
		req.setCharacterEncoding("UTF-8");
		chain.doFilter(req, res);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}




게시글 수정
1) 파일을 업로드 하는 경우
  1-1 예전에 업로드한 파일이 있을 경우 => 예전 파일 삭제 처리후 새로운 파일 업로드 처리
  1-2 예전에 업로드한 파일이 없는 경우 => 새로운 파일 업로드처리
2) 업로드 하지 않는 경우 => 수정 처리

package board.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import board.model.BoardDAO;
import board.model.BoardVO;
import common.base.CommonUtil;
import common.controller.AbstractAction;

public class BoardEditEndAction extends AbstractAction {

	@Override
	public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
		//0. 파일 업로드 처리
		ServletContext app = req.getServletContext();
		String upDir=app.getRealPath("/Upload");
		System.out.println(upDir);
		MultipartRequest mr =null;
		try {
			mr=new MultipartRequest(req,upDir,10*1024*1024,"UTF-8",new DefaultFileRenamePolicy());
		}catch(IOException e){//multipart/form-data가 아니거나 업로드 용량 초과시 발생
			e.printStackTrace();
			throw new ServletException(e);
		}
		//1. 글번호, 작성자, 글내용, 비밀번호, 첨부파일명 파라미터 값 받기
		String idx = mr.getParameter("idx");
		String name = mr.getParameter("name");
		String content = mr.getParameter("content");
		String pwd =mr.getParameter("pwd");
		String subject = mr.getParameter("subject");
		//String filename = mr.getParameter("filename");
		String filename = mr.getFilesystemName("filename");//첨부파일
		String originFilename = mr.getOriginalFileName("filename");//원본파일명
		String old_filename=mr.getParameter("old_filename");
		if(filename!=null) {
			//새로 첨부파일이 있는 경우
			if(!old_filename.trim().isEmpty()) {
				//예전에 첨부한 파일이 있을 경우 ==> 예전 파일 삭제 처리
				File oldFile = new File(upDir+File.separator+old_filename);
				if(oldFile.exists()) {
					oldFile.delete(); //삭제 처리
				}
			}
		}
		long filesize = 0;
		if(filename!=null) {
			File file = mr.getFile("filename");
			filesize=file.length();
		}
		//2. 유효성체크(글번호,작성자,비번)
		if(idx==null||name==null||pwd==null||idx.trim().isEmpty()||name.trim().isEmpty()||pwd.trim().isEmpty()) {
			this.setViewPage("list.do");
			this.setRedirect(true);
			System.out.println("??");
			return;
		}
		//3. BoardVO에 담아주기
		int idx_int=Integer.parseInt(idx.trim());
		BoardVO board = new BoardVO(idx_int,name,subject,content,pwd,null,0,filename,originFilename,filesize);
		//4. BoardDAO생성해서 updateBoard(board) 반환형 int
		BoardDAO dao = new BoardDAO();
		int n = dao.updateBoard(board);
		String msg = (n>0) ? "성공":"실패";
		String loc = (n>0) ? "list.do":"javascript:history.back()";
		//5. 실행결과 메시지 처리
		this.setViewPage(CommonUtil.addMsgLoc(req, msg, loc));
		this.setRedirect(false);
		
	}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
ajax 삭제, 수정 요청

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
response.setHeader("Pragma","No-cache"); //HTTP 1.0 
response.setDateHeader ("Expires", 0); 
   response.setHeader("Cache-Control","no-cache");
%>    
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BOOK</title>
<!-- CDN 참조-------------------------------------- -->
<link rel="stylesheet"
   href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
   src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- --------------------------------------------- -->
<style type="text/css">
</style>
<script type="text/javascript">
   $(function(){
      getAllBook();
   })
   var goDel=function(visbn){
      //alert(visbn);
      $.ajax({
         type:'GET',
         url:'bookDel.jsp?isbn='+visbn,
         dataType:'xml',
         cache:false,
         success:function(res){
            //alert(res);
            var str=$(res).find('result').text();
            //alert(str);
            if(parseInt(str)>0){
               getAllBook();
            }else{
               alert('삭제 실패');
            }
         },
         error:function(err){
            //alert('error: '+err.status);
         }
      });
   }
   var goEdit=function(visbn){
      //alert(visbn);
      $.ajax({
      type:'POST',
      url:'bookInfo.jsp',
      data:"isbn="+visbn, //요청데이터, post방식일 경우 data속성 값으로 데이터를 넘긴다.
      dataType:'xml',
      success:function(res){
         //alert(res);
         //응답 데이터 추출하기(isbn,title,price,publish,pubDate,bimage)
         var visbn=$(res).find('isbn').text();
         var vtitle=$(res).find('title').text();
         var vprice=$(res).find('price').text();
         var vpublish=$(res).find('publish').text();
         var vpubDate=$(res).find('pubDate').text();
         var vbimage=$(res).find('bimage').text();
         $('#isbn').val(visbn);
         $('#title').val(vtitle);
         $('#price').val(vprice);
         $('#publish').val(vpublish);
         $('#published').val(vpubDate);
         var str="<img style='width:80%'; 'margin:auto' src='../images/"+vbimage+"' class='img img-thumbnail img-responsive'>";
         $('#bimage').html(str); 
      },
      error:function(err){
         alert('error: '+err.status);
      }
      })
   }//-----------------------
   
   var goEditEnd=function(){
      //alert('a');
      //폼객체 serialize() 함수를 이용하여 파라미터 데이터를 만든다.
      var paramData=$('#editF').serialize();
      alert(paramData);
   }//------------------------
   
   var getAllBook= function(){
      $.ajax({
         type:'get',
         url:'bookAll.jsp',
         dataType:'html',//text, html, xml, json ...
         cache: false,
         success:function(res){
            $("#book_data").html(res);
         },
         error:function(err){
            alert('error: '+err.status);
         }
      })
   }
</script>
</head>
<!--onload시 출판사 목록 가져오기  -->
<body onload="getPublish()">
   <div class="container">
   <h2 id="msg">서적 정보 페이지</h2>
<form name="findF" id="findF" role="form"
 action="" method="POST">
<div class="form-group">
<label for="sel" class="control-label col-sm-2">출판사</label>
<span id="sel"></span><span id="sel2"></span>
</div>
<p>
<div class='form-group'>
   <label for="books" class="control-label col-sm-2" id="msg1">도서검색</label>
   <div class="col-sm-6">
   <input type="text" name="books" id="books"
    onkeyup="autoComp(this.value)"
    class="form-control" >
    <!-- ---------------------------- -->
    <div id="lst1" class="listbox"
     style="display:none">
       <div id="lst2" class="blist"
        style="display:none">
       </div>
    </div>
    <!-- ---------------------------- -->
   </div>
</div>
</form>
<div>
 
 <button type="button"
  onclick="getBook()"
  class="btn btn-primary">검색</button>
 
 <button type="button" onclick="getAllBook()" class="btn btn-success">모두보기</button>
 <button type="button" id="openBtn"
  class="btn btn-info">OPEN API에서 검색</button><br><br>
</div>
<div id="localBook">

<table class="table table-bordered" border="1">
   <tr class="info">
      <td style="width:20%;">서명</td>
      <td style="width:20%;">출판사</td>
      <td style="width:20%;">가격</td>
      <td style="width:20%;">출판일</td>
      <td style="width:20%;">편집</td>
   </tr>
</table>
<!-- ----------------------- -->
<div id="book_data"></div>
<!-- ----------------------- -->
<form id="editF" name="editF">
<table id="book_info" class="table table-hover" border="2">
   <tr>
      <td width="20%">ISBN코드</td>
      <td>
      <input type="text" name="isbn" id="isbn"
      class="form-control" readonly>
      </td>
      <td rowspan="6" width="30%" id="bimage" class="text-center"></td>
   </tr>
   <tr>
      <td>서명</td>
      <td>
      <input type="text" name="title" id="title"
      class="form-control">
      </td>
      
   </tr>
   <tr>
      
      <td>출판사</td>
      <td>
      <input type="text" name="publish" id="publish"
      class="form-control">
      </td>
      
   
   </tr>
   <tr>
   
      <td>가격</td>
      <td>
      <input type="text" name="price" id="price"
      class="form-control">
      </td>
      
   </tr>
   <tr>
   
      <td>출판일</td>
      <td>
      <input type="text" name="published"
       id="published"  disabled
      class="form-control">
      </td>
      
   </tr>
   <tr>
      <td colspan="2">
      <button type="button"
      onclick="goEditEnd()" class="btn btn-danger">수정</button></td>
   </tr>
</table>
</form>
   </div>
</div><!-- #localBook end -->

<!-- ------------------------------- -->
<div id="openApiBook">

</div>
   
</body>
</html>

<!-- https://apis.daum.net/search/book -->
<!-- 53c73f32f6c4150ca5aa184ba6250d8e -->

<!-- https://apis.daum.net/search/book?apikey=53c73f32f6c4150ca5aa184ba6250d8e&q=다음카카오&output=json -->

bookInfo.jsp

<%@page import="ajax.book.BookDTO"%>
<%@ page language="java" contentType="text/xml; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="bDao" class="ajax.book.BookDAO" scope="session"/>
<%
	String isbn=request.getParameter("isbn");
	ajax.book.BookDTO book = bDao.getBookInfo(isbn);
	request.setAttribute("book", book);
%>
<book>
	<isbn>${book.isbn}</isbn>
	<title>${book.title}</title>
	<price>${book.price}</price>
	<publish>${book.publish}</publish>
	<pubDate>${book.published}</pubDate>
	<bimage>${book.bimage}</bimage>
</book>

 

+ Recent posts