본문 바로가기

웹 - 서버

웹 - 수정

*) 수정은 파일 수정(UploadAction)과 나머지 인자값 수정(ModifyAction)으로 나눠서 해야한다.

 

수정폼.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>
<!-- bootstrap 3 -->
<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.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- SweetAlert2사용설정  -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style type="text/css">
  #box{
      width: 600px;
      margin: auto;
      margin-top: 50px;  
  }

  textarea {
	  width: 100%;
	  resize: none;
  }
  
  input[type='button']{
      width: 100px;
  }
  
  img{
      width: 200px;
  }

</style>


<script type="text/javascript">
   
   function send(f){
	   
	   //입력값 체크....
	   
	   var p_title = f.p_title.value.trim();
	   var p_content = f.p_content.value.trim();
	   
	   if(p_title==''){
		   alert('제목을 입력하세요');
		   f.p_title.value='';
		   f.p_title.focus();
		   return;
	   }
	   
	   
	   if(p_content==''){
		   alert('내용을 입력하세요');
		   f.p_content.value='';
		   f.p_content.focus();
		   return;
	   }
	   
	   
	   f.action = "modify.do"; //PhotoModifyAction
	   f.submit();
	   
   }
 
// ----------------- Ajax이용한 이미지 수정 ------------------------------------   
   function ajaxFileUpload() {
       // 업로드 버튼이 클릭되면 파일 찾기 창을 띄운다.
       $("#ajaxFile").click();
   }

   function ajaxFileChange() {
       // 파일이 선택되면 업로드를 진행한다.
       photo_upload();
   }


   
   function photo_upload() {

	   //파일선택->취소시
	   if( $("#ajaxFile")[0].files[0]==undefined)return;
	   
	   	   
	   var form = $("#ajaxForm")[0];
       var formData = new FormData(form);
       formData.append("p_idx", '${ vo.p_idx }');			// p_dix=5
       formData.append("photo", $("#ajaxFile")[0].files[0]);// photo=a.png

       $.ajax({
             url : "photo_upload.do", //PhotoUploadAction // 사진 수정
             type : "POST",
             data : formData,
             processData : false,
             contentType : false,
             dataType : 'json',
             success:function(res_data) {
            	 //res_data = {"p_filename":"aaa.jpb"}
                 
            	 //location.href=''; //자신의 페이지를 리로드(refresh)
            	 //           prop
            	 $("#my_img").attr("src","../images/" + res_data.p_filename);
            	 
             },
             error : function(err){
            	 alert(err.responseText);
             }
       });

   }
</script>



</head>
<body>

<!--화일업로드용 폼  -->
<form enctype="multipart/form-data" id="ajaxForm" method="post">
    <input id="ajaxFile" type="file"  style="display:none;"  onChange="ajaxFileChange();" >
</form>

  
  
  
<form>

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

  <div id="box">
        <div class="panel panel-primary">
	      <div class="panel-heading"><h4>수정화면</h4></div>
	      <div class="panel-body">
	          <table class="table  table-striped">
	               <tr>
	                   <td colspan="2" align="center">
	                       <img src="../images/${ vo.p_filename }" id="my_img">
	                       <br>
	                       <input  class="btn  btn-info" type="button"  value="이미지편집"  onclick="ajaxFileUpload();">
	                   </td>
	               </tr>
	          
	               <tr>
	                  <th>제목</th>
	                  <td><input name="p_title"  value="${ vo.p_title }"></td>
	               </tr>
	               
	               <tr>
	                  <th>내용</th>
	                  <td>
	                      <textarea  name="p_content"  rows="5" cols="">${ vo.p_content }</textarea>
	                  </td>
	               </tr>
	               
	               <tr>
	                   <td colspan="2" align="center">
	                       <input class="btn  btn-primary" type="button"  value="수정하기" 
	                              onclick="send(this.form);">
	                       <input class="btn  btn-success" type="button"  value="메인으로" 
	                              onclick="location.href='list.do'">
	                   </td>
	               </tr>
	               
	          </table>
	      </div>
	    </div>
  </div>
</form>


</body>
</html>

 

이미지 수정 (UploadAction)

// 이미지 수정용 서블릿
@WebServlet("/photo/photo_upload.do")
public class PhotoUploadAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// /photo/photo_upload.do?p_idx=5&photo=aaa.jpg
		// 파일 업로드 처리
			// String saveDir = "F:\\dev\\upload"; // upload 위치
				String webPath  = "/images/"; // 웹(URL)경로
				
				// 현재 웹어플리케이션의 전역관리객체(상대경로->절대경로)
				ServletContext application = request.getServletContext();
				//				  웹(상대)경로 -> 절대경로 구하기 (과정 꼭 필요!!!)
				String saveDir = application.getRealPath(webPath); 
				System.out.println(saveDir);
				int	   maxSize = 1024 * 1024 * 100; // 최대업로드크기 (100MB)
				// FileUpload객체 => MultipartRequest
				MultipartRequest mr = new MultipartRequest(
												request, 	 // request 위임
												saveDir,     // 저장위치
												maxSize, 	 // 최대업로드크기
												"utf-8", 	 // 수신인코딩
												// 화일이름이 동일할 경우 다른 이름으로 변경시키는 객체
												new DefaultFileRenamePolicy() 
												);	
				// 업로드화일명을 얻어온다
				String p_filename = "no_file";
				// mr에 의해서 업로드된 화일정보 얻어온다 // 
				File f = mr.getFile("photo");
				
				if(f!=null) { //업로드화일 존재하면
					
					p_filename = f.getName();
				}
				
				int p_idx = Integer.parseInt(mr.getParameter("p_idx"));
				
				// p_idx에 저장된 이전파일은 삭제
				PhotoVo vo = PhotoDao.getInstance().selectOne(p_idx);
				File delFile = new File(saveDir, vo.getP_filename());
				delFile.delete();
				
				//update된 파일이름 수정
				vo.setP_filename(p_filename);
				int res = PhotoDao.getInstance().update_filename(vo);
				
				// 응답처리
				response.setContentType("application/json; charset=utf-8;");
				//{"p_filename":"a.jpg"}
				String json = String.format("{\"p_filename\":\"%s\"}", p_filename);
				
				response.getWriter().print(json);			
	}

}

)Dao 이미지 수정용 메서드 추가

public int update_filename(PhotoVo vo) {
		// TODO Auto-generated method stub

		int res = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		//										  1             2
		String sql = "update photo set p_filename=? where p_idx=?";

		try {
			//1.Connection 얻어오기
			conn = DBService.getInstance().getConnection();

			//2.PreparedStatement
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter index 채우기
			pstmt.setString(1, vo.getP_filename());
			pstmt.setInt(2, vo.getP_idx());
			//4.DB update
			res = pstmt.executeUpdate();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();

		} finally {

			//마무리 작업(열린역순으로 닫기)
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return res;

	}//end:update()

 

)인자값 수정 (ModifyAction)

@WebServlet("/photo/modify.do")
public class PhotoModifyAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		int p_idx = Integer.parseInt(request.getParameter("p_idx"));
		String p_title = request.getParameter("p_title");
		String p_content = request.getParameter("p_content");
		
		PhotoVo vo = new PhotoVo(p_idx,p_title, p_content);
		
		int res = PhotoDao.getInstance().update(vo);
		
		response.sendRedirect("list.do");

	}

}

-> dao에 update() 추가