4. JSP - Servlet 예제
Servlet 을 이용하여 아주 간단한 회원가입(신규입력), 회원목록 보기 예를 한다.
Servlet작성 시 service메소드(get,post 모두 가능) 또는 doGet(get방식), doPost(Post방식) 사용가능.
0. web.xml
1. main.html 초기화면(회원가입, 회원목록 링크)
2. insert.html 입력 화면
3. InsertServlet.java 입력처리 Servlet
4. ListServlet.java 조회 Servlet
5. DeleteServlet.java 삭제처리 Servlet
6. UpdateServlet 변경대상 상세 조회 Servlet
7. UpdateOkServlet 수정 처리 Servlet
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>day02_servlet01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>insert</servlet-name>
<servlet-class>test.servlet.InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>insert</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>test.servlet.ListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/list.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>delete</servlet-name>
<servlet-class>test.servlet.DeleteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>delete</servlet-name>
<url-pattern>/delete.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>update</servlet-name>
<servlet-class>test.servlet.UpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>update</servlet-name>
<url-pattern>/update.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>updateok</servlet-name>
<servlet-class>test.servlet.UpdateOkServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>updateok</servlet-name>
<url-pattern>/updateok.do</url-pattern>
</servlet-mapping>
</web-app>
1. main.html
; 초기화면(회원가입, 회원목록 링크)
<!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>
<ul>
<li><a href="insert.html">회원가입</a></li>
<li><a href="list.do">회원목록</a></li>
</ul>
</body>
</html>
2. insert.html 입력 화면
<!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>
<style type="text/css">
#regbox{
width : 300px;
}
#regbox label{
display : block;
width: 100px;
float : left;
}
</style>
</head>
<body>
<form method="get" action="abc">
<fieldset id="regbox">
<legend>회원가입</legend>
<label for="id">아이디</label>
<input type="text" name="id"/><br/>
<label for="pwd">비밀번호</label>
<input type="text" name="pwd"/><br/>
<label for="email">이메일</label>
<input type="text" name="email"/><br/>
<label for="phone">전화번호</label>
<input type="text" name="phone"/><br/>
<input type="submit" value="가입">
<input type="reset" value="취소"/>
</fieldset>
</form>
</body>
</html>
3. InsertServlet.java
; 입력처리 Servlet
package test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InsertServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1. 파라미터로 전송된 값을 얻어오기.
request.setCharacterEncoding("euc-kr");
String id = request.getParameter("id");
String pwd= request.getParameter("pwd");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
int n=0;
PreparedStatement pstmt = null;
Connection con = null;
try{
// 2. 전송된 값을 db에 저장.
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(url, "scott", "tiger");
String sql = "insert into members values( ?,?,?,?, sysdate )";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
pstmt.setString(3, email);
pstmt.setString(4, phone);
//sql구문 실행하기
n=pstmt.executeUpdate();
}catch(ClassNotFoundException ce){
System.out.println(ce.getMessage());
}catch(SQLException se){
System.out.println(se.getMessage());
}finally{
try{
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
}catch(SQLException se){
System.out.println(se.getMessage());
}
}
// 3. 사용자(클라이언트)에 결과를 응답하기.
response.setContentType("text/html;charset=euc-kr");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head></head>");
pw.println("<body>");
if(n>0){
pw.println( id + "님! 성공적으로 가입되었습니다.<br/>");
}else{
pw.println("오류로 인해 가입에 실패했습니다.<br/>");
pw.println("<a href='javascript:history.go(-1)'>이전페이지로 가기</a>");
}
pw.println("</body>");
pw.println("</html>");
}
}
4. ListServlet.java
; 조회 Servlet
; 목록보기를 클릭하면
package test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest resquest, HttpServletResponse response)
throws ServletException, IOException {
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs = null;
response.setContentType("text/html;charset=euc-kr");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head></head>");
pw.println("<body>");
try{
Class.forName("oracle.jdbc.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(url, "scott", "tiger");
String sql = "select * from members";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
pw.println("<div>");
pw.println("<table border='1' width='1200'>");
pw.println("<tr>");
pw.println("<td>아이디</td>");
pw.println("<td>비밀번호</td>");
pw.println("<td>이메일</td>");
pw.println("<td>전화번호</td>");
pw.println("<td>등록일</td>");
pw.println("<td>삭제</td>");
pw.println("<td>수정</td>");
pw.println("</tr>");
while(rs.next()){
String id = rs.getString("id");
String pwd = rs.getString("pwd");
String email = rs.getString("email");
String phone = rs.getString("phone");
Timestamp regdate = rs.getTimestamp("regdate");
pw.println("<tr>");
pw.println("<td>" + id + "</td>");
pw.println("<td>" + pwd + "</td>");
pw.println("<td>" + email + "</td>");
pw.println("<td>" + phone + "</td>");
pw.println("<td>" + regdate + "</td>");
pw.println("<td><a href='delete.do?id=" + id + "'>삭제</a></td>");
pw.println("<td><a href='update.do?id=" + id + "'>수정</a></td>");
pw.println("</tr>");
}
pw.println("</table>");
pw.println("</div>");
pw.println("<a href='main.html'>메인페이지로 이동</a>");
}catch(ClassNotFoundException ce){
System.out.println(ce.getMessage());
}catch(SQLException se){
System.out.println(se.getMessage());
}finally{
try{
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
}catch(SQLException se){
System.out.println(se.getMessage());
}
}
pw.println("</body>");
pw.println("</html>");
}
}
5. DeleteServlet.java
; 삭제처리 Servlet
; 삭제링크를 클릭하면
package test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DeleteServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
PreparedStatement pstmt=null;
int n=0;
request.setCharacterEncoding("euc-kr");
String id=request.getParameter("id");
response.setContentType("text/html;charset=euc-kr");
PrintWriter pw = response.getWriter();
try{
Class.forName("oracle.jdbc.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
String user="scott";
String password="tiger";
con = DriverManager.getConnection(url, user, password);
String sql = "delete from members where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
n= pstmt.executeUpdate();
}catch(ClassNotFoundException ce){
System.out.println(ce.getMessage());
}catch(SQLException se){
System.out.println(se.getMessage());
}finally{
try{
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
}catch(SQLException se){
System.out.println(se.getMessage());
}
}
if(n>0){
response.sendRedirect("list.do");
}else{
pw.println("<html>");
pw.println("<head></head>");
pw.println("<body>");
pw.println("회원삭제에 실패했습니다. ");
pw.println("<a href='javascript:history.go(-1)'>이전페이지로 가기</a>");
pw.println("</body>");
pw.println("</html>");
pw.close();
}
}
}
6. UpdateServlet.java
; 변경대상 상세 조회 Servlet
package test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 1. parameter로 전송된 id얻기.
String id=req.getParameter("id");
// 2. id에 해당하는 정보를 db에서 조회해서 출력.
resp.setContentType("text/html;charset=euc-kr");
PrintWriter pw = resp.getWriter();
pw.println("<html>");
pw.println("<head></head>");
pw.println("<body>");
PreparedStatement pstmt = null;
Connection con = null;
ResultSet rs=null;
try{
// 2. 전송된 값을 db에 저장.
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(url, "scott", "tiger");
String sql = "select * from members where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
//sql구문 실행하기
rs = pstmt.executeQuery();
rs.next();
String pwd = rs.getString("pwd");
String email=rs.getString("email");
String phone=rs.getString("phone");
pw.println("<form method='post' action='updateok.do'>");
pw.println("<input type='hidden' name='id' value='" + id + "'/>");
pw.println("아이디<input type='text' name='id' value='" + id + "' disabled='disabled'/><br/>");
pw.println("비밀번호<input type='text' name='pwd' value='" + pwd + "'/><br/>");
pw.println("email<input type='text' name='email' value='" + email + "'/><br/>");
pw.println("phone<input type='text' name='phone' value='" + phone + "'/><br/>");
pw.println("<input type='submit' value='저장'/><br/>");
pw.println("</form>");
}catch(ClassNotFoundException ce){
System.out.println(ce.getMessage());
}catch(SQLException se){
System.out.println(se.getMessage());
}finally{
try{
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
}catch(SQLException se){
System.out.println(se.getMessage());
}
}
pw.println("</body>");
pw.println("</html>");
pw.close();
}
}
7. UpdateOkServlet.java
;수정 처리 Servlet
package test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateOkServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("euc-kr");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
String email=req.getParameter("email");
String phone=req.getParameter("phone");
PreparedStatement pstmt = null;
Connection con = null;
int n=0;
try{
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(url, "scott", "tiger");
String sql = "update members set pwd=?,email=?,phone=? where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, pwd);
pstmt.setString(2, email);
pstmt.setString(3, phone);
pstmt.setString(4, id);
n = pstmt.executeUpdate();
if(n>0){
resp.sendRedirect("list.do");
}else{
PrintWriter pw = resp.getWriter();
pw.println("<html><head></head>");
pw.println("<body>실패</body>");
pw.println("</heal>");
pw.close();
}
}catch(ClassNotFoundException ce){
System.out.println(ce.getMessage());
}catch(SQLException se){
System.out.println(se.getMessage());
}
}
}