<상세보기>
상세보기는 num이 파라미터 값이다. 그리고 돌아오는 값은 DTO이다.
따라서 ObjectMapper.xml 에서 parameterType, resultType 둘다 써줘야한다.
addrList.jsp에서 다음과 같이 제목을 클릭하면 상세보기로 넘어가도록 함
<td><a href="viewAction.amy?num=${arr.num}">${arr.name}</a></td>
ViewAction.java
package org.addrMy.action;
import java.io.IOException;
import java.util.List;
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.addrMy.config.MybatisManager;
import org.addrMy.model.AddressVO;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* Servlet implementation class ViewAction
*/
@WebServlet("/address_my/viewAction.amy")
public class ViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ViewAction() {
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"));
SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();
SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);
AddressVO vo=sqlSession.selectOne("viewData",num);
request.setAttribute("address", vo);
RequestDispatcher rd=request.getRequestDispatcher("arrView.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);
}
}
addrView.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="updateAction.amy" method="post" name="frm">
<input type="hidden" name="num" value="${address.num}">
<table>
<tr>
<td colspan="2">주소록 수정하기</td>
</tr>
<tr>
<td>이름</td>
<td><input type="text" name="name" value="${address.name}"></td>
</tr>
<tr>
<td>우편번호 </td>
<td><input type="text" name="zipcode" size=10 value="${address.zipcode}">
<input type="button" name="search" value="검색" onclick="zipfinder()"></td>
<tr>
<td>주소
<td><input type="text" name="addr" size=30 value="${address.addr}"></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" name="tel" value="${address.tel}"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="수정" onclick="location.href='updateAction.amy?num=${address.num}'">
<input type="button" value="삭제" onclick="location.href='deleteAction.amy?num=${address.num}'"> <!-- del()이라는 함수를 부른다. -->
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
<수정하기>
상세보기 후 수정 버튼을 눌러서 수정되도록.
받아오는 값들을 다 써주고 Address vo 객체에 담는다. vo 객체를 들고 업데이트를 시켜야한다. 그 후 전체보기로 넘어간다.
UpdateAction.java
package org.addrMy.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 org.addrMy.config.MybatisManager;
import org.addrMy.model.AddressVO;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* Servlet implementation class UpdateAction
*/
@WebServlet("/address_my/updateAction.amy")
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 {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
AddressVO vo=new AddressVO();
vo.setAddr(request.getParameter("addr"));
vo.setName(request.getParameter("name"));
vo.setNum(Integer.parseInt(request.getParameter("num")));
vo.setTel(request.getParameter("tel"));
vo.setZipcode(request.getParameter("zipcode"));
SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();
SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);
sqlSession.update("updateData",vo);
sqlSession.commit();
response.sendRedirect("listAction.amy");
}
}
<삭제하기>
DeleteAction.java
package org.addrMy.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 org.addrMy.config.MybatisManager;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* Servlet implementation class DeleteAction
*/
@WebServlet("/address_my/deleteAction.amy")
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"));
SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();
SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);
sqlSession.delete("deleteData", num);
sqlSession.commit();
response.sendRedirect("listAction.amy");
}
/**
* @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);
}
}
ObjectMapper.xml 주의점
<경로지정 혹은 형 지정>
ObjectMapper.xml 에 resulttype을 쓸때 경로가 아니므로 . 을 쓴다.
resultType="org/addrMy/model/AddressVO" 가 아닌
resultType="org.addrMy.model.AddressVO" 이다.
=>이름이 너무 기므로 별칭으로 대신 써주고 싶다면 Configuration.xml을 수정해야함
<typeAliases>, <typeAlias type="타입이름" alias="별칭">
ObjectMapper.xml에 다음과 같이 쓸 수 있다.
resultType="별칭"
<like 연산자 쓸때 주의점>
sql문에 like가 들어갈때 #{변수}는 홑따옴표를 포함하고 있기 때문에
'%#{dong}%' 이렇게 쓰면 안되고 '%'||#{dong}||'%' 이렇게 써야함.
<우편번호>
이번엔 API를 쓰지 않고 전국 주소 엑셀을 SQL에서 임포트하여 우편번호 DB를 만들었다.
ZipcodeVO.java
package org.addrMy.model;
public class ZipcodeVO {
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 int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
}
zipCheck.jsp에서 비동기함수 $.post를 사용해서 ZipAction.java액션으로 갔다. Mybatis를 수행후 결과값이 List에 담겨있다. 그 값을 가지고 어디로 출력할 것인가? zipCheck.jsp에 다시 돌아온다. 비동기함수는 자신에게 돌아오는 함수이다.
그런데 ZipAction.java에서 dispatcher를 사용하면 다른 페이지로 이동한다.
따라서 JSON 방법을 사용해서 값을 가지고, 데이터를 기다리고 있는 jsp에 가야한다.
예전에는 json simple jar를 이용하여 JSON object, array를 만들었는데.. 이번엔 gson-2.8.5.jar를 maven repository에서 다운받아 사용한다.
https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5
ZipAction.java
package org.addrMy.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
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.addrMy.config.MybatisManager;
import org.addrMy.model.ZipcodeVO;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.google.gson.Gson;
/**
* Servlet implementation class ZipAction
*/
@WebServlet("/address_my/zipAction.amy")
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 {
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");
SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();
SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);
List<ZipcodeVO> zarr=sqlSession.selectList("zipData", dong);
HashMap<String, Object> hm=new HashMap<String, Object>();
hm.put("zarr",zarr);
//java->json형태로 값 출력
Gson gson=new Gson();
String obj=gson.toJson(hm); //자바 오브젝을 json으로 만들어준다.
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(obj.toString());
}
}
zipCheck.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>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#send").click(function(){
if($("#dong").val()==""){
alert("동이름 입력");
return false;
}
$.post("zipAction.amy",
{"dong":$("#dong").val()},
function(data){
var res=JSON.parse(data); //JSON으로 부른게 아니기 때문에 파싱 필요
var htmlStr="<table>";
$.each(res.zarr,function(key,val){
var bunji=val.bunji==null?"":val.bunji;
var gugun=val.gugun==null?"":val.gugun;
htmlStr+="<tr>";
htmlStr+="<td>"+val.zipcode+"</td>";
htmlStr+="<td>"+val.sido+"</td>";
htmlStr+="<td>"+gugun+"</td>";
htmlStr+="<td>"+val.dong+"</td>";
htmlStr+="<td>"+bunji+"</td>";
htmlStr+="</tr>";
});//each
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>
<tr>
<td>*주소를 클릭하면 주소록에 자동 입력 됩니다</td>
</tr>
</table>
<div id="area"></div>
</body>
</html>
<검색>
field값과 word값을 받아와서 selectList에 같이 들고 가야하는데 selectList는 Stirng 두개를 달고 가지 못한다. 따라서 해쉬맵에 field와 word를 저장한다.
그리고 List로 돌아온 검색결과를 뿌리기 위해 해쉬맵을 하나 더 만들어서 저장하고 gson을 이용하여 JSON으로 형변환후 toString으로 다시 돌려준다.
addrList.jsp 에서 검색부분을 삽입
addrList.jsp
<div align="left">
<form name="search" id="search">
<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="btnSearch">
</form>
</div>
검색 버튼을 누르면 검색 실행
$(document).ready(function(){
$("#btnSearch").click(function(){
$.getJSON("searchAction.amy",
{"field":$("#field").val(), "word":$("#word").val()},
function(data){
$("#count").html("개수:"+data.count);
var htmlStr="";
$.each(data.arr, function(key,val){
htmlStr+="<tr>";
htmlStr+="<td>순서</td>";
htmlStr+="<td>"+val.num+"</td>";
htmlStr+="<td>"+val.name+"</td>";
htmlStr+="<td>"+val.addr+"</td>";
htmlStr+="<td>"+val.tel+"</td>";
htmlStr+="<td onclick='javascript:fdelete("+val.num+")'>"+삭제+"</td>";
htmlStr+="</tr>";
});
$("table tbody").html(htmlStr);
}
); //getJSON
})//btnSearch
});//document
SearchAction.java
package org.addrMy.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
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.addrMy.config.MybatisManager;
import org.addrMy.model.AddressVO;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.google.gson.Gson;
/**
* Servlet implementation class SearchAction
*/
@WebServlet("/address_my/searchAction.amy")
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");
HashMap<String, String> map=new HashMap<String, String>();
map.put("field", field);
map.put("word", word);
SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();
SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);
List<AddressVO> arr=sqlSession.selectList("searchData", map);
int count=sqlSession.selectOne("countSearchData",map);
HashMap<String,Object> hm=new HashMap<>();
hm.put("arr",arr);
hm.put("count",count);
Gson gson=new Gson();
String obj=gson.toJson(hm);
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 {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ajax로 삭제하기
addrList.jsp의 결과 테이블 td값에 자바스크립트 함수 포함
<td onclick="fdelete(${arr.num})">삭제</td>
function fdelete(num){
if(confirm("정말 삭제하시겠습니까?")){
$.getJSON("deleteAjaxAction.amy",
{"num":num},
function(data){
$("#count").html("개수:"+data.count);
var htmlStr="";
$.each(data.arr, function(key,val){
htmlStr+="<tr>";
htmlStr+="<td>순서</td>";
htmlStr+="<td>"+val.num+"</td>";
htmlStr+="<td><a href='viewAction.amy?num="+val.num+"'>"+val.name+"</a></td>";
htmlStr+="<td>"+val.addr+"</td>";
htmlStr+="<td>"+val.tel+"</td>";
htmlStr+="<td onclick='fdelete("+val.num+")'>삭제</td>";
htmlStr+="</tr>";
});
$("table tbody").html(htmlStr);
}
)//getJSON
}
}//fdelete
위 사항들을 종합한 ObjectMApper.xml 의 sql문들
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.addrMy.config.ObjectMapper">
<sql id="search">
<where>
<if test="word!=null and field=='name'">
<!-- name like '%'||#{word}||'%' -->
name like '%${word}%'
</if>
<if test="word!=null and field=='tel'">
tel like '%'||#{word}||'%'
</if>
</where>
</sql>
<!-- insert -->
<insert id="insertData" parameterType="org.addrMy.model.AddressVO">
insert into address(num, name, zipcode, addr, tel)
values(address_seq.nextval,#{name},#{zipcode},#{addr},#{tel})
</insert>
<!-- all select -->
<select id="listData" resultType="org.addrMy.model.AddressVO">
select * from address
</select>
<!-- count -->
<select id="countData" resultType="Integer">
select count(*) from address
</select>
<!-- view -->
<select id="viewData" parameterType="Integer" resultType="org.addrMy.model.AddressVO">
select * from address where num=#{num}
</select>
<!-- update -->
<update id="updateData" parameterType="org.addrMy.model.AddressVO">
update address set name=#{name}, zipcode=#{zipcode}, addr=#{addr}, tel=#{tel} where num=#{num}
</update>
<!-- delete -->
<delete id="deleteData" parameterType="Integer">
delete from address where num=#{num}
</delete>
<!-- zipcode select -->
<select id="zipData" parameterType="String" resultType="zipvo">
select * from zipcode where dong like '%'||#{dong}||'%'
</select>
<!-- search -->
<select id="searchData" parameterType="java.util.Map" resultType="org.addrMy.model.AddressVO">
select * from address
<include refid="search"></include>
</select>
<!-- countSearchData -->
<select id="countSearchData" resultType="Integer" parameterType="java.util.Map">
select count(*) from address
<include refid="search"></include>
</select>
</mapper>
'Learning > JSP' 카테고리의 다른 글
안드로이드 어플 만들기 프로젝트 (Moodtracker) (0) | 2020.10.30 |
---|---|
포털사이트에서 필요한 정보 출력하기 (jsoup select) (0) | 2020.08.21 |
Mybatis 연동하기 (주소록 만들기1) (0) | 2020.08.19 |
JSP 개인프로젝트-영어 학습 사이트 만들기 (강의 장바구니 담기 및 삭제) (0) | 2020.08.19 |
JSP 개인프로젝트-영어 학습 사이트 만들기 (수강후기 상세보기 및 수정 삭제, 댓글 입력 및 삭제) (0) | 2020.08.18 |