sql>tbl_product생성
create table tbl_product(
pid char(11) primary key,
pname varchar(200),
price varchar(100),
image varchar(200),
wdate datetime default now()
);
NaverAPI(class)
package com.example.domain;
import java.io.*;
import java.net.*;
public class NaverAPI {
public static String main(String query,int start) {
String clientId = "r_XLF45OBi3Xw08BTmvq";//애플리케이션 클라이언트 아이디값";
String clientSecret = "DjUKEbgt13";//애플리케이션 클라이언트 시크릿값";
try {
String text = URLEncoder.encode(query, "UTF-8");
String apiURL = "https://openapi.naver.com/v1/search/shop.json";
apiURL += "?query="+ text;
apiURL += "&display=5";
apiURL += "&start=" +start;
//String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Naver-Client-Id", clientId);
con.setRequestProperty("X-Naver-Client-Secret", clientSecret);
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) { // 정상 호출
br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
} else { // 에러 발생
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
return response.toString();
} catch (Exception e) {
System.out.println(e);
return e.toString();
}
}
}
ProductVO(class)
package com.example.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class ProductVO {
private String pid;
private String pname;
private String price;
private String image;
@JsonFormat(pattern="yyyy-MM-dd kk:mm:ss",timezone="Asia/Seoul")
private Date wdate;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public Date getWdate() {
return wdate;
}
public void setWdate(Date wdate) {
this.wdate = wdate;
}
public void setImage(String image) {
this.image = image;
}
@Override
public String toString() {
return "ProductVO [pid=" + pid + ", pname=" + pname + ", price=" + price + ", image=" + image + "]";
}
//ctrl+f int->String ,all누르면 int 타입 String 변환
}
ProductDAO(interface)
package com.example.persistence;
import java.util.List;
import com.example.domain.ProductVO;
import com.example.domain.SearchCriteria;
public interface ProductDAO {
public void insert(ProductVO vo) throws Exception;
public List<ProductVO> list(SearchCriteria cri)throws Exception;
public int total(SearchCriteria cri) throws Exception;
public void delete(String pid) throws Exception;
public void update(ProductVO vo) throws Exception;
}
ProductMapper(xml)
package com.example.persistence;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.domain.ProductVO;
import com.example.domain.SearchCriteria;
@Repository
public class ProductDAOImpl implements ProductDAO{
@Inject
SqlSession session;
private static final String namespace="ProductMapper";
@Override
public void insert(ProductVO vo) throws Exception {
// TODO Auto-generated method stub
session.insert(namespace+".insert",vo);
}
@Override
public List<ProductVO> list(SearchCriteria cri) throws Exception {
// TODO Auto-generated method stub
return session.selectList(namespace+".list",cri);
}
@Override
public int total(SearchCriteria cri) throws Exception {
// TODO Auto-generated method stub
return session.selectOne(namespace+".total",cri);
}
@Override
public void delete(String pid) throws Exception {
// TODO Auto-generated method stub
session.delete(namespace+".delete",pid);
}
@Override
public void update(ProductVO vo) throws Exception {
// TODO Auto-generated method stub
session.update(namespace+".update",vo);
}
}
DBTest(class)
package com.example.web;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.example.domain.ProductVO;
import com.example.domain.SearchCriteria;
import com.example.persistence.ProductDAO;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class DBTest4 {
@Inject
ProductDAO dao;
@Test
public void insert()throws Exception{
ProductVO vo=new ProductVO();
vo.setPid("12345678910");
dao.insert(vo);
}
@Test
public void list()throws Exception{
SearchCriteria cri=new SearchCriteria();
cri.setKeyword("삼성");
dao.list(cri);
}
@Test
public void delete() throws Exception{
dao.delete("20640226142");
}
@Test
public void update() throws Exception{
ProductVO vo=new ProductVO();
vo.setPid("12572381303");
vo.setPname("김경민");
vo.setPrice("100000");
dao.update(vo);
}
}
ProuductDAOImpl(class)
package com.example.persistence;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.domain.ProductVO;
import com.example.domain.SearchCriteria;
@Repository
public class ProductDAOImpl implements ProductDAO{
@Inject
SqlSession session;
private static final String namespace="ProductMapper";
@Override
public void insert(ProductVO vo) throws Exception {
// TODO Auto-generated method stub
session.insert(namespace+".insert",vo);
}
@Override
public List<ProductVO> list(SearchCriteria cri) throws Exception {
// TODO Auto-generated method stub
return session.selectList(namespace+".list",cri);
}
@Override
public int total(SearchCriteria cri) throws Exception {
// TODO Auto-generated method stub
return session.selectOne(namespace+".total",cri);
}
@Override
public void delete(String pid) throws Exception {
// TODO Auto-generated method stub
session.delete(namespace+".delete",pid);
}
@Override
public void update(ProductVO vo) throws Exception {
// TODO Auto-generated method stub
session.update(namespace+".update",vo);
}
}
ProductController(class)
package com.example.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.domain.NaverAPI;
import com.example.domain.PageMaker;
import com.example.domain.ProductVO;
import com.example.domain.SearchCriteria;
import com.example.persistence.ProductDAO;
@RequestMapping("product")
@Controller
public class ProductController {
@Inject
ProductDAO dao;
@RequestMapping("insert")
public String insert(){
return "product/insert";
}
@ResponseBody
@RequestMapping(value="list.json",
produces="application/JSON;charset=UTF-8")
public String listjson(String query,int start){
return NaverAPI.main(query,start);
}
@ResponseBody
@RequestMapping(value="insert",method=RequestMethod.POST)
public void insertPost(ProductVO vo) throws Exception{
//System.out.println(vo.toString());
dao.insert(vo);
}
@RequestMapping("list")
public String list(){
return "product/list";
}
@ResponseBody
@RequestMapping(value="plist.json")
public Map<String, Object> listProduct(SearchCriteria cri) throws Exception{
Map<String, Object> map=new HashMap<String, Object>();
cri.setPerPageNum(5);
PageMaker pm=new PageMaker();
pm.setCri(cri);
pm.setTotalCount(dao.total(cri));
map.put("pm", pm);
map.put("list", dao.list(cri));
return map;
}
@ResponseBody
@RequestMapping("delete")
public void delete(String pid) throws Exception{
dao.delete(pid);
}
@ResponseBody
@RequestMapping("update")
public void update(ProductVO vo) throws Exception{
dao.update(vo);
}
}
product>insert(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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
<link href="${pageContext.request.contextPath}/resources/pro.css" rel="stylesheet">
</head>
<body>
<h1>[상품등록]</h1>
<button class="btnpro" onClick="location.href='list'">등록상품확인</button>
<div class="div-search">
<span>
<input type="checkbox" class="checkbox" id="chkall">
<input type="button" value="상품저장" class="prosave" id="btninsert">
</span>
<span>
<span id="total" style="float:right;margin-bottom:10px;padding-top:5px;margin-right:5px;"></span>
<input type="text" id="query" value="스마트워치" style="width:400px;height:30px;font-size:15px;float:left;margin-top:10px;margin-right:5px;margin:5px 5px 5px 5px;">
<input type="button" value="검색" id="btnsearch" style="padding:5px;background-color: white;float:left; margin-top:5px; width:50Dpx; height:30px; margin-bottom:10px">
</span>
</div>
<table id="tbl" border=1 width=700 class="tbl-pro"></table>
<script id="temp" type="text/x-handlebars-template">
{{#each items}}
<tr class="row">
<td><input type="checkbox" class="chk"></td>
<td><img class="image" width=100 src="{{image}}"></td>
<td class="pid">{{productId}}</td>
<td class="pname">{{{title}}}</td>
<td class="price">{{lprice}}</td>
</tr>
{{/each}}
</script>
<div>
<button id="btnprev" style="margin-top:10px;margin-bottom:10px;width:50px;height:50px;">←</button>
<button id="btnnext" style="margin-bottom:10px;margin-top:10px;width:50px;height:50px;">→</button>
</div>
</body>
<script>
var query=$("#query").val();
//var query=frm.query.value=query;
var start=1;
var total=0;
$("#chkall").on("click",function(){
if($(this).is(":checked")){ //':은 상태'
$("#tbl .row .chk").each(function(){
$(this).prop("checked",true);
});
}else{
$("#tbl .row .chk").each(function(){
$(this).prop("checked",false);
});
}
});
$("#btninsert").on("click",function(){
if(!confirm("선택상품들을(를) 저장하시겠습니까?")) return;
$("#tbl .row .chk:checked").each(function(){
var row=$(this).parent().parent();
var pid=row.find(".pid").html();
var pname=row.find(".pname").html();
var price=row.find(".price").html();
var image=row.find(".image").attr("src");
//alert(pid+"\n"+ pname+"\n"+ price +"\n"+image);
$.ajax({
type:"post",
url:"insert",
data:{"pid":pid,"pname":pname,"price":price,"image":image},
dataType:"json",
success:function(){
alert("success save!");
$("#tbl .row .chk").each(function(){
$(this).prop("checked",false);
});
$("#chkall").prop("checked",false);
getlist();
}
});
});
});
$("#btnnext").on("click",function(){
if(start < total){
start += 5;
getlist();
}
});
$("#btnprev").on("click",function(){
if(start > 1 ){
start -= 5;
getlist();
}
});
getlist();
$("#btnsearch").on("click",function(){
query=$("#query").val();
getlist();
});
/*
$("#query").keyup(function(key){
query=$("#query").val();
getlist();
});
*/
$("#query").keydown(function(key){
if(key.keyCode==13){
query=$("#query").val();
getlist();
}
});
function getlist(){
$.ajax({
type:"get",
url:"list.json",
data:{"query":query,"start":start},
success:function(data){
var temp=Handlebars.compile($("#temp").html());
$("#tbl").html(temp(data));
total=data.total;
$("#total").html("검색수:" + total + "건");
}
});
}
</script>
</html>
product>list(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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link href="${pageContext.request.contextPath}/resources/pro.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<h1>상품목록</h1>
<div class="div-search-list">
<input type="text" id="keyword" style="margin-top:10px;">
<input type="button" id="btnsearch" value="검색">
<span id="total"></span>
</div>
<div>
<button class="btnmy" style="margin-top:12px;" onClick="location.href='insert'">상품등록</button>
</div>
<table id="tbl" width=800 border=1 class="tbl-my-pro"></table>
<script id="temp" type="text/x-handlebars-template">
{{#each list}}
<tr class="row" pid="{{pid}}">
<td>{{pid}}</td>
<td><input type="text"size=30 value="{{{pname}}}" class="pname"></td>
<td><input type="text" value="{{{price}}}" class="price"></td>
<td><img src="{{image}}" width=100></td>
<td><input type="text" value="{{wdate}}"></td>
<td><img cursor="pointer" width=30 src="../resources/cut.png" class="btndel"></td>
<td><button class="btnup">수정</button></td>
</tr>
{{/each}}
</script>
<div id="pagination"></div>
</body>
<script>
var keyword=$("#keyword").val();
var total=0;
var page=1;
$("#tbl").on("click",".row .btnup",function(){
var row=$(this).parent().parent();
var pid=row.attr("pid");
var pname=row.find(".pname").val();
var price=row.find(".price").val();
if(!confirm(pid + "을(를) 수정하시겠습니까?")) return;
//alert(pid + "\n" + pname + "\n" + price);
$.ajax({
type:"get",
url:"update",
data:{"pid":pid,"pname":pname,"price":price},
success:function(){
alert("수정되었다.");
getlist();
}
});
});
$("#tbl").on("click",".row .btndel",function(){
var pid=$(this).parent().parent().attr("pid");
if(!confirm(pid + "을(를) 삭제하시겠습니까?")) return;
$.ajax({
type:"get",
url:"delete",
data:{"pid":pid},
success:function(){
alert("삭제되었다.");
getlist();
}
});
});
$("#keyword").keyup(function(key){
if(key.keyCode==13){
keyword=$("#keyword").val();
page=1;
getlist();
}
});
$("#btnsearch").on("click",function(){
keyword=$("#keyword").val();
getlist();
});
getlist();
function getlist(){
$.ajax({
type:"get",
url:"plist.json",
data:{"keyword":keyword,"page":page},
success:function(data){
//alert("성공?");
var temp=Handlebars.compile($("#temp").html());
$("#tbl").html(temp(data));
total=data.pm.totalCount;
$("#total").html("총검색수:" + total + "건");
var str="";
if(data.pm.prev){
str += "<a href='" + (data.pm.startPage-1) + "'>이전</a>";
}
for(var i=data.pm.startPage; i<=data.pm.endPage; i++){
str += "[<a href='" + i + "'>" + i + "</a>]";
}
if(data.pm.next){
str += "<a href='" + (data.pm.endPage+1) + "'>다음</a>";
}
$("#pagination").html(str);
}
});
$("#pagination").on("click","a",function(event){
event.preventDefault();
page=$(this).attr("href");
getlist();
});
}
</script>
</html>
src>main>webapp>resources>cut.png
구글에 쓰레기 삭제 아이콘 무료 치면 나옴
src>main>webapp>resources>pro.css(css)
@CHARSET "UTF-8";
* {
margin: 0xp;
padding: 0px;
}
.pname{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 100px;
height: 20px;
}
body {
margin: 0xp auto;
text-align: center;
}
input:focus { outline: none; }
.tbl-pro {
margin:20px auto;
}
.div-search {
margin-top:10px;
margin: 20px;
border: 0.5px solid;
width: 700px;
height: 45px;
margin:0px auto;
}
.active{
color:violet;
}
.div-search-list {
margin-top:10px;
margin: 20px;
border: 0.5px solid;
width: 800px;
height: 45px;
margin:0px auto;
}
.checkbox {
float: left;
margin: 15px 0px 15px 15px;
}
.prosave {
padding: 5px;
margin: 10px;
float: left;
background-color: white;
}
a{
text-decoration:none;
color:black;
}
.tbl-my-pro{
margin:20px auto;
}
.btnpro{
margin-bottom:20px;
background-color:white;
padding:5px;
}
.btnmy{
background-color:white;
padding:5px;
}
'spring' 카테고리의 다른 글
맛집목록 만들기 (0) | 2019.11.26 |
---|---|
Transaction 처리 (0) | 2019.11.26 |
게시판에 댓글만들기 (0) | 2019.11.22 |
사용자 게시판 만들기 (0) | 2019.11.22 |
Jstl 게시판 만들기 (0) | 2019.11.22 |