Spring 2022/03/30 item

파일명 ItemController.java

package com.example.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.example.dto.ItemDTO;
import com.example.dto.ItemImageDTO;
import com.example.mapper.ItemImageMapper;
import com.example.service.ItemImageService;
import com.example.service.ItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="/item")
public class ItemController {

    @Autowired ItemService iService;

    @Autowired ResourceLoader resLoader;

    @Autowired ItemImageService iiService; 
    
    @Autowired ItemImageMapper iiMapper;

    @PostMapping(value = "/insertimages")
    public String insertimagesPOST(
            @RequestParam(name = "icode") long icode,            
            @RequestParam(name = "timage") MultipartFile[] files) 
            throws IOException{
        // ItemImageDTO를 n개 보관할 수 있는 list
        List<ItemImageDTO> list = new ArrayList<>();
        for(MultipartFile file : files){
            ItemImageDTO obj = new ItemImageDTO();
            obj.setIcode(icode); // 물품코드
            obj.setIimage(file.getBytes()); // 이미지
            obj.setIimagetype(file.getContentType()); // 타입
            obj.setIimagesize(file.getSize()); // 사이즈
            obj.setIimagename(file.getOriginalFilename()); // 파일명

            list.add(obj);           
        }
        int ret = iiService.insertItemImageBatch(list);
        System.out.println("===============================");
        System.out.println(ret);
		return "redirect:/item/selectone?code=" + icode;
    }

    // 127.0.0.1:9090/ROOT/item/subimage?imgcode=12 
    // html에서 사용시 <img th:src="@{/item/subimage(imgcode=15)}">
    @GetMapping(value = "/subimage")
    public ResponseEntity<byte[]> subimageGET(@RequestParam(name = "imgcode")long imgcode) throws IOException{
        // 이미지명, 이미지크기, 이미지종류, 이미지데이터
        ItemImageDTO item = iiMapper.selectItemImageCodeOne(imgcode);
        // System.out.println(item.getIimagetype());
        // System.out.println(item.getIimage().length);
        if(item != null){ // 물품정보가 존재하면
            if(item.getIimagesize() > 0){ // 첨부한 파일 존재
                HttpHeaders headers = new HttpHeaders();

                if(item.getIimagetype().equals("image/jpeg")){
                    headers.setContentType(MediaType.IMAGE_JPEG);
                }
                else if(item.getIimagetype().equals("image/png")){
                    headers.setContentType(MediaType.IMAGE_PNG);
                }
                else if(item.getIimagetype().equals("image/gif")){
                    headers.setContentType(MediaType.IMAGE_GIF);
                }

                // 이미지, byte[], headers, HttpStatus.OK
                ResponseEntity<byte[]> response = new ResponseEntity<>(item.getIimage(),headers,HttpStatus.OK);
                return response;
            }
            else {
                InputStream is = resLoader.getResource("classpath:/static/img/default.png").getInputStream();
                HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.IMAGE_PNG);
                ResponseEntity<byte[]> response = new ResponseEntity<>(is.readAllBytes(), headers, HttpStatus.OK);
                return response;
            }
        }
        return null;
    }


    // 127.0.0.1:9090/ROOT/item/image?code=12 
    // html에서 사용시 <img th:src="@{/item/image(code=15)}">
    @GetMapping(value = "/image")
    public ResponseEntity<byte[]> imageGET(@RequestParam(name = "code")long code) throws IOException{
        // 이미지명, 이미지크기, 이미지종류, 이미지데이터
        ItemDTO item = iService.selectItemImageOne(code);
        // System.out.println(item.getIimagetype());
        // System.out.println(item.getIimage().length);
        if(item != null){ // 물품정보가 존재하면
            if(item.getIimagesize() > 0){ // 첨부한 파일 존재
                HttpHeaders headers = new HttpHeaders();

                if(item.getIimagetype().equals("image/jpeg")){
                    headers.setContentType(MediaType.IMAGE_JPEG);
                }
                else if(item.getIimagetype().equals("image/png")){
                    headers.setContentType(MediaType.IMAGE_PNG);
                }
                else if(item.getIimagetype().equals("image/gif")){
                    headers.setContentType(MediaType.IMAGE_GIF);
                }

                // 이미지, byte[], headers, HttpStatus.OK
                ResponseEntity<byte[]> response = new ResponseEntity<>(item.getIimage(),headers,HttpStatus.OK);
                return response;
            }
            else {
                InputStream is = resLoader.getResource("classpath:/static/img/default.png").getInputStream();
                HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.IMAGE_PNG);
                ResponseEntity<byte[]> response = new ResponseEntity<>(is.readAllBytes(), headers, HttpStatus.OK);
                return response;
            }
        }
        return null;
    }


    // 127.0.0.1:9090/ROOT/item/selectone?code=12
    @GetMapping(value = "/selectone")
    public String selectoneGET(
            Model model,
            @RequestParam(name = "code") long code){
        ItemDTO item = iService.selectItemOne(code);
        model.addAttribute("item", item);

        List<Long> imgcode = iiService.selectItemImageList(code);
        model.addAttribute("imgcode", imgcode);
        return "/item/selectone";
    }

    // 127.0.0.1:9090/ROOT/item/selectlist?txt=검색어&page=1
    @GetMapping(value = "/selectlist")
    public String selectlistGET(
            HttpSession httpSession,
            Model model,
            @RequestParam(name = "txt", defaultValue = "") String txt,
            @RequestParam(name = "page", defaultValue = "1") int page
           ){

        // 세션에서 이메일 정보를 받음
        String em = (String)httpSession.getAttribute("SESSION_EMAIL");

        if(em != null){
            String role = (String)httpSession.getAttribute("SESSION_ROLE");
            if(role.equals("SELLER") ){
                Map<String, Object> map = new HashMap<>();
                map.put("txt", txt);
                map.put("start", page * 10 -9);
                map.put("end", page * 10);      
                map.put("email", em);
                // page 1, start 1  end 10
                // page 2, start 11 end 20
                // page 3, start 21 end 30  

                List<ItemDTO> list = iService.selectItemList(map);
                model.addAttribute("list", list);

                long cnt = iService.selectItemCount(map);
                // 9  => 1
                // 11 => 2
                // 24 => 3
                model.addAttribute("pages", (cnt-1)/10+1);

                // System.out.println(list);
                return "/item/selectlist";
            }                        
        }        
        return "redirect:/seller/select";
        
    }

    // 127.0.0.1:9090/ROOT/item/insert
    @GetMapping(value="/insert")
    public String insertGET(){
        // templates폴더 item폴더 insert.html 표시(렌더링)
        return "/item/insert";
    }

    @PostMapping(value = "/insert")
    public String insertPOST(
            HttpSession httpSession,
            @ModelAttribute ItemDTO item,
            @RequestParam(name = "timage") MultipartFile file) throws IOException {
        // System.out.println("==================================");
        // System.out.println(item.toString());
        // System.out.println(file.getOriginalFilename());
        // System.out.println("==================================");
        // 파일관련내용
        item.setIimagetype(file.getContentType());
        item.setIimagename(file.getOriginalFilename());
        item.setIimagesize(file.getSize());
        item.setIimage(file.getBytes());

        // 세션에서 이메일 꺼내기
        String em = (String)httpSession.getAttribute("SESSION_EMAIL");
        item.setUemail(em);

        int ret = iService.insertItemOne(item);
        // System.out.println(ret);
        // System.out.println("==================================");
    	if(ret == 1) {
    		return "redirect:/item/selectlist";
    	}
    	return "redirect:/item/insert";
        }
}


파일명 selectone.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>물품 상세</title>
</head>

<body style="padding: 10px;">
    <h3>물품상세</h3>

    <hr />
    
    <div style="padding:20px">

        <a th:href="@{/item/selectlist}">목록으로</a><br />

        <label style="width:75px; height: 30px; display:inline-block;">물품번호 :</label>
        <P style="display:inline-block" th:text="${item.icode}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">물품명 :</label>
        <P style="display:inline-block" th:text="${item.iname}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">물품내용 :</label>
        <P style="display:inline-block" th:text="${item.icontent}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">물품가격 :</label>
        <P style="display:inline-block" th:text="${item.iprice}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">물품수량 :</label>
        <P style="display:inline-block" th:text="${item.iquantity}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">등록일 :</label>
        <P style="display:inline-block" th:text="${item.iregdate}"></P><br />

        <label style="width:75px; height: 30px; display:inline-block;">이미지 :</label>
        <img th:src="@{/item/image(code=${item.icode})}" style="width: 100px; height: 100px;">
        <hr />

        <h3>서브이미지 등록</h3>
        <form th:action="@{/item/insertimages}" method="post" enctype="multipart/form-data">
            <input type="text" name="icode" th:value="${item.icode}"/>
            <th:block th:each = "i : ${#numbers.sequence(1,3)}">
                <input type="file" name="timage" /><br />
            </th:block>
            <input type="submit" value="서브이미지일괄등록">
        </form>
        <hr />
        <h3>등록된 이미지 표시</h3>
        <table border="1">
            <tr>
                <th>물품이미지코드</th>
                <th>이미지</th>
                <th>버튼</th>
            </tr>
            <tr th:each="tmp : ${imgcode}">
                <td th:text="${tmp}"></td>
                <td><img th:src="@{/item/subimage(imgcode=${tmp}) }" style="width: 50px; height: 50px;"/></td>
                <td>수정 삭제</td>
            </tr>
        </table>

    </div>
</body>
</html>

파일명 ItemService.java

package com.example.service;

import java.util.List;
import java.util.Map;

import com.example.dto.ItemDTO;

import org.springframework.stereotype.Service;

@Service
public interface ItemService {

    // 물품등록
    public int insertItemOne(ItemDTO item);

    // 물품조회(검색어 + 페이지네이션)
    public List<ItemDTO> selectItemList(Map<String, Object> map);

    // 물품개수(페이지네이션용)
    public long selectItemCount(Map<String, Object> map);

    // 물품상세
    public ItemDTO selectItemOne(long code);

    // 이미지
    public ItemDTO selectItemImageOne(long code);
    
}

파일명 ItemServiceImpl.java

package com.example.service;

import java.util.List;
import java.util.Map;

import com.example.dto.ItemDTO;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    SqlSessionFactory sqlFactory;

    @Override
    public int insertItemOne(ItemDTO item) {
        return sqlFactory.openSession().insert("Item.insertItemOne", item);
    }

    @Override
    public List<ItemDTO> selectItemList(Map<String, Object> map) {        
        return sqlFactory.openSession().selectList("Item.selectItemList", map);
    }

    @Override
    public long selectItemCount(Map<String, Object> map) {        
        return sqlFactory.openSession().selectOne("Item.selectItemCount", map);
    }

    @Override
    public ItemDTO selectItemOne(long code) {        
        return sqlFactory.openSession().selectOne("Item.selectItemOne", code);
    }

    @Override
    public ItemDTO selectItemImageOne(long code) {        
        return sqlFactory.openSession().selectOne("Item.selectItemImageOne", code);
    }    
}

파일명 itemMapper.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="Item">

    <insert id="insertItemOne" parameterType="com.example.dto.ItemDTO">
        INSERT INTO ITEM( ICODE, INAME, ICONTENT, IPRICE, IQUANTITY, 
                    IIMAGE, IIMAGESIZE, IIMAGETYPE, IIMAGENAME, UEMAIL ) 
		VALUES ( SEQ_ITEM_ICODE.NEXTVAL, #{iname}, #{icontent}, #{iprice}, #{iquantity},
                    #{iimage, jdbcType=BLOB}, #{iimagesize}, #{iimagetype}, #{iimagename}, #{uemail} )
    </insert>

    <select id="selectItemList"	parameterType="map"	resultType="com.example.dto.ItemDTO">
        SELECT * FROM (
            SELECT 
                I.ICODE, I.INAME, I.IPRICE, I.IQUANTITY, I.IREGDATE, 
                ROW_NUMBER() OVER (ORDER BY I.ICODE DESC) ROWN 
            FROM 
                ITEM I
            WHERE 
                I.INAME LIKE '%' || #{txt} || '%'
                AND I.UEMAIL = #{email}
        )
        WHERE ROWN BETWEEN #{start} AND #{end}
    </select>

    <select id="selectItemCount" parameterType="map" resultType="long">
		SELECT
			COUNT(*) CNT 
		FROM 
			ITEM I	
		WHERE 
			I.INAME LIKE '%' || #{txt} || '%'
            AND I.UEMAIL = #{email}
	</select>

    <select id="selectItemOne" parameterType="long" resultType="com.example.dto.ItemDTO">
        SELECT 
            ICODE, INAME, ICONTENT, IPRICE, IQUANTITY, IREGDATE 
        FROM    
            ITEM
        WHERE 
            ICODE = #{code}
    </select>

    <resultMap id="result1" type="com.example.dto.ItemDTO" >
        <result column="IIMAGE" property="iimage" jdbcType="BLOB"/>
    </resultMap>

    <select id="selectItemImageOne" parameterType="long" resultMap="result1">
        SELECT  
            ICODE, IIMAGE, IIMAGESIZE, IIMAGETYPE, IIMAGENAME
        FROM    
            ITEM    
        WHERE 
            ICODE = #{code}
        
    </select>

</mapper>

좋은 웹페이지 즐겨찾기