Data Scientist 옌

매일 발전하는 IT문제해결사

국비지원교육 (22.01-22.07)/강의노트

22-05-13(금) 074일차 [Oracle, Spring Framework, Mybatis Framework] JOIN, 상품 등록 페이지 만들기(Insert)

옌炎 2022. 6. 17. 18:59
728x90

수업내용


1교시 (09:30-10:20)

  • JOIN
SELECT EMPNO, ENAME, JOB, MGR FROM EMP;

-- 내가 짠 코드
SELECT A.EMPNO, A.ENAME, A.MGR, B.ENAME AS MANAGER
FROM EMP A
JOIN EMP B ON A.MGR = B.EMPNO;

SELECT * 
FROM   EMP A, EMP B
WHERE  A.MGR = B.EMPNO;

SELECT A.*, B.* 
FROM   EMP A, EMP B
WHERE  A.MGR = B.EMPNO;

SELECT A.ENAME, B.ENAME 
FROM   EMP A, EMP B
WHERE  A.MGR = B.EMPNO;

SELECT * FROM EMP WHERE MGR = 
(SELECT MGR FROM EMP WHERE ENAME = 'FORD');

SELECT * FROM EMP WHERE EMPNO = 
(SELECT MGR FROM EMP WHERE ENAME = 'FORD');

2교시 (10:30-11:20)

  • JOIN
SELECT A.ENAME || ' 사원의 상사(매니저)는 ' || B.ENAME  || ' 이다'
FROM   EMP A, EMP B
WHERE  A.MGR = B.EMPNO;

-- 상사(매니저)가 없는 사원을 구하시오 ? 
SELECT MGR FROM EMP;
SELECT EMPNO, ENAME, JOB, MGR FROM EMP;

SELECT * FROM EMP WHERE MGR = NULL;
SELECT * FROM EMP WHERE MGR IS NULL;
SELECT * FROM EMP WHERE MGR IS NOT NULL;

SELECT * FROM SALGRADE;
SELECT SAL FROM EMP;

SELECT A.EMPNO, A.ENAME, A.SAL * 50 , B.GRADE
FROM   EMP A, SALGRADE B
WHERE  A.SAL >= B.LOSAL
AND    A.SAL <= B.HISAL;


--서브쿼리 
--SELECT : 셀렉트 절 
--    SELECT * FROM DUAL; : 스칼라 서브쿼리 : 셀렉트 절에 SELECT 구문을 사용하는 것 
--      일부 OUTER JOIN 효과가 있다. 
--FROM : 프럼 절 
--    SELECT * FROM DUAL; : 인라인 뷰 서브쿼리 : 프럼 절에 SELECT 구문을 사용하는 것
--      인라인 뷰 서브쿼리를 사용하는 이유는 
--      테이블에 있는 전체 데이터를 사용하지 않고 
--      그 조건에 필요한 컬럼만 먼저 추출해서 사용하기 위해서 
--      파일의 크기를 줄이기 위해서 사용하는 것 
--      INLINE VIEW SUBQUERY 는 INNSER JOIN 효과가 있다. 
--WHERE : 웨어 절 
--    SELECT * FROM DUAL; : 서브쿼리 : 웨어 절에 SELECT 구문을 사용하는 것

--서브쿼리 유형
--단일 행(Single-Row) 서브쿼리
--다중 행(Multi-Row) 서브쿼리
--다중 열(컬럼)(Multi-Column) 서브쿼리 
--인라인 뷰(Inline view) 서브쿼리
--스칼라(Scala) 서브쿼리

3교시 (11:30-12:20)

  • 상품 등록 만들기

4교시 (12:30-13:20)

  • 상품 등록 만들기

5교시 (14:30-15:20)

  • kosmoSpring 프로젝트를 위한 설치 및 환경설정
    이클립스 스프링 설치

    1. 이클립스 설치 및 워크 스페이스 세팅
    ----------------------------------
    C:\00.KOSMO108\30.Web\eclipse_web <-- 이클립스 
    C:\00.KOSMO108\30.Web\eclipse_web_work <-- 이클립스 워크 스페이스 

    C:\00.KOSMO108\90.Download\eclipse\eclipse-jee-2020-06-R-win32-x86_64 폴더에서 eclipse 폴더 카피해서 
    C:\00.KOSMO108\30.Web\eclipse_web 폴더에 eclpise 폴더를 복사하기 <-- 이클립스 설치 

    C:\00.KOSMO108\30.Web\eclipse_web\eclipse\eclipse.exe 실행
    C:\00.KOSMO108\30.Web\eclipse_web_work 워크스페이스 설정하기


    2. 이클립스 인코딩 세팅하기 UTF-8
    --------------------------------
    인코딩 종류 : UTF-8, EUC-KR, KSC5601, ISO-8859-1

    Window - Preferences - General - Content Types - Java Class File - Default encoding : UTF-8  Update
                           General - Workspace - Text file encoding -  Other - UTF-8 Apply
                           General - Editors - Text Editors - Spelling - Encoding - Default(UTF-8) 체크 Apply 
                           General - Web Browser - Use external web browser 체크
                               External web browsers: Chrome 체크 Apply
    Web - CSS Files - Encoding - ISO 10646/Unicode(UTF-8) Apply
    Web - HTML Files - Encoding - ISO 10646/Unicode(UTF-8) Apply
    Web - JSP Files - Encoding - ISO 10646/Unicode(UTF-8) Apply
    XML - XML Files - Encoding - ISO 10646/Unicode(UTF-8) Apply

    3. jdk 이클립스 플러그인 확인하기 
    -----------------------------
    Window - Preferences - Java - installed JREs - jdk 또는 jre 이 세팅이 됬는지 확인하기 

    4. tomcat 이클립스에 플러그 인 하기 
    ----------------------------------
    Window - Preferences - Server - Runtime Enviorments - 우측에 있는 Add.. 버튼 클릭 
    New Server Runtime Enviorments 창에서 Apache Tomcat v8.5 선택 Next
    Tomcat Server 창 에서 Tomcat installation direcory : Browse 버튼 클릭
    C:\Program Files\Apache Software Foundation\Tomcat 8.5 선택 하고 Finish
    Apply and Close

    이클립스 하단에 Servers 탭 (Window - Show View - Servers 선택)
    No servers are available. Click this link to create a new server... 링크 클릭
    Define a New Server 창에서 
    Select the server type: Tomcat v8.5 Server 선택하고 Finish 클릭 

    Project Explorer 창에
    Servers 폴더가 생성된다.  <--   이클립스에 tomcat 플러그이 완성된 것이다. 

    5. STS 플러그인 하기
    ---------------------------
    Marketplace에서 플러그인 하기
    이클립스 메뉴에서 Help 누르기
    Eclipse Marketplace.. 누르기
    Eclipse Marketplace 창에서
    Find 텍스트필드 : sts 키인하고 Go 버튼 누르기
    검색된 sts 플러그인 중에서
    Spring Tools 3(Standalone Edition) 3.9.14.RELEASE
    에 있는 install 버튼 누르기
    Confirm Selected Features 창에서 Confirm 버튼 누르기
    파일 다운로드 하나라 시간이 걸린다
    다운로드가 다 되면
    Riview License 창이 뜬다.
    I accpet the terms of the license agreements
    래디오 버튼 체크하면 Finish 버튼이 활성화됨
    Finish 버튼 누르기
    이클립스에 파일 다운로드하면서 설치 작업을 오래 한다.
    중간에 팝업이 뜨면 OK하고 이클립스가 재시작한다.


    6. 프로젝트 만들기 : Dynamic Web Project
    -----------------------------------------
    스프링 프로젝트 이름 : kosmoSpring
    File -> New -> Dynamic Web Project 선택하기
    Dynamic Web Project 창 Project name : kosmoSpring입력하고 Next 버튼 클릭
    Java 창 아래에 있는 Default output folder 아래 텍스트 필드에서
    build/classes --> WebContent\WEB-INF\classes 변경하고 Next 버튼 클릭하기
    -- testSpring\WebContent\WEB-INF\classes
    Web Module 창에서
    Generate web.xml deployment descripter 체크박스 체크하고 Finish 버튼 누르기
    Project Explorer에
    testSpring 프로젝트가 생성된다.
    testSpring 프로젝트에 마우스로 우클릭하면
    아래에 Spring 메뉴 아이템이 보인다.
    Spring 메뉴 아이템에 마우스를 롤오버해서 Add Spring Project Nature 클릭하면
    testSpring 프로젝트 폴더에 파란색 S 이미지가 보인다.


    7. 수동으로 라이브러리 포팅하기
    ------------------------------
    Context/WEB-INF/lib 폴더에 포팅하고자 하는 라이브러리를 복사해둔다.

    스프링 라이브러리 21개


    스프링 + 마이바티스 17개

    spring library
    spring-aop-3.2.9.RELEASE.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-context-3.2.9.RELEASE.jar
    spring-context-support-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar
    spring-expression-3.2.9.RELEASE.jar
    spring-jdbc-3.2.9.RELEASE.jar
    spring-tx-3.2.9.RELEASE.jar
    spring-web-3.2.9.RELEASE.jar
    spring-webmvc-3.2.9.RELEASE.jar

    mybatis library
    mybatis-spring-1.2.2.jar <-- Spring + Mybatis 연결 library
    mybatis-3.2.4.jar <-- Mybatis Framework library

    JDBC
    ojdbc6.jar

    log4j
    log4j-1.2.17.jar

    jstl
    jstl.jar
    standard.jar

    스프링로그
    commons-logging-1.1.2.jar


    Context 우클릭 Build Path - Configure Build Path
    Properties for firstWeb 창에서 -  Java Build Path - 
    Libraries 탭 선택하고 우측에 Add External JARs... 버튼 클릭 
     폴더에서 포팅할 라이브러리 전체 선택 하고 
    Java Build Path 창에서 Apply and Close 클릭 
    Context 
     Referenced Libaries 에 라이브러리가 포팅된다.


    8. 설정 확인
    ---------------
    Servers - Tomcat v8.5 Server at localhost-config
    web.xml
    server.xml
    context.xml 추가

    WebContent - WEB-INF - web.xml 추가
    log4j.xml 복사 해두기

    WebContent - WEB-INF 우클릭 - New -  Other...
    spring Bean Configuration File - spring-servlet.xml 키인

    beans, c, context, lang, mvc, p를 선택하여 finish

            spring-servlet.xml 추가

            beans, context, tx를 선택하여 finish

        servlet-context.xml 추가
  • context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <Resource 	auth="Container" 				 
				maxActive="100" 
				maxIdle="30" 
				maxWait="10000"  
				type="javax.sql.DataSource" 
				name="jdbc/jndi_spring_orclKSY00"
				driverClassName="oracle.jdbc.driver.OracleDriver"
				url="jdbc:oracle:thin:@127.0.0.1:1521:orclKSY00"
				username="scott" 
				password="tiger" />
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>
  • spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:c="http://www.springframework.org/schema/c"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:lang="http://www.springframework.org/schema/lang"
		xmlns:mvc="http://www.springframework.org/schema/mvc"
		xmlns:p="http://www.springframework.org/schema/p"
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
							http://www.springframework.org/schema/beans/spring-beans.xsd
							http://www.springframework.org/schema/context 
							http://www.springframework.org/schema/context/spring-context.xsd
							http://www.springframework.org/schema/lang 
							http://www.springframework.org/schema/lang/spring-lang.xsd
							http://www.springframework.org/schema/mvc 
							http://www.springframework.org/schema/mvc/spring-mvc.xsd">

		<mvc:annotation-driven />	
		<context:component-scan base-package="a.b.c.com.**" />	
		<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
			<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
			<property name="prefix" value="/WEB-INF/view/" />
			<property name="suffix" value=".jsp" />
		</bean>	
		
		<!-- 마이바티스 환경설정 파일 불러오기  -->
		<import resource="servlet-context.xml"/>	
</beans>

  • servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
							http://www.springframework.org/schema/beans/spring-beans.xsd
							http://www.springframework.org/schema/context 
							http://www.springframework.org/schema/context/spring-context.xsd
							http://www.springframework.org/schema/tx 
							http://www.springframework.org/schema/tx/spring-tx.xsd">

		<!-- 데이터 소스 연결하기 context.xml jdbc/jndi_spring_orclHBE00 -->
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="java:comp/env/jdbc/jndi_spring_orclKSY00"></property>
	</bean>							

	<!-- 마이바티스 쿼리문 찾아서 연결하기  -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!-- 
			classpath: == springEmp/Java Resources/src : /WEB-INF/classes/ 
			mybatisconfig 폴더 만들기 
			springEmp/Java Resources/src 에서 우클릭 New -> Other -> Select a wizard -> folder 검색
		 -->	 	
		<property name="configLocation" value="classpath:/mybatisconfig/mybatis-config.xml"></property>		
		<property name="mapperLocations" value="classpath:/mybatisquery/*.xml"></property>				
	</bean>
	
	<!-- 트랜잭션 처리 : spring-mybatis 에서는 개발자가 tx 처리에 관여하지 않는다. -->
	<bean id="transactionManager" 
	      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
			<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- DAO 또는 Mapper 찾기  -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage"><value>a.b.c.com.**.dao</value></property>
	</bean>	
</beans>
  • mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
		  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<typeAliases>
		<typeAlias type="a.b.c.com.kosmo.product.vo.KosmoProductVO" alias="kosmoproductvo"/>
	</typeAliases>
</configuration>
  • spring_chabun.xml
<?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="a.b.c.com.kosmo.common.dao.SpringChabunDAO">

<select id="getProductChabun" resultType="kosmoproductvo">
	SELECT NVL(MAX(SUBSTR(A.KPNUM, -4)), 0) + 1  KPNUM FROM KOSMO_PRODUCT A
</select>

</mapper>
  • spring_product.xml
<?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="a.b.c.com.kosmo.product.dao.KosmoProductDAO">

<insert id="kosmoProductInsert" parameterType="kosmoproductvo" >
	
	INSERT INTO KOSMO_PRODUCT (	KPNUM
							   ,KPID
							   ,KPNAME
							   ,KPCOMPANY
							   ,KPFILE
							   ,KPCNT
							   ,KPPRICE
							   ,KPDESC
							   ,DELETEYN
							   ,INSERTDATE
							   ,UPDATEDATE)
            			VALUES( #{kpnum}
							   ,#{kpid}
							   ,#{kpname}
							   ,#{kpcompany}
							   ,#{kpfile}
							   ,#{kpcnt}
							   ,#{kpprice}
							   ,#{kpdesc}
							   ,'Y'
							   ,SYSDATE
							   ,SYSDATE)
</insert>

</mapper>

6교시 (15:30-16:20)

  • DateFormatUtil.java
package a.b.c.com.kosmo.common;

import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class DateFormatUtil {

	public static String ymdFormat() {
		return new SimpleDateFormat("yyyyMMdd").format(new Date());
	}
	
	public static String ymFormat() {
		return new SimpleDateFormat("yyyyMM").format(new Date());
	}
	
	public static String yFormat() {
		return new SimpleDateFormat("yyyy").format(new Date());
	}
	
	public static String ymdFormats(String ymdFlag) {
		
		String y ="";
		if ("D".equals(ymdFlag.toUpperCase())) {
			y = DateFormatUtil.ymdFormat();
		}
		if ("M".equals(ymdFlag.toUpperCase())) {
			y = DateFormatUtil.ymFormat();
		}
		if ("Y".equals(ymdFlag.toUpperCase())) {
			y = DateFormatUtil.yFormat();
		}
		if ("N".equals(ymdFlag.toUpperCase())) {
			y = "";
		}
		
		return y;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}
  • ChabunUtil.java
package a.b.c.com.kosmo.common;

public abstract class ChabunUtil {

	public static final String BIZ_GUBUN_P = "P";
	
	// type : D : YYYYMMDD, M : YYYYMM, Y : YYYY, N;
	public static String numPad(String t, String c) {
		
		for (int i=c.length(); i < 4; i++) {
			c = "0" + c;
		}
		String ymd = DateFormatUtil.ymdFormats(t);
		
		return ymd.concat(c);
	}
	
	public static String getProductChabun(String type, String memNum) {
		return BIZ_GUBUN_P.concat(ChabunUtil.numPad(type, memNum));
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String c = "1";
		System.out.println(">>> : " + ChabunUtil.getProductChabun("m", c));
	}
}
  • CommonUtils.java
package a.b.c.com.kosmo.common;

public abstract class CommonUtils {
	
	// 게시판
	public static final String PRODUCT_IMG_UPLOAD_PATH = "C:\\00.KOSMO108\\30.Web\\eclipse_kosmo_spring_work\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\kosmoSpring\\fileupload\\product";	
	public static final int PRODUCT_IMG_FILE_SIZE = 10*1024*1024; // 10MB
	public static final String PRODUCT_EN_CODE = "UTF-8";
}
  • FileRename.java
package a.b.c.com.kosmo.common;

import java.io.File;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class FileRename implements FileRenamePolicy {

	public FileRename() {
		
	}
	
	@Override
	public File rename(File sf) {
		// TODO Auto-generated method stub
		String f = sf.getName();
		System.out.println("fileName >>> : " + f);
		
		try {
			String s = f;
			for (int i=1; sf.exists(); i++) {
				int lt = s.lastIndexOf(".");
				String s1 = s.substring(0, lt);
				String s2 = s.substring(lt);
				String st = "_" + i + "_";
				f = s1.concat(st).concat(s2);
				sf = new File(sf.getParent(), f);
			}
		} catch (Exception e) {
			System.out.println("FileRename.reName() >>> : " + e.getMessage());
		}
		
		return sf;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File f = new File("C:\\msdia80.dll");
		File ss = new FileRename().rename(f);
		System.out.println("ss >>> : " + ss.getName());
	}
}
  • ThumbnailImg.java
package a.b.c.com.kosmo.common;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

public abstract class ThumbnailImg {
	
	public static void thumbnailFun(String uploadPath,String filename){
		System.out.println("ThumnailFun thumnailFun >>> : ");
		System.out.println("uploadPath >>> : " + uploadPath);
		System.out.println("filename >>> : " + filename);
		File file = null;
		try{	
			ParameterBlock pb = new ParameterBlock();
			pb.add(uploadPath + "\\" + filename);
			
			RenderedOp rOp = JAI.create("fileload", pb);
			BufferedImage bi = rOp.getAsBufferedImage();
			
			// 썸네일 배경크기화 썸네일색상
			BufferedImage thumb = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = thumb.createGraphics();
			
			// 썸네일 위치, 썸네이을 크기 
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, 50, 50);
			g.drawImage(bi,0,0,50,50,null);
			
			//g.setComposite(AlphaComposite.Clear);
			//g.fillRect(0, 0, 500, 500);
			//g.setComposite(AlphaComposite.Src);
			
			file = new File(uploadPath + "\\sm_" + filename);
			ImageIO.write(thumb,"jpg",file);
			System.out.println("uploadPath/" + file.getName());
			
		}catch(Exception e){
			System.out.println("ThumnailImg.thumnailFun() >>> : " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}
  • FileUploadUtil.java
package a.b.c.com.kosmo.common;

import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import com.oreilly.servlet.MultipartRequest;

public class FileUploadUtil {
	
	private String imgfilePaths;
	private int imgfileSize; 
	private String encodeType;	
	private MultipartRequest mr;;

	public FileUploadUtil(String imgfilePaths, int imgfileSize, String encodeType) {
		this.imgfilePaths = imgfilePaths;
		this.imgfileSize = imgfileSize;
		this.encodeType = encodeType;		
	}
	
	public boolean imgfileUpload(HttpServletRequest req) {		
		boolean bool = imgfileUpload(req, imgfilePaths);		
		return bool;
	}
	
	public boolean imgfileUploadSize(HttpServletRequest req) {		
		boolean bool = imgfileUploadSize(req, imgfilePaths);		
		return bool;
	}

	public boolean imgfileUpload(HttpServletRequest req, String filePath) {
		boolean bool = false;
		try {
			mr = new MultipartRequest(req, filePath, imgfileSize, encodeType, new FileRename());
			System.out.println("mr >>> : " + mr);
			bool=true;
		}catch(Exception e) {
			System.out.println("imgfileUploadUtil.imgfileUpload() >>> : " + mr);			
		}		
		return bool;
	}
	
	public boolean imgfileUploadSize(HttpServletRequest req, String filePath) {
		boolean bool = false;
		try {
			mr = new MultipartRequest(req, filePath, imgfileSize, encodeType, new FileRename());
			System.out.println("mr >>> : " + mr);
			System.out.println("mr.getOriginalFileName(\"sbfile\") >>> : " + mr.getOriginalFileName("sbfile"));
			System.out.println("mr.getFilesystemName(\"sbfile\") >>> : " + mr.getFilesystemName("sbfile"));
			
			ThumbnailImg.thumbnailFun(filePath, mr.getFilesystemName("sbfile"));	
			bool=true;						
		}catch(Exception e) {
			System.out.println("imgfileUploadUtil.imgfileUpload() >>> : " + mr);			
		}		
		return bool;
	}
	
	public String getParameter(String s){
		return mr.getParameter(s);
	}
	
	public String[] getParameterValues(String s){
		return mr.getParameterValues(s);		
	}
	
	public String getFileName(String f){
		return mr.getFilesystemName(f);
	}
	
	public ArrayList<String> getFileNames(){
		@SuppressWarnings("unchecked")
		Enumeration<String> en = mr.getFileNames();
		ArrayList<String> a = new ArrayList<String>();
		
		while (en.hasMoreElements()){
			String f = en.nextElement().toString();
			a.add(mr.getFilesystemName(f));
		}		
		return a;
	}
}
  • KosmoProductVO.java
package a.b.c.com.kosmo.product.vo;

public class KosmoProductVO {

	private String kpnum;
	private String kpid;
	private String kpname;
	private String kpcompany;
	private String kpfile;
	private String kpcnt;
	private String kpprice;
	private String kpdesc;
	private String deleteyn;
	private String insertdate;
	private String updatedate;
	
	// generator
	public KosmoProductVO() {
	
	}

	public KosmoProductVO(String kpnum, String kpid, String kpname, String kpcompany, String kpfile, String kpcnt,
			String kpprice, String kpdesc, String deleteyn, String insertdate, String updatedate) {
		
		this.kpnum = kpnum;
		this.kpid = kpid;
		this.kpname = kpname;
		this.kpcompany = kpcompany;
		this.kpfile = kpfile;
		this.kpcnt = kpcnt;
		this.kpprice = kpprice;
		this.kpdesc = kpdesc;
		this.deleteyn = deleteyn;
		this.insertdate = insertdate;
		this.updatedate = updatedate;
	}
	
	// setters/getters
	public String getKpnum() {
		return kpnum;
	}
	public void setKpnum(String kpnum) {
		this.kpnum = kpnum;
	}
	public String getKpid() {
		return kpid;
	}
	public void setKpid(String kpid) {
		this.kpid = kpid;
	}
	public String getKpname() {
		return kpname;
	}
	public void setKpname(String kpname) {
		this.kpname = kpname;
	}
	public String getKpcompany() {
		return kpcompany;
	}
	public void setKpcompany(String kpcompany) {
		this.kpcompany = kpcompany;
	}
	public String getKpfile() {
		return kpfile;
	}
	public void setKpfile(String kpfile) {
		this.kpfile = kpfile;
	}
	public String getKpcnt() {
		return kpcnt;
	}
	public void setKpcnt(String kpcnt) {
		this.kpcnt = kpcnt;
	}
	public String getKpprice() {
		return kpprice;
	}
	public void setKpprice(String kpprice) {
		this.kpprice = kpprice;
	}
	public String getKpdesc() {
		return kpdesc;
	}
	public void setKpdesc(String kpdesc) {
		this.kpdesc = kpdesc;
	}
	public String getDeleteyn() {
		return deleteyn;
	}
	public void setDeleteyn(String deleteyn) {
		this.deleteyn = deleteyn;
	}
	public String getInsertdate() {
		return insertdate;
	}
	public void setInsertdate(String insertdate) {
		this.insertdate = insertdate;
	}
	public String getUpdatedate() {
		return updatedate;
	}
	public void setUpdatedate(String updatedate) {
		this.updatedate = updatedate;
	}
}
  • SpringChabunDAO.java
package a.b.c.com.kosmo.common.dao;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

public interface SpringChabunDAO {

	public KosmoProductVO getProductChabun();
}
  • SpringChabunDAOImpl.java
package a.b.c.com.kosmo.common.dao;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

@Repository
public class SpringChabunDAOImpl implements SpringChabunDAO {

	Logger logger = LogManager.getLogger(SpringChabunDAOImpl.class);
	
	@Autowired(required=false)
	private SqlSessionTemplate sqlSession;
	
	@Override
	public KosmoProductVO getProductChabun() {
		// TODO Auto-generated method stub
		return sqlSession.selectOne("getProductChabun");
	}
}
  • SpringChabunService.java
package a.b.c.com.kosmo.common.service;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

public interface SpringChabunService {

	public KosmoProductVO getProductChabun();
}
  • SpringChabunServiceImpl.java
package a.b.c.com.kosmo.common.service;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import a.b.c.com.kosmo.common.dao.SpringChabunDAO;
import a.b.c.com.kosmo.product.vo.KosmoProductVO;

@Service
@Transactional
public class SpringChabunServiceImpl implements SpringChabunService {

	Logger logger = LogManager.getLogger(SpringChabunServiceImpl.class);
	
	@Autowired(required=false)
	private SpringChabunDAO springChabunDAO;
	
	@Override
	public KosmoProductVO getProductChabun() {
		// TODO Auto-generated method stub
		logger.info("SpringChabunServiceImpl get ProductChabun >>> : ");
		return springChabunDAO.getProductChabun();
	}
}

7교시 (16:30-17:20)

  • KosmoProductDAO.java
package a.b.c.com.kosmo.product.dao;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

public interface KosmoProductDAO {

	public int kosmoProductInsert(KosmoProductVO kpvo);
}
  • KosmoProductDAOImpl.java
package a.b.c.com.kosmo.product.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

@Repository
public class KosmoProductDAOImpl implements KosmoProductDAO {
	
	Logger logger = LogManager.getLogger(KosmoProductDAOImpl.class);
	
	@Autowired(required=false)
	private SqlSession sqlSession;
	
	@Override
	public int kosmoProductInsert(KosmoProductVO kpvo) {
		// TODO Auto-generated method stub
		
		logger.info("KosmoProductDAOImpl kosmoProductInsert 함수 진입 >>> : ");
		
		return (Integer)sqlSession.insert("kosmoProductInsert", kpvo);
	}
}
  • KosmoProductService.java
package a.b.c.com.kosmo.product.service;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;

public interface KosmoProductService {

	public int kosmoProductInsert(KosmoProductVO kpvo);
}
  • KosmoProductServiceImpl.java
package a.b.c.com.kosmo.product.service;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import a.b.c.com.kosmo.product.vo.KosmoProductVO;
import a.b.c.com.kosmo.product.dao.KosmoProductDAO;
import a.b.c.com.kosmo.product.dao.KosmoProductDAOImpl;

@Service
@Transactional
public class KosmoProductServiceImpl implements KosmoProductService {

	Logger logger = LogManager.getLogger(KosmoProductServiceImpl.class);
	
	// 서비스에서 DAO 연결하기
	// 필드 @Autowired 어노테이션으로 DI (의존성 주입하기)
	@Autowired(required=false)
	private KosmoProductDAO kosmoProductDAO;
	
	@Override
	public int kosmoProductInsert(KosmoProductVO kpvo) {
		// TODO Auto-generated method stub
		
		logger.info("KosmoProductServiceImpl kosmoProductInsert 함수 진입 >>> : ");
		
		return kosmoProductDAO.kosmoProductInsert(kpvo);
	}
}
  • KosmoProductController.java
package a.b.c.com.kosmo.product.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import a.b.c.com.kosmo.common.ChabunUtil;
import a.b.c.com.kosmo.common.CommonUtils;
import a.b.c.com.kosmo.common.FileUploadUtil;
import a.b.c.com.kosmo.common.service.SpringChabunService;
import a.b.c.com.kosmo.product.service.KosmoProductService;
import a.b.c.com.kosmo.product.vo.KosmoProductVO;

@Controller
public class KosmoProductController {
	
	Logger logger = LogManager.getLogger(KosmoProductController.class);
	
	// 필드 오토와이어드
	@Autowired(required=false)
	private SpringChabunService springChabunService;
	
	// 필드 오토와이어드
	@Autowired(required=false)
	private KosmoProductService kosmoProductService;
	
	// 상품 입력 폼
	@RequestMapping(value="kosmoProductInsertForm", method=RequestMethod.GET)
	public String kosmoProductInsertForm() {
		logger.info("KosmoProductController kosmoProductInsertForm 함수 진입 >>> : ");
		return "product/kosmoProductInsertForm";
	}
	
	// 상품 입력
	@RequestMapping(value="kosmoProductInsert", method=RequestMethod.POST)
	public String kosmoProductInsert(HttpServletRequest req) {
		logger.info("KosmoProductController kosmoProductInsert 함수 진입 >>> ");
		
		// 채번 구하기
		String kpnum = ChabunUtil.getProductChabun("D", springChabunService.getProductChabun().getKpnum());
		logger.info("KosmoProductController kosmoProductInsertForm kpnum >>> : " + kpnum);
		
		// 이미지 업로드
		FileUploadUtil fu = new FileUploadUtil(  CommonUtils.PRODUCT_IMG_UPLOAD_PATH
												,CommonUtils.PRODUCT_IMG_FILE_SIZE
												,CommonUtils.PRODUCT_EN_CODE);
		
		// 이미지 파일 원본 사이즈
		boolean bool = fu.imgfileUpload(req);
		// 이미지 파일 원본 사이즈 크기 조절 하기
		// boolean bool = fu.imgfileUploadSize(req);
		logger.info("KosmoProductController kosmoProductInsert bool >>> : " + bool);
		
		KosmoProductVO _kpvo = null;
		_kpvo = new KosmoProductVO();
		
		_kpvo.setKpnum(kpnum);
		_kpvo.setKpid(fu.getParameter("kpid"));
		_kpvo.setKpname(fu.getParameter("kpname"));
		_kpvo.setKpcompany(fu.getParameter("kpcompany"));
		
		_kpvo.setKpfile(fu.getFileName("kpfile"));
		
		_kpvo.setKpcnt(fu.getParameter("kpcnt"));
		_kpvo.setKpprice(fu.getParameter("kpprice"));
		_kpvo.setKpdesc(fu.getParameter("kpdesc"));
		
		int nCnt = kosmoProductService.kosmoProductInsert(_kpvo);
		logger.info("KosmoProductController kosmoProductInsert nCnt >>> : " + nCnt);
		
		if (nCnt > 0) { return "product/kosmoProductInsert"; }
		return "product/kosmoProductInsertForm";
	}
}

8교시 (17:30-18:30)

  • kosmoProductInsert.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>
	<h3>kosmoProductInsert.jsp</h3>
	<hr>
</body>
</html>
  • kosmoProductInsertForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 등록</title>
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
	// alert(">>");
	$(document).ready(function(){
		// alert(">>11");
		
		$(document).on("click", "#kpbtn", function(){
			
			console.log("kpbtn >>> : ");								
			
			$('#productForm').attr({
				'action':'kosmoProductInsert.k',
				'method':'POST',
				'enctype':'multipart/form-data'
			}).submit();
		});
	});	
</script>
</head>
<body>
	<h3>kosmoProductInsertForm.jsp</h3>
	<hr>	
	<form name="productForm" id="productForm">
		<table border="1" align="center">
			<tr>
				<td colspan="2" align="center">상품등록</td>				
			</tr>
			<tr>
				<td align="center">상품번호</td>		
				<td><input type="text" name="kpnum" id="kpnum" size="20" readonly></td>
			</tr>
			<tr>
				<td  align="center">상품아이디</td>
				<td><input type="text" name="kpid" id="kpid" size="20"></td>
			</tr>
			<tr>
				<td  align="center">상품이름</td>
				<td><input type="text" name="kpname" id="kpname" size="20"></td>
			</tr>
			<tr>
				<td  align="center">제조사</td>
				<td><input type="text" name="kpcompany" id="kpcompany" size="20"></td>
			</tr>
			<tr>
				<td  align="center">상품이미지</td>
				<td>
				<input type="file" name="kpfile" id="kpfile">
			</td>
			</tr>
			<tr>
				<td  align="center">상품수량</td>
				<td><input type="text" name="kpcnt" id="kpcnt" size="20"></td>
			</tr>
			<tr>
				<td  align="center">상품가격</td>
				<td><input type="text" name="kpprice" id="kpprice" size="20"></td>
			</tr>	
			<tr>
				<td  align="center">상품설명</td>
				<td>
				<textarea name="kpdesc" id="kpdesc" cols="50" rows="10"></textarea>
			</td>
			</tr>	
			<tr>
				<td colspan="2" align="right">				
				<input type="button" value="상품등록" id="kpbtn">		
			</td>				
			</tr>
		</table>
	</form>
</body>
</html>
  • index.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>
	<h3>index.jsp</h3>
	<hr>
	<a href="kosmoProductInsertForm.k">코스모 상품 입력</a>
</body>
</html>


Notes


728x90