상품등록하기
prodInput.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"%>
<jsp:include page="/top.jsp" />
<script>
function selectDCate(upCode){
//alert(upCode);
//ajax로 상위 항목을 가져오자
$.ajax({
type:'get',
url:'downCate.do?upCode='+upCode,
dataType:'json',
cache:false,
success:function(res){
//alert(JSON.stringify(res));
var str="<select id='downCg_code' name='downCg_code'>";
str+="<option value=''>::하위 카테고리::</option>";
$.each(res,function(i,item){
str+="<option value='"+item.downCg_code+"'>";
str+=item.downCg_name;
str+="</option>";
})
str+="</select>";
$('#selectDcg').html(str);
},error:function(err){
alert("error:"+err.status);
}
})
}
$(function(){
$('#prodF').on('submit',function(){
//상위 카테고리코드, 하위 카테고리 코드
if(!$("#upCg_code").val()){
alert('상위 카테고리 선택하세요');
$("#upCg_code").focus();
return false;
}
if(!$("#downCg_code").val()){
alert('하위 카테고리 선택하세요');
$("#downCg_code").focus();
return false;
}
//상품명
if(!$('#pname').val()){
alert('상품명을 입력');
$('#pname').focus();
return false;
}
//가격, 판매가,포인트 숫자 여부
//숫자 여부를 하면 빈문자까지 확인 가능
if(!($('#price').val())){
alert('정가를 입력');
$('#price').focus();
return false;
}
if(isNaN($('#price').val())){
alert('정가는 숫자여야 합니다.');
$('#price').select();
return false;
}
if(!($('#saleprice').val())){
alert('판매가를 입력');
$('#saleprice').focus();
return false;
}
if(isNaN($('#saleprice').val())){
alert('판매가는 숫자여야 합니다.');
$('#saleprice').select();
return false;
}
})
})
</script>
<div class="container">
<div class="row">
<div class="col-md-10 offset-md-1 text-left">
<h1>상품 등록[ADMIN모드]</h1>
<form name="prodF" id="prodF" action="prodInsert.do" method="POST"
enctype="multipart/form-data">
<table class="table table-condensed table-bordered mt-4">
<thead>
<tr class="bg-success">
<th colspan="2">
<h3>:::Product Register:::</h3>
</th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%"><b>카테고리</b></td>
<td width="80%"><select id="upCg_code" name="upCg_Code"
onchange="selectDCate(this.value)">
<option value="">::상위 카테고리::</option>
<c:forEach var="up" items="${upCgList}">
<option value="${up.upCg_code}">${up.upCg_name}</option>
</c:forEach>
</select>
<span id="selectDcg">
<!-- <select name="downCode">
<option value="1">노트북.PC</option>
</select> -->
</span></td>
</tr>
<tr>
<td width="20%"><b>상품명</b></td>
<td width="80%"><input type="text" name="pname" id="pname">
<span style="color: red">
</span></td>
</tr>
<tr>
<td width="20%"><b>제조사</b></td>
<td width="80%"><input type="text" name="pcompany"
id="pcompany"></td>
</tr>
<tr>
<td width="20%"><b>상품스펙</b></td>
<td width="80%"><select name="pspec" id="pspec">
<option value="NEW" selected>NEW</option>
<option value="HIT">HIT</option>
<option value="BEST">BEST</option>
</select></td>
</tr>
<tr>
<td>상품이미지</td>
<td>
<input type="file" name="pimage1"><br>
<input type="file" name="pimage2"><br>
<input type="file" name="pimage3"><br>
</td>
</tr>
<tr>
<td width="20%"><b>상품수량</b></td>
<td width="80%"><input type="number" name="pqty" id="pqty">
개
<span style="color: red">
</span></td>
</td>
</tr>
<tr>
<td width="20%"><b>상품정가</b></td>
<td width="80%">
<input type="number" name="price" id="price">
원
<span style="color: red">
</span>
</td>
</tr>
<tr>
<td width="20%"><b>상품판매가</b></td>
<td width="80%"><input type="text" name="saleprice"
id="saleprice"> 원
<span style="color: red">
</span>
</td>
</tr>
<tr>
<td width="20%"><b>상품설명</b></td>
<td width="80%"><textarea name="pcontents" id="pcontents"
rows="5" cols="60"></textarea></td>
</tr>
<tr>
<td width="20%"><b>포인트</b></td>
<td width="80%"><input type="number" name="point" id="point">
POINT</td>
</tr>
<tr>
<td colspan="2">
<button class="btn btn-success">상품등록</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script>
</script>
<jsp:include page="/foot.jsp" />
ProductInsertAction
package shop.controller;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import common.base.CommonUtil;
import common.controller.AbstractAction;
import shop.domain.ProductVO;
import shop.persistence.ProductDAOMyBatis;
public class ProductInsertAction extends AbstractAction {
@Override
public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
//1.업로드할 디렉토리 절대경로 얻어오기
ServletContext app = req.getServletContext();
String upDir = app.getRealPath("images");
System.out.println(upDir);
//2.이미지파일들 업로드 처리 - cos.jar
MultipartRequest mr
=new MultipartRequest(req,upDir,10*1024*1024,"UTF-8",new DefaultFileRenamePolicy());
//3.사용자가 입력한 값 받기, 유효성 체크
String upCg_code = mr.getParameter("upCg_code");
String downCg_code = mr.getParameter("downCg_code");
String pname = mr.getParameter("pname");
int price = Integer.parseInt(mr.getParameter("price"));
int saleprice = Integer.parseInt(mr.getParameter("saleprice"));
int pqty = Integer.parseInt(mr.getParameter("pqty"));
int point = Integer.parseInt(mr.getParameter("point"));
String pspec = mr.getParameter("pspec");
String pcontents = mr.getParameter("pcontents");
String pcompany = mr.getParameter("pcompany");
String pimage1=mr.getFilesystemName("pimage1");
String pimage2=mr.getFilesystemName("pimage2");
String pimage3=mr.getFilesystemName("pimage3");
//업로드한 파일명과 크기 알아내기
/*Enumeration<String> en=mr.getFileNames();
if(en!=null) {
while(en.hasMoreElements()) {
String param=en.nextElement();
String fname = mr.getFilesystemName(param);
System.out.println(param+"/"+fname);
}
}*/
//4.ProductVO에 담아주기
ProductVO item = new ProductVO(null,upCg_code,downCg_code,pname,pimage1,pimage2,pimage3,price,saleprice,pqty,point,pspec,pcontents,pcompany,null);
//5.DAO의 productInsert(vo) 호출
ProductDAOMyBatis dao = new ProductDAOMyBatis();
int n = dao.productInsert(item);
String msg= (n>0)? "등록 성공":"등록 실패";
String loc= (n>0)? "prodList.do":"javascript:history.back()";
//6.그 결과 메시지 처리
String viewPage=CommonUtil.addMsgLoc(req, msg,loc);
this.setViewPage(viewPage);
this.setRedirect(false);
}
}
ProductDAOMyBatisBase
Mybatis는 자동 commit이 아니다
package shop.persistence;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import common.base.DAOMyBatisBase;
import shop.domain.CategoryVO;
import shop.domain.ProductVO;
public class ProductDAOMyBatis extends DAOMyBatisBase{
private final String NS="common.mapper.ProductMapper";
private SqlSession ses;
public int productInsert(ProductVO item) {
try {
ses=this.getSqlSessionFactory().openSession();
int n = ses.insert(NS+".productInsert",item);
if(n>0) { //트랜잭션 처리
ses.commit();
}else {
ses.rollback();
}
}finally {
close(ses);
}
return 0;
}
}
ProductMapper
<?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="common.mapper.ProductMapper">
<!-- pspec별로 상품정보 가져오기 -->
<select id="selectByPspec" parameterType="string" resultType="Product">
select * from product where pspec=#{value} order by pnum desc
</select>
<!-- 상위 카테고리 목록 가져오기 -->
<select id="getUpCategoryList" resultType="Category">
select * from upCategory order by upCg_code asc
</select>
<select id="getDownCategoryList" resultType="Category" parameterType="string">
select * from downCategory where upCg_code=#{value}
</select>
<insert id="productInsert" parameterType="Product">
insert into product values(product_seq.nextval,#{upCg_code},
#{downCg_code},#{pname},#{pimage1:VARCHAR},#{pimage2:VARCHAR},#{pimage3:VARCHAR},
#{price},#{saleprice:NUMERIC},#{pqty:NUMERIC},#{point:NUMERIC},#{pspec:VARCHAR},
#{pcontents:VARCHAR},#{pcompany:VARCHAR},sysdate)
</insert>
</mapper>
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
NaverAPI사용
naverdeveloper 접속 -> application신청 -> cliend id , pwd 가져오기
요청 URL
JavaScript보안 제약때문에 네이버로 직접 요청을 보낼 수가 없음
Ajax통신은 같은 도메인일 경우 통신할 수 있기때문에 따라서 Ajax통신을 대신할 자바 객체를 이용해서
통신을 해보자 ==> Proxy객체
$('#bt7').click(function(){
var url ="naverBookApi.jsp?query="+encodeURIComponent("사랑과 평과");
$.ajax({
type:'get',
url:url,
dataType:'json',
cache:false,
success:function(res){
//alert(JSON.stringify(res));
//showList(res);
var str="<h2>검색 결과</h2>";
$.each(res.items, function(i,book){
str+=book.title+"<br>";
})
$("#msg").html(str);
},error:function(err){
alert("error: "+err.status);
}
})
})
naverBookApi.jsp
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8" import="ajax.book.*"%>
<%
String query= request.getParameter("query");
if(query==null||query.trim().isEmpty()){
query="Ajax";
}
BookNaverProxy proxy = new BookNaverProxy();
String jsonData = proxy.getData(query);
%>
<%=jsonData%>
BookNaverProxy.java
package ajax.book;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class BookNaverProxy {
public String getData(String keyword) {
String clientId = ""; //애플리케이션 클라이언트 아이디값"
String clientSecret = ""; //애플리케이션 클라이언트 시크릿값"
String text = null;
try {
text = URLEncoder.encode(keyword, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("검색어 인코딩 실패",e);
}
System.out.println(text);
String apiURL = "https://openapi.naver.com/v1/search/book.json?query=" + text; // json 결과
//String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
String responseBody = get(apiURL,requestHeaders);
System.out.println(responseBody);
return responseBody;
}
private static String get(String apiUrl, Map<String, String> requestHeaders){
HttpURLConnection con = connect(apiUrl);
try {
con.setRequestMethod("GET");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
return readBody(con.getInputStream());
} else { // 에러 발생
return readBody(con.getErrorStream());
}
} catch (IOException e) {
throw new RuntimeException("API 요청과 응답 실패", e);
} finally {
con.disconnect();
}
}
private static HttpURLConnection connect(String apiUrl){
try {
URL url = new URL(apiUrl);
return (HttpURLConnection)url.openConnection();
} catch (MalformedURLException e) {
throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
} catch (IOException e) {
throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
}
}
private static String readBody(InputStream body){
try {
InputStreamReader streamReader = new InputStreamReader(body,"UTF-8");
BufferedReader lineReader = new BufferedReader(streamReader);
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
lineReader.close();
streamReader.close();
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
}
}
}
'개발자 > 국비지원 SW' 카테고리의 다른 글
국비지원 78일차 - 네이버 도서 API활용, 페이징처리 (0) | 2020.08.04 |
---|---|
국비지원 77일차 - 쇼핑몰 상품 목록, 상품 정보 ,MyBatis 모듈화 (0) | 2020.08.03 |
국비지원 75일차 - 쇼핑몰 MyBatis 사용하기, Alias, Ajax DB에서 JSON만들기 라이브러리로JSON만들기 (0) | 2020.07.30 |
국비지원 74일차 - LoginFilter, AdminFilter, 쇼핑몰 table, MyBatis 환경설정, Ajax json 정의, 사용방법 (0) | 2020.07.29 |
국비지원 73일차 - ConnectionPool 사용, Ajax 도서검색 기능, GET방식 한글처리, 자동완성 (0) | 2020.07.28 |