예제3: Model 2 DB연동 : ORACLE DB. MEMBER1 테이블 사용
dr.mini.action
DeleteAction
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import dr.mini.dao.MemberDao; public class DeleteAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); MemberDao manager = MemberDao.getInstance(); int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd")); if(check == 1){ manager.deleteMember(request.getParameter("id")); } request.setAttribute("check", check); return "/view/delete.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; public class DeleteFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); request.setAttribute("id", id); return "/view/deleteForm.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import java.sql.Timestamp; import dr.mini.dao.MemberDao; import dr.mini.domain.Member; public class InsertAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); Member member =new Member(); member.setId(request.getParameter("id")); member.setName(request.getParameter("name")); member.setPasswd(request.getParameter("passwd")); member.setRegister(new Timestamp(System.currentTimeMillis())); MemberDao manager = MemberDao.getInstance(); manager.insertMember(member); return "/view/insert.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; public class InsertFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { return "/view/insertForm.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import dr.mini.dao.MemberDao; import dr.mini.domain.Member; public class SelectDetailAction implements Action { @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); MemberDao mdb=MemberDao.getInstance(); Member member =mdb.getMember(id); request.setAttribute("member", member); return "/view/selectDetail.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import dr.mini.dao.MemberDao; import dr.mini.domain.Member; import java.util.List; public class SelectListAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); List<member> List =null; MemberDao mdb = MemberDao.getInstance(); List = mdb.getMemberList(); request.setAttribute("memberList", List); return "/view/selectList.jsp"; } }
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import dr.mini.dao.MemberDao; import dr.mini.domain.Member; public class UpdateAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); MemberDao manager = MemberDao.getInstance(); int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd")); if(check==1){ Member member =new Member(); member.setId(request.getParameter("id")); member.setName(request.getParameter("name")); manager.updateMember(member); } //오토박싱 request.setAttribute("check", check); return "/view/update.jsp"; } }
UpdateFormAction
package dr.mini.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dr.mini.controller.Action; import dr.mini.dao.MemberDao; import dr.mini.domain.Member; public class UpdateFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); MemberDao manager= MemberDao.getInstance(); Member member = manager.getMember(id); request.setAttribute("member", member); return "/view/updateForm.jsp"; } }
Action
package dr.mini.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스 public interface Action { public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable; }
Controller
package dr.mini.controller; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Controller extends HttpServlet { private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장 //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장 //명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일 public void init(ServletConfig config) throws ServletException { String configFile = config.getInitParameter("configFile"); Properties prop = new Properties(); FileInputStream fis = null; try { String configFilePath = config.getServletContext().getRealPath( configFile); fis = new FileInputStream(configFilePath); prop.load(fis); } catch (IOException e) { throw new ServletException(e); } finally { if (fis != null) try { fis.close(); } catch (IOException ex) { } } Iterator keyIter = prop.keySet().iterator(); while (keyIter.hasNext()) { String command = (String) keyIter.next(); String handlerClassName = prop.getProperty(command); try { Class handlerClass = Class.forName(handlerClassName); Object handlerInstance = handlerClass.newInstance(); commandMap.put(command, handlerInstance); } catch (ClassNotFoundException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } } } public void doGet(//get방식의 서비스 메소드 HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestPro(request, response); } protected void doPost(//post방식의 서비스 메소드 HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestPro(request, response); } //시용자의 요청을 분석해서 해당 작업을 처리 private void requestPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String view = null; Action com=null; try { String command = request.getRequestURI(); if (command.indexOf(request.getContextPath()) == 0) { command = command.substring(request.getContextPath().length()); } com = (Action)commandMap.get(command); view = com.execute(request, response); } catch(Throwable e) { throw new ServletException(e); } RequestDispatcher dispatcher =request.getRequestDispatcher(view); dispatcher.forward(request, response); } }
MemberDao
package dr.mini.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import dr.mini.domain.Member; public class MemberDao { private static MemberDao instance = new MemberDao(); public static MemberDao getInstance() { return instance; } private MemberDao(){} private Connection getConnection()throws Exception { Context initCtx = new InitialContext(); Context envCtx = (Context)initCtx.lookup("java:comp/env"); DataSource ds = (DataSource)envCtx.lookup("jdbc/orcl"); return ds.getConnection(); } //회원가입 public void insertMember(Member member)throws Exception { Connection conn= null; PreparedStatement pstmt = null; String sql=""; int cnt = 0; try{ conn= getConnection(); sql ="insert into MEMBER1 values(?,?,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(++cnt, member.getId()); pstmt.setString(++cnt, member.getPasswd()); pstmt.setString(++cnt, member.getName()); pstmt.setTimestamp(++cnt, member.getRegister()); pstmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //회원 목록 보기 public ListgetMemberList()throws Exception { Connection conn= null; PreparedStatement pstmt =null; ResultSet rs= null; List memeberList =null; Member member=null; String sql=""; try{ conn =getConnection(); sql ="select * from MEMBER1 order by register desc"; pstmt =conn.prepareStatement(sql); rs=pstmt.executeQuery(); if(rs.next()){ memeberList= new ArrayList (); do{ member =new Member(); member.setId(rs.getString("id")); member.setPasswd(rs.getString("passwd")); member.setName(rs.getString("name")); member.setRegister(rs.getTimestamp("register")); memeberList.add(member); }while(rs.next()); }else{ //없으면 //데이터가 없는 경우 비어있는 List 생성 memeberList = Collections.EMPTY_LIST; } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return memeberList; } //회원 상세 정보 보기 public Member getMember(String id)throws Exception { Connection conn =null; PreparedStatement pstmt = null; ResultSet rs = null; Member member=null; String sql=""; try{ conn=getConnection(); sql="select * from MEMBER1 where id= ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs= pstmt.executeQuery(); if(rs.next()){ member=new Member(); member.setId(rs.getString("id")); member.setPasswd(rs.getString("passwd")); member.setName(rs.getString("name")); member.setRegister(rs.getTimestamp("register")); } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return member; } //회원 인증 public int userCheck(String id, String passwd)throws Exception { Connection conn= null; PreparedStatement pstmt = null; ResultSet rs =null; String sql=""; String dbpasswd=""; int x = -1; try{ conn =getConnection(); sql ="select passwd from MEMBER1 where id = ?"; pstmt =conn.prepareStatement(sql); pstmt.setString(1, id); rs=pstmt.executeQuery(); if(rs.next()){ dbpasswd =rs.getString("passwd"); if(dbpasswd.equals(passwd)) x=1; //인증성공 else x=0; //비밀번호 틀림 }else x=-1; //해당 아이디 없음 }catch(Exception e){ e.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return x; } //회원 정보 수정 public void updateMember(Member member)throws Exception{ Connection conn=null; PreparedStatement pstmt =null; String sql = null; int cnt =0; try{ conn =getConnection(); sql = "update MEMBER1 set name=? where id=?"; pstmt =conn.prepareStatement(sql); pstmt.setString(++cnt, member.getName()); pstmt.setString(++cnt, member.getId()); pstmt.executeUpdate(); }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //회원 탈퇴 //회원정보 삭제 public void deleteMember(String id)throws Exception { Connection conn=null; PreparedStatement pstmt =null; String sql = null; try{ conn =getConnection(); sql = "delete from MEMBER1 where id=?"; pstmt =conn.prepareStatement(sql); pstmt.setString(1, id); pstmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //자원정리 private void execClose(ResultSet rs,PreparedStatement pstmt, Connection conn){ if (rs != null) try { rs.close(); } catch(SQLException ex) {} if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {} if (conn != null) try { conn.close(); } catch(SQLException ex) {} } }
Member
package dr.mini.domain; import java.sql.Timestamp; //자바빈 public class Member { //프로퍼티 private String id; private String passwd; private String name; private Timestamp register; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Timestamp getRegister() { return register; } public void setRegister(Timestamp register) { this.register = register; } }
META-INF
context.xml
<?xml version="1.0" encoding="UTF-8"?> <Context> <!-- maxActive="20" //최대 커넥션 수 maxIdle="10" //미리 만들어둘 기본커낵션 수 --> <Resource name="jdbc/orcl" auth="container" type="javax.sql.DataSource" username="hr" password="hr" driverClassName="oracle.jdbc.driver.OracleDriver" factory="org.apache.commons.dbcp.BasicDataSourceFactory" url="jdbc:oracle:thin:@localhost:1521:orcl" maxActive="20" maxIdle="10" /> </Context>
delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% //오토언박싱 int check =(Integer)request.getAttribute("check"); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>레코드 삭제 예제</title> </head> <body> <%if (check == 1){ %> <script type="text/javascript"> alert("글을 삭제하였습니다"); location.href="selectList.do"; </script> <% }else{ %> <script type="text/javascript"> alert("암호가 다릅니다."); history.go(-1); </script> <% } %> </body> </html>
deleteForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String id = (String)request.getAttribute("id"); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>레코드 삭제 예제</title></head> <body> <h2>member1 테이블에 삭제 예제</h2> <form method="post" action="delete.do"> <input type="hidden" name="id" value="<%=id %>"> 아이디 : <%=id %><p> 패스워드 : <input type="password" name="passwd"><p> <input type="submit" value="보내기"> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>레코드 삽입(추가)예제</title> </head> <body> member1 테이블에 새로운 레코드를 삽입(추가)했습니다. <input type="button" value="목록보기" onclick="location.href='selectList.do'"> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>레코드 삽입(추가)예제</title></head> <body> <h2>member1 테이블에 레코드삽입(추가)예제</h2> <form method="post" action="insert.do"> 아이디 : <input type="text" name="id"><p> 패스워드 : <input type="password" name="passwd"><p> 이름:<input type="text" name="name"><p> <input type="submit" value="보내기"> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="dr.mini.domain.Member" %> <% Member member = (Member)request.getAttribute("member"); %> <!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=UTF-8"> <title>레코드 삽입 (추가)예제</title> </head> <body> <h2>회원관리 상세 페이지</h2> 아이디:<%=member.getId() %><br/> 패스워드:<%=member.getPasswd() %><br/> 이름:<%=member.getName() %><br/> <input type="button" value="수정" onclick="location.href='updateForm.do?id=<%=member.getId()%>'"> <input type="button" value="삭제" onclick="location.href='deleteForm.do?id=<%=member.getId()%>'"> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.*"%> <%@ page import="dr.mini.domain.Member"%> <%@ page import="java.text.SimpleDateFormat"%> <!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=UTF-8"> <title>테이블의 레코드를 화면에 표시하는 예제</title> </head> <body> <h2>member1 테이블의 레코드를 화면에 표시하는 예제</h2> <a href="insertForm.do">등록</a> <br /> <% //목록같은경우는 어쩔수없이 jsp에서 루프를 돌려야함. SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy년 MM월 dd일 HH:mm:ss"); //제네릭표현에 의해 타입이 정해져있음 List<Member> memberList = (List<Member>)request.getAttribute("memberList"); Member mb=null; if(!memberList.isEmpty()){ for(int i=0;i<memberList.size();i++){ //제네릭 표현때문에 (Member)memberList를 memberList로 생략가능 mb=memberList.get(i); %> <a href="selectDetail.do?id=<%=mb.getId()%>"><%=mb.getId()%></a>-<%=mb.getPasswd()%>-<%=mb.getName()%>-<%=dateFormat.format(mb.getRegister())%><br /> <%}}%> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% //오토언박싱 int check =(Integer)request.getAttribute("check"); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>레코드 수정 예제</title> </head> <body> <%if (check == 1){ %> <script type="text/javascript"> alert("글을 수정하였습니다"); location.href="selectList.do"; </script> <% }else{ %> <script type="text/javascript"> alert("암호가 다릅니다."); history.go(-1); </script> <% } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import ="dr.mini.domain.Member" %> <% Member member=(Member)request.getAttribute("member"); %> <!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=UTF-8"> <title>레코드 수정 예제</title> </head> <body> <h2>member1 테이블에 레코드 수정 예제</h2> <form method="post" action="update.do"> <input type="hidden" name="id" value="<%=member.getId()%>"> 아이디:<%=member.getId() %><p> 패스워드:<input type="password" name="passwd"><p> 이름:<input type="text" name="name" value="<%=member.getName()%>"><p> <input type="submit" value="보내기"> </form> </body> </html>
lib
commons-collections-3.1.jar
commons-dbcp-1.2.1.jar
commons-pool-1.2.jar
commandMap.properties
web.xml
/insertForm.do=dr.mini.action.InsertFormAction /insert.do=dr.mini.action.InsertAction /selectList.do=dr.mini.action.SelectListAction /selectDetail.do=dr.mini.action.SelectDetailAction /updateForm.do=dr.mini.action.UpdateFormAction /update.do=dr.mini.action.UpdateAction /deleteForm.do=dr.mini.action.DeleteFormAction /delete.do=dr.mini.action.DeleteAction
<?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"> <!-- Controller start --> <servlet> <servlet-name>Controller</servlet-name> <servlet-class>dr.mini.controller.Controller</servlet-class> <init-param> <param-name>configFile</param-name> <param-value>/WEB-INF/commandMap.properties</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Controller</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Controller end --> <display-name>mvcMain2</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> </web-app>
컨트롤러 맵핑확인 :Controller
insertForm.do 로연결확인
회원가입 테스트 [Controller 실행 ->요청-> InsertFormAction.java->insertForm.jsp -> insertAction.java-> insert.jsp]
DB입력확인
리스트확인 : selectList.do
상세페이지 테스트 : SelectDetailAction -> selectDetail.jsp
수정페이지 테스트 : UpdateFormAction ->updateForm.jsp ->UpdateActioc ->update.jsp
삭제테스트 : DeleteFormAction ->deleteForm.jsp ->DeleteActioc ->delete.jsp
'JSP > 기본(Oracle)' 카테고리의 다른 글
방명록 (0) | 2012.06.20 |
---|---|
회원관리 (1) | 2012.06.20 |
모델2 : MVC : Model View Controlle r- DB연동없이 (0) | 2012.06.20 |
MVC: Model View Controller 모델2 ( 완전중요) (0) | 2012.06.20 |
EL(표현언어), JSTL, 국제화 태그 - 예제 (0) | 2012.06.20 |