-
톰캣이 안잡힐때.. 해당 작업중인 Project 마우스 우클릭 properties에서 java build path에서 jre remove 후 add library해서 다시 넣어줌
-
insert.jsp: 주소록 입력 폼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#zipBtn").on("click",function(){
window.open("zip.do","","width=700 height=400");
})
})
</script>
</head>
<body>
<a href="list.do">전체보기</a>
<form action="insert.do" method="post" name="frm">
<table>
<tr>
<td colspan="2">주소록 등록하기</td>
</tr>
<tr>
<td>이름</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>우편번호</td>
<td><input type="text" name="zipcode" id="zipcode" size=7>
<input type="button" value="검색" id="zipBtn">
</td>
</tr>
<tr>
<td>주소</td>
<td><input type="text" name="addr" id="addr" size=50></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" name="tel"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="등록">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
-
InsertAction.java: 주소록 등록 관련 서블릿
package com.address.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.address.model.SAddressDAO;
import com.address.model.SAddressDTO;
/**
* Servlet implementation class InsertAction
*/
@WebServlet("/address/insert.do")
public class InsertAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InsertAction() {
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");
SAddressDTO dto = new SAddressDTO();
dto.setAddr(request.getParameter("addr"));
dto.setName(request.getParameter("name"));
dto.setTel(request.getParameter("tel"));
dto.setZipcode(request.getParameter("zipcode"));
SAddressDAO dao = SAddressDAO.getInstance();
dao.insertAddress(dto);
response.sendRedirect("list.do");
}
}
-
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" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<table>
<div align="right">
<a href="insert.do">회원등록 </a>/주소록 개수: <span id="cntSpan">${count}</span>
</div>
<thead>
<tr>
<td>번호</td>
<td>이름</td>
<td>주소</td>
<td>전화번호</td>
</tr>
</thead>
<tbody>
<c:forEach items="${listArr}" var="address">
<tr>
<td>${address.num}</td>
<td><a href="detail.do?num=${address.num}">${address.name }</a></td>
<td>${address.addr}</td>
<td>${address.tel}</td>
</tr>
</c:forEach>
</tbody>
</table>
<select name="field" id="field">
<option value="name">이름</option>
<option value="tel">전화</option>
</select>
<input type="text" name="word" id="word">
<input type="button" value="검색" id="searchBtn">
<script type="text/javascript">
$("#searchBtn").click(function(){
if($("#word").val()==""){
alert("검색어를 입력하세요");
$("#word").focus();
return false;
}
$.getJSON("search.do",
{"field":$("#field").val(),
"word":$("#word").val()},
function(data){
var htmlStr="";
$.each(data.searchArr,function(key,val){
htmlStr+="<tr>";
htmlStr+="<td>"+val.num+"</td>";
htmlStr+="<td>"+val.name+"</td>";
htmlStr+="<td>"+val.addr+"</td>";
htmlStr+="<td>"+val.tel+"</td>";
htmlStr+="</tr>"
})//each
$("table tbody").html(htmlStr);
$("#cntSpan").text(data.searchCount.scount);
}//콜백함수
)//getJSON
})//searchBtn
</script>
</body>
</html>
-
ListAction.java: 전체보기 서블릿 (list.jsp가 아니라 이 파일을 실행해야 함)
package com.address.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.address.model.SAddressDAO;
import com.address.model.SAddressDTO;
/**
* Servlet implementation class ListAction
*/
@WebServlet("/address/list.do")
public class ListAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ListAction() {
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");
SAddressDAO dao = SAddressDAO.getInstance();
int count=dao.getCount();
ArrayList<SAddressDTO> arr =dao.addressList();
request.setAttribute("listArr", arr);
request.setAttribute("count", count);
RequestDispatcher rd = request.getRequestDispatcher("list.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
-
detail.jsp: 주소록 상세보기 및 수정하기 폼
<%@ 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="update.do" method="post" name="frm">
<input type="hidden" name="num" value="${dto.num}">
<table>
<tr>
<td colspan="2">주소록 수정하기</td>
</tr>
<tr>
<td>이름</td>
<td><input type="text" name="name"
value="${dto.name}"></td>
</tr>
<tr>
<td>우편번호 </td>
<td><input type="text" name="zipcode" size=10
value="${dto.zipcode}">
<input type="button" name="search" value="검색" onclick="zipfinder()"></td>
<tr>
<td>주소
<td><input type="text" name="addr" size=30
value="${dto.addr}"></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" name="tel"
value="${dto.tel}"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="수정" onclick="location.href='update.do?num=${dto.num}'">
<input type="button" value="삭제" onclick="location.href='delete.do?num=${dto.num}'"> <!-- del()이라는 함수를 부른다. -->
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
-
DetailAction.java 만들기: 패키지 우클릭-New-Servlet
-
DeatilAction - Next>
-
Edit... 클릭
-
url mappings를 /address/detail.do 로 설정. detail.do는 어디서 나온 것이냐?
-
list.jsp에서 name에 링크를 걸고 클릭했을때 넘어가는 경로 이름.
-
다시 Servlet 만드는 창으로 와서.. doPost, doGet등 만들기 원하는 부분에 체크
-
DetailAction.java에 자동으로 불러온 모습
package com.address.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.address.model.SAddressDAO;
import com.address.model.SAddressDTO;
/**
* Servlet implementation class DetailAction
*/
@WebServlet("/address/detail.do")
public class DetailAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DetailAction() {
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"));
SAddressDAO dao = SAddressDAO.getInstance();
SAddressDTO dto = dao.addressDetail(num);
request.setAttribute("dto", dto);
RequestDispatcher rd=request.getRequestDispatcher("detail.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
-
같은 방식으로 DeleteAction.java를 서블릿으로 생성. url mappings는 /address/delte.do
package com.address.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.address.model.SAddressDAO;
/**
* Servlet implementation class DeleteAction
*/
@WebServlet("/address/delete.do")
public class DeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteAction() {
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"));
SAddressDAO dao=SAddressDAO.getInstance();
dao.addressDelete(num);
response.sendRedirect("list.do");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
-
메소드: SAddressDAO의 addressDelete(num)
-
list.do를 호출하여 list.jsp로
-
UpdateAction.java 서블릿 생성. url mappings는 /address/update.do
package com.address.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.address.model.SAddressDAO;
import com.address.model.SAddressDTO;
/**
* Servlet implementation class UpdateAction
*/
@WebServlet("/address/update.do")
public class UpdateAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateAction() {
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");
SAddressDTO dto=new SAddressDTO();
dto.setNum(Integer.parseInt(request.getParameter("num")));
dto.setAddr(request.getParameter("addr"));
dto.setName(request.getParameter("name"));
dto.setTel(request.getParameter("tel"));
dto.setZipcode(request.getParameter("zipcode"));
SAddressDAO dao=SAddressDAO.getInstance();
dao.addressUpdate(dto);
response.sendRedirect("list.do");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
-
메소드: SAddressDAO의 addressUpdate(SAddressDTO dto)
-
우편번호 검색하기. insert.jsp에 우편번호 검색 버튼에 id="zipBtn". 상단에 자바스크립트 불러오고 zipBtn을 눌렀을때 window.open으로 zip.do 불러오도록 하기
-
서블릿으로 ZipAction.java 생성. url mappings는 /address/zip.do
package com.address.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.address.model.SAddressDAO;
import com.address.model.ZipcodeDTO;
/**
* Servlet implementation class ZipAction
*/
@WebServlet("/address/zip.do")
public class ZipAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ZipAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.sendRedirect("zipCheck.jsp");
RequestDispatcher rd=request.getRequestDispatcher("zipCheck.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 dong=request.getParameter("dong");
SAddressDAO dao=SAddressDAO.getInstance();
ArrayList<ZipcodeDTO>arr=dao.zipSearch(dong);
JSONObject mainObj=new JSONObject();
JSONArray jarr=new JSONArray();
for (ZipcodeDTO zip:arr) {
JSONObject obj=new JSONObject();
obj.put("zipcode", zip.getZipcode());
obj.put("sido", zip.getSido());
obj.put("gugun", zip.getGugun());
obj.put("dong",zip.getDong());
obj.put("bunji",zip.getBunji());
jarr.add(obj);
}
mainObj.put("jarr",jarr);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(mainObj.toString());
}
}
-
doGet에서 zipCheck.jsp를 디스패처로 호출
-
zipCheck.jsp: 검색 버튼 id는 send라 명명. 제이슨 형식으로 zip.do 부르기
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#send").click(function(){
if($("#dong").val()==""){
alert("동이름을 입력하세요");
$("#dong").focus();
return false;
}
$.post("zip.do",{"dong":$("#dong").val()},
function(data){
data=JSON.parse(data); //파싱
var htmlStr="";
htmlStr+="<table>";
for(var i=0;i<data.jarr.length;i++){
htmlStr+="<tr>";
htmlStr+="<td>"+data.jarr[i].zipcode+"</td>";
htmlStr+="<td>"+data.jarr[i].sido+"</td>";
htmlStr+="<td>"+data.jarr[i].gugun+"</td>";
htmlStr+="<td>"+data.jarr[i].dong+"</td>";
htmlStr+="<td>"+data.jarr[i].bunji+"</td>";
htmlStr+="</tr>";
}
htmlStr+="</table>";
$("#area").html(htmlStr);
}
);//post
}) //send
$("#area").on("click","tr",function(){
var address = $("td:eq(1)",this).text()+" " +
$("td:eq(2)",this).text()+" " +
$("td:eq(3)",this).text()+" " +
$("td:eq(4)",this).text();
$(opener.document).find("#zipcode").val($("td:eq(0)",this).text());
$(opener.document).find("#addr").val(address);
self.close();
}); //area
}) //document
</script>
</head>
<body>
<table>
<tr>
<td> 동이름입력: <input type="text" name="dong" id="dong">
<input type="button" value="검색" id="send">
</td>
</tr>
</table>
<div id="area"></div>
</body>
</html>
-
메소드: SAddressDAO의 zipSearch
-
주소 bunji 부분에 null 값이 나오는게 싫다면
-
이클립스 메뉴 window-preference-java-code style-code templates-getter body-edit
-
return ${field}==null?"":${field}.trim(); 으로 고쳐줌
-
json-simple-1.1.1.jar파일을 lib에 넣는다.
-
자바스크립트가 인식할 수 있는 코드로 바꿔주기위해 필요함
-
검색 SearchAction.java
package com.address.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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.address.model.SAddressDAO;
import com.address.model.SAddressDTO;
/**
* Servlet implementation class SearchAction
*/
@WebServlet("/address/search.do")
public class SearchAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchAction() {
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");
String field=request.getParameter("field");
String word=request.getParameter("word");
SAddressDAO dao=SAddressDAO.getInstance();
ArrayList<SAddressDTO> arr=dao.addressSearch(field, word);
int count=dao.searchCount(field,word);
JSONObject mainObj=new JSONObject();
JSONArray jarr=new JSONArray();
for(SAddressDTO dto:arr) {
JSONObject obj=new JSONObject();
obj.put("num", dto.getNum());
obj.put("name", dto.getName());
obj.put("addr", dto.getAddr());
obj.put("tel", dto.getTel());
obj.put("zipcode", dto.getZipcode());
jarr.add(obj);
}
JSONObject objCount=new JSONObject();
objCount.put("scount", count);
mainObj.put("searchArr", jarr);
mainObj.put("searchCount", objCount);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(mainObj.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
-
SAddressDAO.java
package com.address.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 SAddressDAO {
private static SAddressDAO instance = new SAddressDAO();
public static SAddressDAO 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/member");
return ds.getConnection();
}
//추가
public void insertAddress(SAddressDTO ad) {
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
String sql = "insert into address "
+ "values(address_seq.nextval,?,?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, ad.getName());
ps.setString(2, ad.getZipcode());
ps.setString(3, ad.getAddr());
ps.setString(4, ad.getTel());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps);
}
}
//상세보기
public SAddressDTO addressDetail(int num) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
SAddressDTO dto=null;
try {
con=getConnection();
st=con.createStatement();
String sql="select * from address where num="+num;
rs=st.executeQuery(sql);
if(rs.next()) {
dto=new SAddressDTO();
dto.setNum(rs.getInt("num"));
dto.setAddr(rs.getString("addr"));
dto.setName(rs.getString("name"));
dto.setNum(rs.getLong("num"));
dto.setTel(rs.getString("tel"));
dto.setZipcode(rs.getString("zipcode"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return dto;
}
//전체보기
public ArrayList<SAddressDTO> addressList(){
Connection con = null;
Statement st = null;
ResultSet rs = null;
ArrayList<SAddressDTO> arr = new ArrayList<>();
try {
con = getConnection();
String sql ="select * from address";
st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next()) {
SAddressDTO ad= new SAddressDTO();
ad.setAddr(rs.getString("addr"));
ad.setName(rs.getString("name"));
ad.setNum(rs.getLong("num"));
ad.setTel(rs.getString("tel"));
ad.setZipcode(rs.getString("zipcode"));
arr.add(ad);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
closeConnection(con, st, rs);
}
return arr;
}
//삭제하기
public void addressDelete(int num) {
Connection con=null;
Statement st=null;
try {
con=getConnection();
st=con.createStatement();
String sql="delete from address where num="+num;
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, null);
}
}
//수정하기
public SAddressDTO addressUpdate(SAddressDTO dto) {
Connection con=null;
PreparedStatement ps=null;
try {
con=getConnection();
String sql="update address set name=?, zipcode=?, tel=?, addr=? where num=?";
ps=con.prepareStatement(sql);
ps.setString(1, dto.getName());
ps.setString(2, dto.getZipcode());
ps.setString(3, dto.getTel());
ps.setString(4, dto.getAddr());
ps.setLong(5, dto.getNum());
ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
closeConnection(con, ps);
}
return dto;
}
//개수출력
public int getCount() {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int count=0;
try {
con=getConnection();
String sql="select count(*) from address";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) {
count=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
//검색 개수출력
public int searchCount(String field, String word) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int count=0;
try {
con=getConnection();
String sql="select count(*) from address where "+field+" like '%"+word+"%'";
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 ArrayList<ZipcodeDTO> zipSearch(String dong){
Connection con = null;
Statement st = null;
ResultSet rs = null;
ArrayList<ZipcodeDTO> arr = new ArrayList<>();
try {
con = getConnection();
String sql ="select * from zipcode where dong like '%"+dong+"%'";
st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next()) {
ZipcodeDTO zip= new ZipcodeDTO();
zip.setBunji(rs.getString("bunji"));
zip.setDong(rs.getString("dong"));
zip.setGugun(rs.getString("gugun"));
zip.setSido(rs.getString("sido"));
zip.setZipcode(rs.getString("zipcode"));
arr.add(zip);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
closeConnection(con, st, rs);
}
return arr;
}
//검색
public ArrayList<SAddressDTO > addressSearch(String field, String word) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
ArrayList<SAddressDTO> arr=new ArrayList<SAddressDTO>();
try {
con=getConnection();
String sql="select * from address where "+field+" like '%"+word+"%'";
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next()) {
SAddressDTO sd=new SAddressDTO();
sd.setNum(rs.getInt("num"));
sd.setName(rs.getString("name"));
sd.setAddr(rs.getString("addr"));
sd.setTel(rs.getString("tel"));
sd.setZipcode(rs.getString("zipcode"));
arr.add(sd);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return arr;
}
//닫기
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 (rs != null)
rs.close();
if (st != null)
st.close();
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-
SAddressDTO.java
package com.address.model;
public class SAddressDTO {
private long num;
private String name;
private String zipcode;
private String tel;
private String addr;
public long getNum() {
return num;
}
public void setNum(long num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
-
ZipcodeDTO.java
package com.address.model;
public class ZipcodeDTO {
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String bunji;
private int seq;
public String getZipcode() {
return zipcode == null ? "" : zipcode.trim();
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getSido() {
return sido == null ? "" : sido.trim();
}
public void setSido(String sido) {
this.sido = sido;
}
public String getGugun() {
return gugun == null ? "" : gugun.trim();
}
public void setGugun(String gugun) {
this.gugun = gugun;
}
public String getDong() {
return dong == null ? "" : dong.trim();
}
public void setDong(String dong) {
this.dong = dong;
}
public String getBunji() {
return bunji == null ? "" : bunji.trim();
}
public void setBunji(String bunji) {
this.bunji = bunji;
}
public void setSeq(int seq) {
this.seq = seq;
}
}
'Learning > JSP' 카테고리의 다른 글
로그인, 회원가입, 게시판 만들기 1 (0) | 2020.07.29 |
---|---|
서블릿: 출력경로 통일하기 (0) | 2020.07.29 |
JSTL (0) | 2020.07.27 |
서블릿 (0) | 2020.07.27 |
게시판 2 (0) | 2020.07.23 |