JAVA
240111 홈페이지 만들기
코딩하는딩굴
2024. 1. 11. 10:01
기존에 만들었던 홈페이지를 다시 만들어보면서
기능은 조금씩 다르게 구현하는 중
삭제, 수정 등 jsp 에서 바로 사용하던 것을
Servlet 으로만 사용해보기, Servlet 에서도 if 를 사용하여 에러 제거해보기
public class Util {
// String 을 int 로 변경
public static int str2Int(String str) {
StringBuffer sb = new StringBuffer();
// String s = "";
for(int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
return Integer.parseInt(sb.toString());
}
public static int str2Int2(String str) {
String s = str.replaceAll("[^0-9]", "");
return Integer.valueOf(s);
}
// String 값이 들어오면 int 값을 체크하는 메소드
public static boolean intCheck(String str) {
try {
Integer.parseInt(str);
return true;
} catch (Exception e) {
return false;
}
}
// 구형
public static boolean intCheck2(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
글 수정하는 update.jsp 의 일부
<form action="./update" method="post">
<input id="title" type="text" name="title" value="${update.title }">
<textarea id="summernote" name="content">${update.content }</textarea>
<button type="submit">저장</button>
<button type="reset">초기화</button>
<input type="hidden" name="no" value="${update.no }">
</form>
post 형식으로 보내서 update Servlet 에서는 getpost 에 작성해야 함
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
if ((request.getParameter("title") != null) && (request.getParameter("content") != null)
&& Util.intCheck(request.getParameter("no"))) {
String title = request.getParameter("title");
String content = request.getParameter("content");
int no = Util.str2Int(request.getParameter("no"));
BoardDAO dao = new BoardDAO();
int result = dao.update(title, content, no);
if (result != 0) {
response.sendRedirect("./detail?no=" + no);
} else {
response.sendRedirect("./error");
}
} else {
response.sendRedirect("./error");
}
}
나는 글 수정을 완료하면 글 목록이 아닌 글 상세보기로 들어가고 싶어 Redirect 를 따로 했음
왜인지는 모르겠지만 Encoding 을 if 안에 넣으면 글씨가 깨짐
작성하면서 물론 DAO 도 작성
public int update(String title, String content, int no) {
Connection conn = DBConnection.getInstance().getConn();
PreparedStatement pstmt = null;
String sql = "UPDATE board SET board_title=?, board_content=? WHERE board_no=?";
int result = 0;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.setInt(3, no);
result = pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("DAO - update 오류");
} finally {
close(conn, pstmt, null);
}
return result;
}
계속 오류가 발생하여 어디서 발생하는 지 체크하였는데
맨 처음에 board_no 값을 받지 않아 발생한 오류였음
JSP 페이지에서 꼭 no 값을 form 안에 넣어 같이 보내줘야 함 -> 실수 해봤으니 다음에는 덜 할듯