JSP/Servlet – 데이터베이스에 데이터 입력하기
맨 처음 다음의 sql 문으로 테이블을 만듭니다.
create table userinfo (
name varchar(10) not null,
id varchar(12) not null,
password varchar(12) not null,
primary key(id)
);
위와 같이 예제는 1개의 HTML파일과 2개의 JSP파일로 구성됩니다.
SubscriptionForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<FORM ACTION=Subscription.jsp METHOD=POST>
이름 : <INPUT TYPE=TEXT NAME=name SIZE=10><BR>
아이디: <INPUT TYPE=TEXT NAME=id SIZE=8><BR>
패스워드 : <INPUT TYPE=PASSWORD NAME=password SIZE=8><BR>
<INPUT TYPE=SUBMIT VALUE='확인'>
<INPUT TYPE=RESET VALUE='취소'>
</FORM>
</body>
</html>
Subscription.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@page import="java.sql.*" %>
<%
//앞에서 입력한 값을 가져옵니다
String name = request.getParameter("name");
String id = request.getParameter("id");
String password = request.getParameter("password");
if(name == null || id == null || password == null)
throw new Exception("데이터를 입력하세요");
Connection conn = null;
Statement stmt = null;
try{
//JDBC 드라이버 이름 설정
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();//Statement 객체 가져옴
//쿼리문을 만들어줌
String command = String.format("insert into userinfo" +
"(name, id, password) values('%s', '%s', '%s');", name, id, password);
int rowNum = stmt.executeUpdate(command);//쿼리문 실행
if(rowNum < 1)
throw new Exception("데이터를 DB에 입력할 수 없음");
}
finally{
try{
stmt.close();
}
catch(Exception ignored){
}
try{
conn.close();
}catch(Exception ignored){
}
}
//다음 페이지 실행
response.sendRedirect("SubscriptionResult.jsp");
%>
<!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>
SubscriptionResult.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>
가입완료
</body>
</html>
실행 화면
데이터를 넣습니다.
확인 버튼을 누르면 다음과 같이 가입완료 창이 뜹니다.
select 문으로 확인해보면 데이터가 제대로 들어갔음을 알 수 있습니다.
'프로그래밍 > JSP Servlet' 카테고리의 다른 글
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.17 |
JSP/Servlet – 데이터베이스에서 값 읽어오기 (0) | 2016.04.10 |
JSP/Servlet – 응답 메시지의 본체 내용을 변형하는 래퍼 클래스 만들기 (0) | 2016.04.07 |
JSP/Servlet – 응답 래퍼 클래스를 작성하는 방법 (0) | 2016.04.04 |
JSP/Servlet – 요청 래퍼 클래스 작성하기 (0) | 2016.03.21 |