JSP/Servlet – 데이터베이스에 있는 데이터 수정하기
2016/04/10 - [프로그래밍/JSP/Servlet] - JSP/Servlet – 데이터베이스에 데이터 입력하기
2016/04/10 - [프로그래밍/JSP/Servlet] - JSP/Servlet – 데이터베이스에서 값 읽어오기
이전 예제에서 만든 데이터베이스를 이용해서 값을 수정해봅시다.
바뀐 점은 기존의 쿼리문에서 insert 문 대신 update 문을 사용한 다는 점만 다릅니다.
위와 같이 예제를 구성합니다.
InitForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<H4>상품 코드를 입력하세요.</H4>
<FORM ACTION=Reader.jsp METHOD=GET>
상품 코드 : <INPUT TYPE=TEXT NAME=code SIZE=5>
<INPUT TYPE=SUBMIT VALUE='확인'>
</FORM>
</body>
</html>
Reader.jsp
<%@page import="java.io.UnsupportedEncodingException"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR" errorPage="DBError.jsp" %>
<%@ page import="java.sql.*" %>
<%
String code = request.getParameter("code");//code 값을 가져옴
if(code == null)
throw new Exception("상품코드를 입력하세요");
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
//데이터 베이스 연결
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webdb", "root", "apmsetup");
if(conn == null)
throw new Exception("연결 실패");
stmt = conn.createStatement();
//코드값을 가지고 쿼리문을 만들어서 실행
ResultSet rs = stmt.executeQuery(
"select * from goodsinfo where code = '" + code + "';");
if(!rs.next())
throw new Exception("상품코드(" + code + ") 에 해당하는 자료 없습니다");
//값을 가져와서 애트리뷰트에 저장함
String title = rs.getString("title");
String writer = rs.getString("writer");
int price = rs.getInt("price");
request.setAttribute("CODE", code);
request.setAttribute("TITLE", toUnicode(title));
request.setAttribute("WRITER", toUnicode(writer));
request.setAttribute("PRICE", new Integer(price));
}
finally{
try{
stmt.close();
}
catch(Exception ignored){
}
try{
conn.close();
}
catch(Exception ignored){
}
}
//결과를 EditForm으로 보내줌
RequestDispatcher dispatcher = request.getRequestDispatcher("EditForm.jsp");
dispatcher.forward(request, response);
%>
<%!
private String toUnicode(String str){//ISO-8859-1문자열을 Unicode 문자열로 바꾸는 메소드
try{
byte[] b = str.getBytes("ISO-8859-1");
return new String(b);
}
catch(UnsupportedEncodingException uee){
System.out.println(uee.getMessage());
return null;
}
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
EditForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<H4>상품 정보를 수정하세요</H4>
<!-- 데이터베이스에서 가져온 값을 뿌려주는 부분 -->
<FORM ACTION=Updater.jsp METHOD=POST>
코드 : <INPUT TYPE=TEXT NAME=code SIZE=5
VALUE='${CODE }' READONLY=TRUE><BR>
제목 : <INPUT TYPE=TEXT NAME=title SIZE=50
VALUE='${TITLE }'> <BR>
저자 : <INPUT TYPE=TEXT NAME=writer SIZE=20
VALUE='${WRITER }'> <BR>
가격 : <INPUT TYPE=TEXT NAME=price SIZE=8
VALUE='${PRICE }'>원 <BR>
<INPUT TYPE=SUBMIT VALUE='수정'>
</FORM>
</body>
</html>
Updater.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@page import="java.sql.*" %>
<%
request.setCharacterEncoding("euc-kr");
//EditForm에서 입력된 값을 가져옴
String code = request.getParameter("code");
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String price = request.getParameter("price");
if(code == null || title == null || writer == null || price == null)
throw new Exception("모든 데이터를 입력해주세요.");
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
//데이터 베이스 연결
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webdb", "root", "apmsetup");
if(conn == null)
throw new Exception("데이터베이스 연결 실패");
stmt = conn.createStatement();
//아래와 같이 쿼리문을 만듬
String command = String.format("update goodsinfo set " +
"title := '%s', writer := '%s', " +
"price := '%s' where code = '%s';",
title, writer, price, code);
int rowNum = stmt.executeUpdate(command);
if(rowNum < 1)
throw new Exception("입력 실패");
}
finally{
try{
stmt.close();
}
catch(Exception ignored){
}
try{
conn.close();
}catch(Exception ignored){
}
//UpdateResult.jsp를 실행함 이때 code 값도 get으로 넘겨줌
response.sendRedirect("UpdateResult.jsp?code=" + code);
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
UpdateResult.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<H4>수정 완료</H4>
수정된 정보 조회시 아래를 클릭하세요<BR><BR>
<A HREF=Reader.jsp?code=${param.code }>상품 정보 조회</A>
</body>
</html>
실행 화면
첫 화면입니다. 상품 코드를 입력하면
상품 정보가 조회되면 수정창이 나옵니다.
아래와 같이 수정완료가 됩니다.
상품 정보 조회 클릭시 다음과 같이 가격이 30000원으로 수정된 것을 알 수 있습니다.
'프로그래밍 > JSP Servlet' 카테고리의 다른 글
[펌자료] 프로젝트 복사 후, "Multiple Context have a path..."에러 해결하기. (0) | 2016.05.05 |
---|---|
Eclipse의 Dynamic Project 시 Context path 를 수정하고 싶을 때 (0) | 2016.05.05 |
JSP/Servlet – 모델2로 웹애플리케이션 설계하기 (7) | 2016.04.29 |
JSP/Servlet – 모델 1로 웹애플리케이션 설계하기 (0) | 2016.04.21 |
JSP/Servlet – 데이터베이스에 데이터 입력하기 (0) | 2016.04.10 |
JSP/Servlet – 데이터베이스에서 값 읽어오기 (0) | 2016.04.10 |
JSP/Servlet – 응답 메시지의 본체 내용을 변형하는 래퍼 클래스 만들기 (0) | 2016.04.07 |
JSP/Servlet – 응답 래퍼 클래스를 작성하는 방법 (0) | 2016.04.04 |