<완성된 화면>
<로그인 페이지>
<로그인했을때>
-
Dynamic Web Project로 ServletGuest라는 프로젝트 만들기. Generate web.xml에 체크하기
-
WebContent에 guestbook이라는 폴더 만들고, insert.jsp 만들기 (폼태그)
-
Java Resources-src-com.guest.model 패키지 만들고 GuestDTO.java 만들기 (getter, setter)
-
Preferences에 getter body가 다음과 같이 설정되어야 함
-
num은 정수형 변수이므로 getNum()은 return num;으로만 설정
-
WEB-INF 폴더의 lib 폴더안에 jstl-1.2.jar 파일, json-simple-1.1.1.jar파일을 붙여넣는다.
<데이터베이스>
-
오라클 SQL 디벨로퍼 열고 scott계정에 guestbook 테이블 생성
-
num에 해당하는 시퀀스 생성
-
com.guest.model패키지에 GuestDAO.java 만들기 (디비셋팅, 추가, 전체보기, 상세보기 등)
-
디비셋팅할때 DataSource의 lookup 메소드 인자를 jdbc/guest로 수정
-
전 프로젝트의 META-INF의 context.xml을 복사해서 현재 프로젝트 META-INF폴더 안에 복사해놓고 name="jdbc/guest"로 수정
<GuestDAO.java>
package com.guest.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class GuestDAO {
//디비셋팅
private static GuestDAO instance=new GuestDAO();
public static GuestDAO getInstance() {
return instance;
}
private Connection getConnection() throws Exception{
Context initCtx=new InitialContext();
Context envCtx=(Context) initCtx.lookup("java:comp/env");
DataSource ds=(DataSource) envCtx.lookup("jdbc/guest"); //context.xml의 name을 jdbc/guest로 바꾸기
return ds.getConnection();
}
//추가
public void guestInsert(GuestDTO guest) {
Connection con=null;
PreparedStatement ps=null;
try {
con=getConnection();
String sql="insert into guestbook(num, name, content, grade, created, ipaddr)"
+ "values (guestbook_seq.nextval,?,?,?,sysdate,?)";
ps=con.prepareStatement(sql);
ps.setString(1, guest.getName());
ps.setString(2, guest.getContent());
ps.setString(3, guest.getGrade());
ps.setString(4, guest.getIpaddr());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con,ps);
}
}
//전체보기 페이징
public ArrayList<GuestDTO> guestList(int startRow, int endRow){
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<GuestDTO> arr=new ArrayList<GuestDTO>();
try {
con=getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from");
sb.append(" (select aa.*, rownum rn from");
sb.append(" (select * from guestbook order by num desc) aa");
sb.append(" where rownum<=?) where rn>=?");
ps=con.prepareStatement(sb.toString());
ps.setInt(1, endRow);
ps.setInt(2, startRow);
rs=ps.executeQuery();
while(rs.next()) {
GuestDTO dto=new GuestDTO();
dto.setNum(rs.getInt("num"));
dto.setContent(rs.getString("content"));
dto.setCreated(rs.getString("created"));
dto.setGrade(rs.getString("grade"));
dto.setIpaddr(rs.getString("ipaddr"));
dto.setName(rs.getString("name"));
arr.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps, rs);
}
return arr;
}
//검색 전체보기 페이징
public ArrayList<GuestDTO> guestList(String field, String word, int startRow, int endRow){
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<GuestDTO> arr=new ArrayList<GuestDTO>();
try {
con=getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from");
sb.append(" (select aa.*, rownum rn from");
sb.append(" (select * from guestbook where "+field+" like '%"+word+"%'");
sb.append(" order by num desc) aa");
sb.append(" where rownum<=?) where rn>=?");
ps=con.prepareStatement(sb.toString());
ps.setInt(1, endRow);
ps.setInt(2, startRow);
rs=ps.executeQuery();
while(rs.next()) {
GuestDTO dto=new GuestDTO();
dto.setNum(rs.getInt("num"));
dto.setContent(rs.getString("content"));
dto.setCreated(rs.getString("created"));
dto.setGrade(rs.getString("grade"));
dto.setIpaddr(rs.getString("ipaddr"));
dto.setName(rs.getString("name"));
arr.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps, rs);
}
return arr;
}
//전체보기
public ArrayList<GuestDTO> guestList(){
Connection con=null;
Statement st=null;
ResultSet rs=null;
ArrayList<GuestDTO> arr=new ArrayList<GuestDTO>();
try {
con=getConnection();
st=con.createStatement();
String sql="select * from guestbook order by num desc";
rs=st.executeQuery(sql);
while(rs.next()) {
GuestDTO dto=new GuestDTO();
dto.setNum(rs.getInt("num"));
dto.setContent(rs.getString("content"));
dto.setCreated(rs.getString("created"));
dto.setGrade(rs.getString("grade"));
dto.setIpaddr(rs.getString("ipaddr"));
dto.setName(rs.getString("name"));
arr.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return arr;
}
//상세보기
public GuestDTO guestView(int num) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
GuestDTO guest=null;
try {
con=getConnection();
st=con.createStatement();
String sql="select * from guestbook where num="+num;
rs=st.executeQuery(sql);
if(rs.next()) {
guest=new GuestDTO();
guest.setNum(rs.getInt("num"));
guest.setContent(rs.getString("content"));
guest.setCreated(rs.getString("created"));
guest.setGrade(rs.getString("grade"));
guest.setIpaddr(rs.getString("ipaddr"));
guest.setName(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return guest;
}
//평가 리스트 개수 출력
public int guestCount() {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int count=0;
try {
con=getConnection();
String sql="select count(*) from guestbook";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) {
count=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return count;
}
//검색 평가 리스트 개수 출력
public int guestCount(String field, String word) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int count=0;
String sql="";
try {
con=getConnection();
st=con.createStatement();
if(word.equals("")) {
sql="select count(*) from guestbook";
}else {
sql="select count(*) from guestbook where "+field+" like '%"+word+"%'";
}
rs=st.executeQuery(sql);
if(rs.next()) {
count=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return count;
}
//삭제
public void guestDelete(int num) {
Connection con=null;
Statement st=null;
try {
con=getConnection();
String sql="delete from guestbook where num="+num;
st=con.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, null);
}
}
//로그인체크 (비밀번호 오류: 2, 회원아님: -1, 관리자: 1, 일반회원: 0)
public int guestLoginCheck(String userid, String pwd) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int flag=-1;
try {
con=getConnection();
String sql="select pwd, admin from jmember where userid='"+userid+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) { //id 맞음
if(rs.getString("pwd").equals(pwd)) { //비번 일치
flag=rs.getInt("admin");
}else { //비번 오류
flag=2;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return flag;
}
//닫기 closeConnection
private void closeConnection(Connection con, PreparedStatement ps) {
try {
if(ps!=null) ps.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void closeConnection(Connection con, Statement st, ResultSet rs) {
try {
if(st!=null) st.close();
if(con!=null) con.close();
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<GuestDTO.java>
package com.guest.model;
public class GuestDTO {
private int num;
private String name;
private String content;
private String grade;
private String created;
private String ipaddr;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name == null ? "" : name.trim();
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content == null ? "" : content.trim();
}
public void setContent(String content) {
this.content = content;
}
public String getGrade() {
return grade == null ? "" : grade.trim();
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getCreated() {
return created == null ? "" : created.trim();
}
public void setCreated(String created) {
this.created = created;
}
public String getIpaddr() {
return ipaddr == null ? "" : ipaddr.trim();
}
public void setIpaddr(String ipaddr) {
this.ipaddr = ipaddr;
}
}
<insert.jsp>
-
submit전송 버튼을 누르면 create.gb로 가도록 함.
-
com.guest.action이란 패키지안에 서블릿으로 GuestInsertAction.java 생성하여 액션 실행. (서블릿의 경로는 guestbook/create.gb)
-
com.guest.model에 들어있는 GuestDAO.java파일에서 guestInsert()메소드를 호출하도록 함
-
GuestInsertAction.java에서 guestInsert를 실행하고나면 list.gb로 가도록 함.
-
이름과 내용에 글자수를 표시하도록 자바스크립트 함수 생성.
-
상세보기 하게끔 fview() 자바스크립트 함수를 생성. (getJSON 사용. 콜백함수에서 결과 출력)
-
검색영역 생성 <form name="search" id="search">
<insert.jsp+ajax>
-
insert.jsp에서 내용을 입력하면 listResult.jsp로 넘어가지 말고 입력칸 바로 밑에 결과들이 뜨게 하고 싶다면? (댓글쓰기 처럼) ajax 비동기 방식으로 값을 뿌려주면 됨.
-
검색찾기 버튼을 클릭하면 getData()함수를 호출함 (전체보기 함수) 단, 함수 호출 시 페이지 번호, field, word 값을 들고 가야함. getData(페이지 번호, field, word)로 함수 수정하기
-
count 함수도 수정
-
검색결과의 페이징을 위해 pageUtil에 filed, word 변수 선언.
-
검색결과의 페이지가 제대로 안넘어간다? listResult.jsp에서 getData의 변수로 오는 field와 word는 문자열이니까 따옴표 혹은 홑따옴표로 감싸야함.
-
삭제실행 추가
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
getData(1, "", ""); //페이지 로드 시 전체 리스트 보기
$("#btnSearch").on("click", function(){//검색버튼 클릭
getData(1, $("#field").val(), $("#word").val());
})//btnSearch
$("#send").click(function(){ //전송버튼 클릭
if(${sessionScope.login==null}){
alert("로그인 필요");
return false;
}
var name=$("#name").val();
var content=$("#content").val();
var grade=$("input:radio[name=grade]:checked").val();
var postString="name="+name+"&content="+content+"&grade="+grade;
$.ajax({
type: "post",
url : "create.gb",
data: postString,
success:function(d){
$("#result").html(d);
},
beforeSend: showRequest, //빈칸 확인
error: function(e){
alert("error:"+e);
}
})//ajax
})//send
})//document
//전체보기 함수
function getData(pageNum, field, word){
$.get("list.gb",
{"pageNum":pageNum, "field":field, "word":word},
function(d){
$("#result").html(d);
})
}//getData
//빈칸 확인
function showRequest(){
if($("#name").val()==""){
alert("이름을 입력하세요");
$("#name").focus();
return false;
}
if($("#content").val()==""){
alert("내용을 입력하세요");
$("#content").focus();
return false;
}
if($("input:radio[name=grade]:checked").length==0){
alert("평가를 해주세요");
return false;
}
return true;
}//showRequest
//글자수 초과 함수
function textCount(obj,target){ //target: nameCount, contentCount
var len=$("#"+obj.id).val().length;
if(obj.size==len){
alert("글자수 초과");
return false;
}
$("#"+target).text(len);
}//textCount
//상세보기 함수
function fview(num){
$.getJSON ("view.gb", {"num": num}, function(data){
var htmlStr="<table align='center' border='1'>";
htmlStr+="<tr>";
htmlStr+="<th>번호</th>";
htmlStr+="<td>"+data.num+"</td>";
htmlStr+="</tr>";
htmlStr+="<tr>";
htmlStr+="<th>글쓴이</th>";
htmlStr+="<td>"+data.name+"</td>";
htmlStr+="</tr>";
htmlStr+="<tr>";
htmlStr+="<th>내용</th>";
htmlStr+="<td>"+data.content+"</td>";
htmlStr+="</tr>";
htmlStr+="<tr>";
htmlStr+="<th>평가</th>";
htmlStr+="<td>"+data.grade+"</td>";
htmlStr+="</tr>";
htmlStr+="<th>작성일</th>";
htmlStr+="<td>"+data.created+"</td>";
htmlStr+="</tr>";
htmlStr+="<tr>";
htmlStr+="<th>ip주소</th>";
htmlStr+="<td>"+data.ipaddr+"</td>";
htmlStr+="</tr>";
htmlStr+="</table>";
$("#view").html(htmlStr);
}//콜백함수
)
} //fview
//삭제 함수
function fdelete(num, name){
if(confirm("["+name+"]의 게시물을 삭제할까요?")){
$.get ("delete.gb?num="+num, function(data){
$("#result").html(data);
})
}
}
</script>
</head>
<body>
<c:if test="${sessionScope.login==null}">
<a href="login.jsp">로그인</a>
</c:if>
<c:if test="${sessionScope.login!=null}">
${login}님 반갑습니다.
<a href="logout.gb">로그아웃</a>
</c:if>
<br/><br/>
<form action="create.gb" method="post">
<table align="center" width=900px>
<tr>
<td align="center">글쓴이</td>
<td>
<input type="text" size="20" maxlength="20" id="name" name="name" onKeyup="textCount(this,'nameCount')">
*20글자이내 (<span id="nameCount" style="color:red">0</span>)
</td>
</tr>
<tr>
<td align="center">내용</td>
<td>
<input type="text" size="70" maxlength="70" id="content" name="content" onKeyup="textCount(this,'contentCount')">
*70글자이내 (<span id="contentCount" style="color:red">0</span>)
</td>
</tr>
<tr>
<td align="center">평가</td>
<td>
<input type="radio" name="grade" value="excellent">아주잘함(excellent)
<input type="radio" name="grade" value="good">잘함(good)
<input type="radio" name="grade" value="normal">보통(normal)
<input type="radio" name="grade" value="fail">노력(fail)
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit전송">
<input type="button" value="ajax버튼 전송" id="send">
</td>
</tr>
</table>
</form>
<br/><br/>
<div align="center">
<form name="search" id="search">
<select name="field" id="field">
<option value="name">이름</option>
<option value="content">내용</option>
</select>
<input type="text" name="word" id="word">
<input type="button" value="찾기" id="btnSearch">
</form>
</div>
<br/><br/>
<div id="result" align="center"></div>
<hr>
<div id="view"></div>
</body>
</html>
<GuestInsertAction.java>
package com.guest.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.guest.model.GuestDAO;
import com.guest.model.GuestDTO;
/**
* Servlet implementation class GuestInsertAction
*/
@WebServlet("/guestbook/create.gb")
public class GuestInsertAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestInsertAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd=request.getRequestDispatcher("insert.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
GuestDTO guest=new GuestDTO();
guest.setName(request.getParameter("name"));
guest.setContent(request.getParameter("content"));
guest.setGrade(request.getParameter("grade"));
guest.setIpaddr(request.getRemoteAddr());
GuestDAO dao=GuestDAO.getInstance();
dao.guestInsert(guest);
response.sendRedirect("list.gb");
}
}
<listResult.jsp>
-
list.gb는 GuestListAction.java 서블릿의 경로인데 여기서 guestList()메소드를 호출.
-
메소드로 인해 불러온 값들은 listResult.jsp에 뿌려짐.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<h5>평가 리스트(<span id="cntSpan">${count}</span>)</h5>
<table class="table table-hover">
<thead>
<tr>
<th>번호</th>
<th>seq</th>
<th>글쓴이</th>
<th>평가</th>
<th>작성일</th>
<c:if test="${sessionScope.login!=null}">
<th>삭제</th>
</c:if>
</tr>
</thead>
<tbody>
<c:forEach items="${guest}" var="guest" varStatus="st">
<tr>
<td>${rowNo-st.index}</td>
<td>${guest.num}</td>
<td><a href="javascript:fview(${guest.num})">${guest.name}</a></td>
<td>${guest.grade}</td>
<td>${guest.created}</td>
<c:if test="${sessionScope.login!=null}">
<td><a href="javascript:fdelete(${guest.num},'${guest.name}')">삭제</a></td>
</c:if>
</tr>
</c:forEach>
</tbody>
</table>
<div align="center">
<c:if test="${pu.startPage>pu.pageBlock }"> <!-- 이전 -->
<a href="javascript:getData(${pu.startPage-pu.pageBlock},'${pu.field}','${pu.word}')">[이전]</a>
</c:if>
<c:forEach begin="${pu.startPage}" end="${pu.endPage}" var="i"><!-- 페이지 출력 -->
<c:if test="${i==pu.currentPage}"> <!-- 현재 페이지 -->
<c:out value="${i}"/>
</c:if>
<c:if test="${i!=pu.currentPage}"> <!-- 현재 페이지 아닌 경우 링크 부여-->
<a href="javascript:getData(${i},'${pu.field}','${pu.word}')">${i}</a>
</c:if>
</c:forEach>
<c:if test="${pu.endPage<pu.totPage}"> <!-- 다음-->
<a href="javascript:getData(${pu.endPage+1},'${pu.field}','${pu.word}')">[다음]</a>
</c:if>
</div>
</body>
</html>
<GuestListAction.java>
package com.guest.action;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.guest.model.GuestDAO;
import com.guest.model.GuestDTO;
import com.guest.model.PageUtil;
/**
* Servlet implementation class GuestListAction
*/
@WebServlet("/guestbook/list.gb")
public class GuestListAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestListAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
GuestDAO dao=GuestDAO.getInstance();
String pageNum=request.getParameter("pageNum")==null? "1":request.getParameter("pageNum");
int currentPage=Integer.parseInt(pageNum);
int pageSize=5;
int startRow=(currentPage-1)*pageSize+1;
int endRow=currentPage*pageSize;
int count=0;
String field=request.getParameter("field")==null?"":request.getParameter("field");
String word=request.getParameter("word")==null?"":request.getParameter("word");
count=dao.guestCount(field, word);
//총페이지 수
int totPage=(count/pageSize)+(count%pageSize==0?0:1);
int pageBlock=3;
int startPage=((currentPage-1)/pageBlock)*pageBlock+1;
int endPage=startPage+pageBlock-1;
if(endPage>totPage) endPage=totPage;
PageUtil pu=new PageUtil();
pu.setCurrentPage(currentPage);
pu.setEndPage(endPage);
pu.setPageBlock(pageBlock);
pu.setStartPage(startPage);
pu.setTotPage(totPage);
pu.setField(field);
pu.setWord(word);
ArrayList<GuestDTO> arr=null;
if(word.equals("")) {
arr=dao.guestList(startRow,endRow);
}else {
arr=dao.guestList(field, word, startRow,endRow);
}
int rowNo=count-((currentPage-1)*pageSize); //매 페이지의 시작번호
request.setAttribute("rowNo", rowNo);
request.setAttribute("pu", pu);
request.setAttribute("guest", arr);
request.setAttribute("count", count);
RequestDispatcher rd=request.getRequestDispatcher("listResult.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<PageUtil.java>
-
리스트의 페이지를 나타내고 싶으면? PageUtil.java 파일을 생성하여 페이지 수 표시에 관련된 변수 선언. getter setter.
package com.guest.model;
public class PageUtil {
private int currentPage;
private int endPage;
private int startPage;
private int totPage;
private int pageBlock;
private String field;
private String word;
public String getField() {
return field == null ? "" : field.trim();
}
public void setField(String field) {
this.field = field;
}
public String getWord() {
return word == null ? "" : word.trim();
}
public void setWord(String word) {
this.word = word;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getTotPage() {
return totPage;
}
public void setTotPage(int totPage) {
this.totPage = totPage;
}
public int getPageBlock() {
return pageBlock;
}
public void setPageBlock(int pageBlock) {
this.pageBlock = pageBlock;
}
}
<view.gb>
-
GuestViewAction.java의 경로는 guestbook/view.gb. JSON 형태로 값을 출력
-
GuestDAO.java에서는 guestView()메소드 완성
package com.guest.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.guest.model.GuestDAO;
import com.guest.model.GuestDTO;
/**
* Servlet implementation class GuestViewAction
*/
@WebServlet("/guestbook/view.gb")
public class GuestViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestViewAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
//void라서 리턴값이 없다. 그래서 JSON형태로 바꿔서 콜백함수를 통해 값을 돌려주는 것
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int num=Integer.parseInt(request.getParameter("num"));
GuestDAO dao=GuestDAO.getInstance();
GuestDTO guest=dao.guestView(num);
//자바 Object을 JSON형태로 바꿔야 한다..
JSONObject obj=new JSONObject();
obj.put("name", guest.getName());
obj.put("content", guest.getContent());
obj.put("created", guest.getCreated());
obj.put("grade", guest.getGrade());
obj.put("ipaddr", guest.getIpaddr());
obj.put("num", guest.getNum());
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(obj.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<delete.gb>
-
GuestDeleteAction.java의 경로 guestbook/delete.gb.
-
$.get 함수를 사용하여 insert.jsp에서 delete.gb 호출
-
delete.gb에서 guestDelete()메소드를 부르고 GuestDAO.java에서 메소드 완성
package com.guest.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.guest.model.GuestDAO;
/**
* Servlet implementation class GuestDeleteAction
*/
@WebServlet("/guestbook/delete.gb")
public class GuestDeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestDeleteAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int num=Integer.parseInt(request.getParameter("num"));
GuestDAO dao=GuestDAO.getInstance();
dao.guestDelete(num);
response.sendRedirect("list.gb");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<login.jsp>
-
로그인 기능 구현. ajax 콜백이 아닌 다른 페이지로 넘어감
-
GuestLoginAction.java의 경로는 guestbook/login.gb.
-
GuestDAO.java에서 guestLoginCheck()메소드 완성 (아이디와 비밀번호가 테이블에 있는지 확인하여 검사)
-
회원이면 insert.jsp로, 회원이 아니면 다시 login.jsp로 가도록
-
session 값인 login이 있으면 삭제가 보이도록, session 값인 login이 없으면 삭제가 보이지 않도록 함. (sessionScope.login!=null)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.gb" method="post">
<label for="userid">ID</label>
<input type="text" id="userid" name="userid">
<label for="pwd">PW</label>
<input type="password" id="pwd" name="pwd">
<input type="submit" value="로그인">
<span style="color:red">${errMsg}</span>
</form>
</body>
</html>
<GuestLoginAction.java>
package com.guest.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.guest.model.GuestDAO;
/**
* Servlet implementation class GuestLoginAction
*/
@WebServlet("/guestbook/login.gb")
public class GuestLoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestLoginAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd=request.getRequestDispatcher("login.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String userid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
GuestDAO dao=GuestDAO.getInstance();
int flag=dao.guestLoginCheck(userid, pwd); //jmember테이블 사용
String path="";
if(flag==0 || flag==1) {
HttpSession session=request.getSession();
session.setAttribute("login", userid);
path="insert.jsp";
}else if(flag==-1) { //회원 아님
request.setAttribute("errMsg", "회원이 아닙니다.");
path="login.jsp";
}else if(flag==2) { //비번 오류
request.setAttribute("errMsg", "비밀번호 오류");
path="login.jsp";
}
RequestDispatcher rd=request.getRequestDispatcher(path);
rd.forward(request, response);
}
}
<GuestLogoutAction.java>
package com.guest.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class GuestLogoutAction
*/
@WebServlet("/guestbook/logout.gb")
public class GuestLogoutAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GuestLogoutAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
session.invalidate();
response.sendRedirect("insert.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
'Learning > JSP' 카테고리의 다른 글
JSP 개인프로젝트-영어 학습 사이트 만들기 (로그인, 회원가입) (0) | 2020.08.18 |
---|---|
파일 전송 (0) | 2020.08.06 |
로그인, 회원가입, 게시판 만들기 2 (0) | 2020.07.30 |
로그인, 회원가입, 게시판 만들기 1 (0) | 2020.07.29 |
서블릿: 출력경로 통일하기 (0) | 2020.07.29 |