create table guestbook( num number primary key, register date NOT NULL, name varchar2(20) NOT NULL, email varchar2(40), passwd varchar2(10) NOT NULL, content varchar2(4000) NOT NULL); create sequence guestbook_seq;
글번호 num
insert into GUESTBOOK (num,register,name,email,passwd,content) values(guestbook_seq.nextval,?,?,?,?,?)
오라클 sequence guestbook_seq.curval 현재번호
sequence guestbook_seq.nextval 다음번호
테이블작성
select * from( //시스템에서 제공하는 행번호 rownum의 별칭 rnum : 명시적 행번호 호출 //a.* = num,register,name,email,.... a아래있는 모든 컬럼이다. (a: 테이블에 대한 별칭) select a.*, rownum rnum from( //서브쿼리 select * from GUESTBOOK order by num desc )a//테이블 별칭 ) where rnum >=1 and rnum <=10 //행번호 1~10 까지
M: Model : 자바클래스, 데이터 처리
V: View : JSP, 화면 디스클레이
C: Controller : servlet, 요청을 받아서 모델과 뷰를 호출하는 역활
Java Resources
src
com.guestbook.action
DeleteAction
package com.guestbook.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; import com.guestbook.dao.GuestbookDao; public class DeleteAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { //1.전송된 num,비밀번호 추출 int num = Integer.parseInt(request.getParameter("num")); String passwd = request.getParameter("passwd"); //2. GuestbookDao의 uesrCheck에 num, 비밀번호 전달 GuestbookDao manager = GuestbookDao.getInstance(); int check = manager.userCheck(num, passwd); //3. check가 1인 경우 delete 메서드 호출 if(check == 1){ manager.delete(num); } //4. check를 request에 저장 request.setAttribute("check", check); return "/view2/delete.jsp"; } }
DeleteFormAction
package com.guestbook.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; public class DeleteFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { return "/view2/deleteForm.jsp"; } }
ListAction
package com.guestbook.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; import com.guestbook.dao.GuestbookDao; import com.guestbook.domain.Guestbook; import com.guestbook.domain.GuestbookPage; public class ListAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { //한페이지 글의수 int pageSize = 10; String pageNum =request.getParameter("pageNum"); if(pageNum ==null){ pageNum = "1"; } int currentPage = Integer.parseInt(pageNum); int startRow =(currentPage-1)*pageSize +1; int endRow =currentPage * pageSize; int count = 0; List<Guestbook> bookList =null; GuestbookDao manager = GuestbookDao.getInstance(); count =manager.getCount(); if(count>0){ bookList = manager.getList(startRow, endRow); } //GuestbookPage : 자바빈 하나더 만들기 //Guestbook 자바빈에 다 넣을수도있다, 그러나 분류를위해 나눠쓴것 //작업자가 효율적으로 분류해서 쓰도록한다. GuestbookPage page= new GuestbookPage(); page.setCount(count); page.setCurrentPage(currentPage); page.setPageSize(pageSize); request.setAttribute("page", page); request.setAttribute("bookList", bookList); return "/view2/list.jsp"; } }
UpdateAction
package com.guestbook.action; import java.sql.Timestamp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; import com.guestbook.dao.GuestbookDao; import com.guestbook.domain.Guestbook; public class UpdateAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { //1.인코딩처리 request.setCharacterEncoding("utf-8"); //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장 Guestbook book =new Guestbook(); book.setNum(Integer.parseInt(request.getParameter("num"))); book.setName(request.getParameter("name")); book.setEmail(request.getParameter("email")); book.setPasswd(request.getParameter("passwd")); book.setContent(request.getParameter("content")); //3.GuestbookDao의 userCheck 메소드에 num과 비밀번호 전달인증 GuestbookDao manager = GuestbookDao.getInstance(); int check = manager.userCheck(book.getNum(),book.getPasswd()); //4.check가 1인 경우 GuestbookDao의 update 메소드에 자바빈 전달 if(check==1){ manager.update(book); } //5.check를 request에 저장 request.setAttribute("check", check); return "/view2/update.jsp;"; } }
UpdateFormAction
package com.guestbook.action; import java.sql.Timestamp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; import com.guestbook.dao.GuestbookDao; import com.guestbook.domain.Guestbook; public class UpdateFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { //1. 전송된 글번호(num)를 request에서 추출 int num = Integer.parseInt(request.getParameter("num")); //2. GuestbookDao의 getGuestbook 메소드에 num를 전달 GuestbookDao manager = GuestbookDao.getInstance(); Guestbook book = manager.getGuestBook(num); //3. 자바빈을 reqeust에 저장 request.setAttribute("book", book); return "/view2/updateForm.jsp"; } }
WriteAction
package com.guestbook.action; import java.sql.Timestamp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; import com.guestbook.dao.GuestbookDao; import com.guestbook.domain.Guestbook; public class WriteAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { //1.인코딩처리 request.setCharacterEncoding("utf-8"); //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장 Guestbook guestbook =new Guestbook(); guestbook.setRegister(new Timestamp(System.currentTimeMillis())); guestbook.setName(request.getParameter("name")); guestbook.setEmail(request.getParameter("email")); guestbook.setPasswd(request.getParameter("passwd")); guestbook.setContent(request.getParameter("content")); //3.GuestbookDao의 insert 메소드에 자바빈 전달 GuestbookDao manager = GuestbookDao.getInstance(); manager.insert(guestbook); return "/view2/write.jsp"; } }
WriteFormAction
package com.guestbook.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guestbook.controller.Action; public class WriteFormAction implements Action{ @Override public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable { return "view2/writeForm.jsp"; } }
com.guestbook.controller
Action
package com.guestbook.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 com.guestbook.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); } }
com.guestbook.dao
GuestbookDao
package com.guestbook.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; 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 com.guestbook.domain.Guestbook; public class GuestbookDao { private static GuestbookDao instance =new GuestbookDao(); public static GuestbookDao getInstance(){ return instance; } private GuestbookDao(){} 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 insert(Guestbook book) throws Exception{ Connection conn= null; PreparedStatement pstmt = null; String sql=""; //바인드문자 ?의 순서 int cnt = 0; try{ conn= getConnection(); sql = "insert into GUESTBOOK (num,register,name,email,passwd,content) " + "values(guestbook_seq.nextval,?,?,?,?,?)"; //sql ="insert into GUESTBOOK values(guestbook_seq.nextval,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setTimestamp(++cnt, book.getRegister()); pstmt.setString(++cnt, book.getName()); pstmt.setString(++cnt, book.getEmail()); pstmt.setString(++cnt, book.getPasswd()); pstmt.setString(++cnt, book.getContent()); pstmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //글의 총갯수 public int getCount() throws Exception{ Connection conn= null; PreparedStatement pstmt =null; ResultSet rs= null; int count =0; String sql =null; try{ conn=getConnection(); // 갯수를 구하는 sql 함수 count(*) :레코드의 총수는 sql="select count(*) from GUESTBOOK"; pstmt =conn.prepareStatement(sql); rs =pstmt.executeQuery(); if (rs.next()){ //1: 컬럼의 순서 (가상의 컬럼 count(*)) //getInt(count(*))도 가능 count =rs.getInt(1); } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return count; } //글 목록 public List<Guestbook> getList(int startRow, int endRow)throws Exception{ Connection conn= null; PreparedStatement pstmt =null; ResultSet rs= null; List<Guestbook>list =null; String sql=""; try{ conn =getConnection(); //새글이 위로 올라오게 내림차순 //sql ="select * from GUESTBOOK order by num desc"; // select(select 서브쿼리) sql ="select * from(select a.*, rownum rnum from(select * from GUESTBOOK order by num desc)a) where rnum >=? and rnum <=?"; pstmt =conn.prepareStatement(sql); pstmt.setInt(1, startRow); pstmt.setInt(2, endRow); //sql문 반영 rs=pstmt.executeQuery(); //데이터가 있는가없는가 확인 if(rs.next()){ //있으면 list= new ArrayList<Guestbook>(); //if문에서 이미 커서가 첫번째 행을 가리키기 때문에 첫번째 행 부터 뽑기위해 do while 문 do{ Guestbook book =new Guestbook(); book.setNum(rs.getInt("num")); book.setRegister(rs.getTimestamp("register")); book.setName(rs.getString("name")); book.setEmail(rs.getString("email")); book.setPasswd(rs.getString("passwd")); book.setContent(rs.getString("content")); list.add(book); }while(rs.next()); }else{ //없으면 //데이터가 없는 경우 비어있는 List 생성 list = Collections.EMPTY_LIST; } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return list; } //수정 폼에 보여질 한건의 레코드 정보 public Guestbook getGuestBook(int num)throws Exception{ Connection conn =null; PreparedStatement pstmt= null; ResultSet rs = null; Guestbook book=null; String sql=null; try{ conn=getConnection(); sql ="select * from GUESTBOOK where num = ? "; pstmt=conn.prepareStatement(sql); pstmt.setInt(1, num); rs=pstmt.executeQuery(); if(rs.next()){ book=new Guestbook(); book.setNum(rs.getInt("num")); book.setRegister(rs.getTimestamp("register")); book.setName(rs.getString("name")); book.setEmail(rs.getString("email")); book.setPasswd(rs.getString("passwd")); book.setContent(rs.getString("content")); } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return book; } //인증 public int userCheck(int num, String passwd)throws Exception{ Connection conn =null; PreparedStatement pstmt=null; ResultSet rs=null; String dbpasswd=""; String sql=""; int x=-1; try{ conn= getConnection(); sql="select passwd from GUESTBOOK where num=?"; pstmt =conn.prepareStatement(sql); pstmt.setInt(1, num); rs=pstmt.executeQuery(); if(rs.next()){ dbpasswd =rs.getString("passwd"); if(dbpasswd.equals(passwd)){ x=1;//인증성공 }else x=0;//비밀전호 틀림 } }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(rs,pstmt,conn); } return x; } //글수정 public void update(Guestbook book)throws Exception{ Connection conn=null; PreparedStatement pstmt =null; int cnt =0; String sql = null; try{ conn =getConnection(); sql = "update GUESTBOOK set name=?,email=?, content=? where num=?"; pstmt =conn.prepareStatement(sql); pstmt.setString(++cnt, book.getName()); pstmt.setString(++cnt, book.getEmail()); pstmt.setString(++cnt, book.getContent()); pstmt.setInt(++cnt, book.getNum()); pstmt.executeUpdate(); }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(null,pstmt,conn); } } //글삭제 public void delete(int num)throws Exception{ Connection conn =null; PreparedStatement pstmt=null; String sql=null; try{ conn= getConnection(); sql="delete from GUESTBOOK where num=?"; pstmt =conn.prepareStatement(sql); pstmt.setInt(1, num); pstmt.executeUpdate(); }catch(Exception ex){ ex.printStackTrace(); }finally{ execClose(null,pstmt,conn); } return ; } //자원정리 public void execClose(ResultSet rs, PreparedStatement pstmt, Connection conn)throws Exception{ if(rs !=null) try{rs.close();}catch(SQLException sqle){} if(pstmt !=null) try{pstmt.close();}catch(SQLException sqle){} if(conn !=null) try{conn.close();}catch(SQLException sqle){} } }
com.guestbook.domain
Guestbook
package com.guestbook.domain; import java.sql.Timestamp; public class Guestbook { private int num; private Timestamp register; private String name; private String email; private String passwd; private String content; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public Timestamp getRegister() { return register; } public void setRegister(Timestamp register) { this.register = register; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
GuestbookPage
package com.guestbook.domain; public class GuestbookPage { private int count; private int pageSize; private int currentPage; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
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>
WebContent
view2
delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:if test="${check == 1}"> <script type="text/javascript"> alert("글정보가 삭제 되었습니다."); location.href="list.do"; </script> </c:if> <c:if test="${check != 1}"> <script type="text/javascript"> alert("비밀번호가 맞지 않습니다."); history.go(-1); </script> </c:if>
deleteForm.jsp
<%@ 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> <form action="delete.do" method="post"> <input type="hidden" name="num" value="${param.num }"> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>암호</td> <td><input type="password" name="passwd" size="10"><br> 글을 쓸때 입력한 암호와 동일해야 글이 삭제됩니다.</td> </tr> <tr> <td colspan="2"><input type="submit" value="글삭제하기"></td> </tr> </table> </form> </body> </html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>글목록</title></head> <body> <table width="100%" align="center"> <tr> <td> <a href="writeForm.do">글쓰기</a> </td> </table> <c:if test="${page.count == 0}"> <table width="100%" border="1" cellpadding="0" cellspacing="0" align="center"> <tr> <td bgcolor="#e9e9e9"> 방명록에 저장된 글이 없습니다. </td> </table> </c:if> <c:if test="${page.count > 0}"> <table width="100%" border="1" cellpadding="0" cellspacing="0" align="center"> <!-- bookList를 받아 반복문 EL 함수(잘안씀 교제 P523)외에는 프로퍼티형식 \$ 는 주석에서도 \로 무력화 시켜야한다. \${book.email} O \${book,getEmial()} X옳지않다. \${book.name} O \${book,getName()} X옳지않다. 표기법은 변수명이지만 사실상 getter메소드를 통해 출력받는다. --> <c:forEach var="book" items="${bookList}"> <tr> <td bgcolor="#e9e9e9"> <b>${book.name}(${(book.email == null) ? "" : book.email})</b> - <font size="2"> <fmt:formatDate value="${book.register}" pattern="yyyy년MM월dd일"/> <a href="updateForm.do?num=${book.num}">[수정]</a> <a href="deleteForm.do?num=${book.num}">[삭제]</a> </font> </td> </tr> <tr> <td>${book.content }</td> </tr> </c:forEach> </table> </c:if> <div align="center"> <c:if test="${page.count > 0}"> <!-- 1.페이지블록지정 EL로 감싸 넘김 ${10} Integer로 인정 re: value="${(page.currentPage - 1) / pageBlock}" integerOnly="true" :실수가 나와도 정수로만표현 --> <c:set var="pageBlock" value="${10}"/> <c:set var="pageCount" value="${(page.count - 1) / page.pageSize + 1}"/> <fmt:parseNumber var="rs" value="${(page.currentPage - 1) / pageBlock}" integerOnly="true" /> <c:set var="startPage" value="${rs*pageBlock+1}"/> <c:set var="endPage" value="${startPage + pageBlock-1}"/> <c:if test="${endPage > pageCount}"> <c:set var="endPage" value="${pageCount}"/> </c:if> <c:if test="${startPage > pageBlock}"> <a href="list.do?pageNum=${startPage - pageBlock }">[이전]</a> </c:if> <c:forEach var="i" begin="${startPage}" end="${endPage}"> <c:if test="${i == page.currentPage}"> [${i }] </c:if> <c:if test="${i != page.currentPage}"> <a href="list.do?pageNum=${i}">[${i}]</a> </c:if> </c:forEach> <c:if test="${endPage < pageCount}"> <a href="list.do?pageNum=${startPage + pageBlock}">[다음]</a> </c:if> </c:if> </div> </body> </html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:if test="${check == 1}"> <script type="text/javascript"> alert("글정보가 수정되었습니다."); location.href="list.do"; </script> </c:if> <c:if test="${check != 1}"> <script type="text/javascript"> alert("비밀번호가 맞지 않습니다."); history.go(-1); </script> </c:if>
updateForm.jsp
<%@ 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> <script type="text/javaScript"> <!-- function checkIt() { var user = document.userinput; if(!user.name.value) { alert("사용자 이름을 입력하세요"); user.name.focus(); return false; } if(!user.passwd.value ) { alert("비밀번호를 입력하세요"); user.passwd.focus(); return false; } if(!user.content.value ) { alert("내용을 입력하세요"); user.content.focus(); return false; } } //--> </script> </head> <body> <form action="update.do" method="post"> <!-- get방식으로 넘어온 num을 EL을 통해서 뽑아낸다. value="${param.num}" --> <input type="hidden" name="num" value="${param.num}"> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>암호</td> <td><input type="password" name="passwd" size="10"><br> 글을 쓸때 입력한 암호와 동일해야 글이 수정됩니다.</td> </tr> <tr> <td>이름</td> <td><input type="text" name="name" value="${book.name}" size="10"></td> </tr> <tr> <td>이메일</td> <td><input type="text" name="email" value="${book.email}" size="30"></td> </tr> <tr> <td>내용</td> <td> <textarea name="content" rows="5" cols="50">${book.content}</textarea> </td> </tr> <tr> <td colspan="2"><input type="submit" value="글수정하기"></td> </tr> </table> </form> </body> </html>
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <script type="text/javaScript"> alert("방명록에 글을 등록하였습니다."); location.href="list.do"; </script>
writeForm.jsp
<%@ 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> <script type="text/javaScript"> <!-- function checkIt() { var user = document.userinput; if(!user.name.value) { alert("사용자 이름을 입력하세요"); user.name.focus(); return false; } if(!user.passwd.value ) { alert("비밀번호를 입력하세요"); user.passwd.focus(); return false; } if(!user.content.value ) { alert("내용을 입력하세요"); user.content.focus(); return false; } } //--> </script> </head> <body> <form name="userinput" action="write.do" method="post" onsubmit="return checkIt()"> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>이름</td> <td><input type="text" name="name" size="10"></td> </tr> <tr> <td>암호</td> <td><input type="password" name="passwd" size="10"></td> </tr> <tr> <td>이메일</td> <td><input type="text" name="email" size="30"></td> </tr> <tr> <td>내용</td> <td><textarea name="content" rows="5" cols="50"></textarea></td> </tr> <tr> <td colspan="2"><input type="submit" value="글남기기"></td> </tr> </table> </form> </body> </html>
WEB-INF
lib
commons-collections-3.1.jar
commons-dbcp-1.2.1.jar
commons-pool-1.2.jar
jstl-1.2.jar
commandMap.properties
/writeForm.do=com.guestbook.action.WriteFormAction /write.do=com.guestbook.action.WriteAction /list.do=com.guestbook.action.ListAction /updateForm.do=com.guestbook.action.UpdateFormAction /update.do=com.guestbook.action.UpdateAction /deleteForm.do=com.guestbook.action.DeleteFormAction /delete.do=com.guestbook.action.DeleteAction
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>guestbook</display-name> <!-- Controller start --> <servlet> <servlet-name>Controller</servlet-name> <servlet-class>com.guestbook.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 --> <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>
글등록 테스트 WriteFormAction -> writeForm.jsp -> WriteAction -> write.jsp
글목록 테스트 ListAction -> list.jsp
수정테스트 UpdateFormAction -> updateForm.jsp -> UpdateAction -> update.jsp -> list.do
삭제테스트 : DeleteFormAction -> deleteForm.jsp -> DeleteAction -> delete.jsp -> list.do
'JSP > 기본(Oracle)' 카테고리의 다른 글
JSP Oracle Clob 사용법, 날짜 며칠전 / 몇분전 / 몇년전 으로 치환 (0) | 2012.06.20 |
---|---|
MVC 모델2 : (Album게시판) (2) | 2012.06.20 |
회원관리 (1) | 2012.06.20 |
모델2 : MVC : Model View Controller - DB연동 (0) | 2012.06.20 |
모델2 : MVC : Model View Controlle r- DB연동없이 (0) | 2012.06.20 |