336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


안녕하세요

PROCEDURE CURSOR 사용입니다.


ORACLE 프로시저구문

1
2
3
4
5
6
7
8
9
10
11
12
create or replace PROCEDURE pro_testTableSel(
varNameCol IN VARCHAR2,
c_result OUT SYS_REFCURSOR)
IS
 
BEGIN
OPEN c_result FOR
    SELECT idCol, nameCol, valueCol
    FROM testTable
    WHERE nameCol = varNameCol;
 
END pro_testTableSel;
cs


home.jsp

1
2
3
4
5
프로시저 실행 <br/>
<form name="procedureForm" id="procedureForm" method="POST" action="./springProcedure.do">
    <input type="text" value="글쓴이" id="nameCol" name="nameCol"/>
     <input type="submit" value="프로시저 호출" />
</form>
cs


HomeController.java

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value = "/springProcedure.do", method = RequestMethod.POST)
    public void springProcedure(HttpServletRequest request){
        
        //request Map은 수정이 불가능해서 따로 담아서 Procedure 처리
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("NAMECOL", request.getParameter("nameCol"));
        
        logger.info("map check : "+map.toString());
        
        homeService.getProcedureSel(map);
    }
cs


HomeService.java

1
public void getProcedureSel(Map<String, Object> map);
cs


HomeServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
    public void getProcedureSel(Map<String, Object> map) {
        map.put("resultList"new ArrayList<HashMap<?,?>>());
        homeMapper.testDbProcedure(map);
        
        //가져온 사이즈 체크
        int size = map.get("resultList").toString().length();
        
        //가져온값
        List<?> list = (List<?>) map.get("resultList");
        
        //출력
        for(int i = 0; i < size - 1; i++){
            logger.info("cursor list Check ServiceImpl : "+list.get(i));
        }
        
    }
cs


HomeMapper.java

1
public void testDbProcedure(Map<String, Object> map);
cs


testMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- cursor 값 내용물 -->
<resultMap type="java.util.Map" id="resultMap">
    <result property="idCol" column="idCol" javaType="integer"/>
    <result property="nameCol" column="nameCol" javaType="string"/>
    <result property="valueCol" column="valueCol" javaType="string"/>
</resultMap>
 
<!-- 프로시저 (NUMBER -> NUMERIC 문자열(VARCHAR)), resultMap = 상위 id -->
    <select id="testDbProcedure" parameterType="java.util.Map" statementType="CALLABLE">
        CALL pro_testTableSel(
        #{NAMECOL, mode=IN, jdbcType=VARCHAR},
        #{resultList, mode=OUT, jdbcType=CURSOR, javaType=java.sql.ResultSet, resultMap=resultMap}
        )
    </select>
cs


결과


감사합니다.

'SPRING' 카테고리의 다른 글

SPRING PROCEDURE 사용하기 1  (0) 2019.04.01
SPIRNG EXCEL UPLOAD 하기  (1) 2019.04.01
SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

 

참고 프로시저

1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE OR REPLACE PROCEDURE pro_testTableSel(
varIdCol IN OUT NUMBER,
varNameCol OUT VARCHAR2,
varValueCol OUT VARCHAR2)
IS
 
BEGIN
    SELECT idCol, nameCol, valueCol
    INTO varIdCol, varNameCol, varValueCol
    FROM testTable
    WHERE idCOl = varIdCol;
 
END pro_testTableSel;
cs


 


home.jsp

1
2
3
4
5
프로시저 실행 <br/>
<form name="procedureForm" id="procedureForm" method="POST" action="./springProcedure.do">
    <input type="text" value="2" id="idCol" name="idCol"/>
     <input type="submit" value="프로시저 호출" />
</form>
cs


HomeController.java

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value = "/springProcedure.do", method = RequestMethod.POST)
    public void springProcedure(HttpServletRequest request){
        
        //request Map은 수정이 불가능해서 따로 담아서 Procedure 처리
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("IDCOL", Integer.parseInt(request.getParameter("idCol")));
        
        logger.info("map check : "+map.toString());
        
        homeService.getProcedureSel(map);
    }
cs


HomeService.java

1
public void getProcedureSel(Map<String, Object> map);
cs


HomeServiceImpl.java

1
2
3
4
5
6
@Override
    public void getProcedureSel(Map<String, Object> map) {
        homeMapper.testDbProcedure(map);
        
        logger.info("map Check ServiceImpl : "+map.toString());
    }
cs


HomeMapper.java

1
public void testDbProcedure(Map<String, Object> map);
cs


testMapper.xml

1
2
3
4
5
6
7
8
<!-- 프로시저 (NUMBER -> NUMERIC 문자열(VARCHAR)) -->
    <select id="testDbProcedure" parameterType="java.util.Map" statementType="CALLABLE">
        CALL pro_testTableSel(
        #{IDCOL, mode=INOUT, jdbcType=NUMERIC, javaType=Integer},
        #{NAMECOL, mode=OUT, jdbcType=VARCHAR, javaType=String},
        #{VALUECOL, mode=OUT, jdbcType=VARCHAR, javaType=String}
        )
    </select>
cs

 

결과



감사합니다.

'SPRING' 카테고리의 다른 글

SPRING PROCEDURE 사용하기 2  (0) 2019.04.01
SPIRNG EXCEL UPLOAD 하기  (1) 2019.04.01
SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요

EXCEL UPLOAD입니다.

 

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
<!-- excel 처리 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
cs

 

home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$("#excelUpForm").change(function(){
                var form = $("#excelUpForm")[0];
 
                var data = new FormData(form);
                $.ajax({
                   enctype:"multipart/form-data",
                   method:"POST",
                   url: './excelUp.do',
                   processData: false,   
                   contentType: false,
                   cache: false,
                   data: data,
                   success: function(result){  
                       alert("업로드 성공!!");
                   }
                });
            });
 
 
 
엑셀업로드 : <br/>
<form name="excelUpForm" id="excelUpForm" enctype="multipart/form-data" method="POST" action="./excelDown.do">
    <input type="file" id="excelFile" name="excleFile" value="엑셀 업로드" />
</form>
cs

 

ExcelController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@RequestMapping(value = "/excelUp.do", method = RequestMethod.POST)
    public void ExcelUp(HttpServletRequest req, HttpServletResponse rep){
        logger.info("@@@@@@@@@@@@@@@ExcelUp START@@@@@@@@@@@@@@@");
 
        Map returnObject = new HashMap(); 
        
        try { // MultipartHttpServletRequest 생성 
            MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) req; 
            Iterator iter = mhsr.getFileNames(); 
            MultipartFile mfile = null
            String fieldName = ""
            
            // 값이 나올때까지
            while (iter.hasNext()) { 
                fieldName = iter.next().toString(); // 내용을 가져와서 
                mfile = mhsr.getFile(fieldName); 
                String origName; 
                origName = new String(mfile.getOriginalFilename().getBytes("8859_1"), "UTF-8"); //한글꺠짐 방지 // 파일명이 없다면 
                
                returnObject.put("params", mhsr.getParameterMap()); 
                
                
                //위치 및 파일
                homeService.getExcelUpload("D:\\"+origName);
            }
            
            } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block 
                e.printStackTrace(); 
            }catch (IllegalStateException e) { // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (IOException e) { // TODO Auto-generated catch block 
                e.printStackTrace(); 
            }
 
        
        logger.info("@@@@@@@@@@@@@@@ExcelUp END@@@@@@@@@@@@@@@");
        
    }
cs

 

ExcelUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public static Workbook getWorkbook(String filePath) {
 
        /*
         * FileInputStream은 파일의 경로에 있는 파일을 읽어서 Byte로 가져온다.
         * 
         * 파일이 존재하지 않는다면은 RuntimeException이 발생된다.
         */
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
 
        Workbook wb = null;
 
        /*
         * 파일의 확장자를 체크해서 .XLS 라면 HSSFWorkbook에 .XLSX라면 XSSFWorkbook에 각각 초기화 한다.
         */
        if (filePath.toUpperCase().endsWith(".XLS")) {
            try {
                wb = new HSSFWorkbook(fis);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else if (filePath.toUpperCase().endsWith(".XLSX")) {
            try {
                wb = new XSSFWorkbook(fis);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
 
        return wb;
 
    }
 
    //Excel Upload시에 데이터를 얻어옵니다.
    @SuppressWarnings("deprecation")
    public static String cellValue(Cell cell) {
 
        String value = null;
        if (cell == null)
            value = "";
        else {
            switch (cell.getCellType()) { // cell 타입에 따른 데이타 저장
            case Cell.CELL_TYPE_FORMULA:
                value = cell.getCellFormula();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    // you should change this to your application date format
                    SimpleDateFormat objSimpleDateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd");
                    value = ""
                            + objSimpleDateFormat.format(cell
                                    .getDateCellValue());
                } else {
                    value = ""
                            + String.format("%.0f",
                                    new Double(cell.getNumericCellValue()));
                }
                break;
            case Cell.CELL_TYPE_STRING:
                value = "" + cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                // value=""+cell.getBooleanCellValue();
                value = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                value = "" + cell.getErrorCellValue();
                break;
            default:
            }
        }
 
        return value.trim();
    }
cs

 

HomeService.java

1
public List<?> getExcelUpload(String excelFile);
cs

 

 

HomeServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public List<?> getExcelUpload(String excelFile){
        
        logger.info("@@@@@@@@@@@@@@@getExcelUpload START@@@@@@@@@@@@@@@ "+excelFile);
        
        Map<String, Object> map = new HashMap<String, Object>();
        List<?> list = null;
        
        try {
//            Workbook wbs = WorkbookFactory.create(new FileInputStream(excelFile));
            Workbook wbs = ExcelUtil.getWorkbook(excelFile);
            
            Sheet sheet = (Sheet) wbs.getSheetAt(0);
 
            //excel file 두번쨰줄부터 시작
            for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
                
                logger.info("@@@@@@@@map @@@@@@@@@@@@@@@@ i : "+i);
                
                Row row = sheet.getRow(i);
                
                //map.put("IDCOL", ""+ExcelUtil.cellValue(row.getCell(0)));
                map.put("NAMECOL"""+ExcelUtil.cellValue(row.getCell(1)));
                map.put("VALUECOL"""+ExcelUtil.cellValue(row.getCell(2)));
                
                //신규삽입
                homeMapper.insertDB(map);
            }
 
            logger.info("@@@@@@@@map @@@@@@@@@@@@@@@@"+map.toString());
            //데이터가져옵니다.
            list = homeMapper.testDbList(map);
            
        }catch(Exception e){
            logger.error("error : "+e.getMessage());
            logger.error("error : "+e);
        }
        
        logger.info("@@@@@@@@@@@@@@@getExcelUpload END@@@@@@@@@@@@@@@");
        return list;
        
    }
cs

HomeMapper.java

1
public int insertDB(Map<String, Object> map);
cs

 

testMapper.xml

1
2
3
4
5
<!-- 데이터 삽입 -->
    <insert id="insertDB" parameterType="java.util.Map">
        INSERT INTO testTable(IDCOL, NAMECOL, VALUECOL)
        VALUES(seq_id.nextval, #{NAMECOL}, #{VALUECOL})
    </insert>
cs

 

 

감사합니다.

'SPRING' 카테고리의 다른 글

SPRING PROCEDURE 사용하기 2  (0) 2019.04.01
SPRING PROCEDURE 사용하기 1  (0) 2019.04.01
SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

출처 : https://winmargo.tistory.com/103


진행하기 위에선 DB에 파일 정보가 담겨져 있어야 합니다.


pom.xml

1
2
3
4
5
<dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.2</version>
        </dependency>
cs


FileController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
@RequestMapping("/fileDown.do")
    public ModelAndView download(@RequestParam("filecol")String filecol){
        
        logger.info("@@@@@@@@@@@@@@@FileDown(1) START@@@@@@@@@@@@@@@");
        
        String fullPath = filecol;
         
        File file = new File(fullPath);
        
        logger.info("@@@@@@@@@@@@@@@FileDown(1) END@@@@@@@@@@@@@@@");
         
        return new ModelAndView("download""downloadFile", file);
    }
cs


servlet-context.xml

1
2
3
4
5
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
              <property name="order" value="0"/>
    </bean>
    
    <bean id="download" class="com.java.spring.util.FileDownload"/>
cs



FileDownload.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class FileDownload extends AbstractView {
    public void Download(){
        
        setContentType("application/download; utf-8");
         
    }
 
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        
        File file = (File)model.get("downloadFile");
        System.out.println("DownloadView --> file.getPath() : " + file.getPath());
        System.out.println("DownloadView --> file.getName() : " + file.getName());
         
        response.setContentType(getContentType());
        response.setContentLength((int)file.length());
         
        //String userAgent = request.getHeader("User-Agent");
         
        //boolean ie = userAgent.indexOf("MSIE") > -1;
         
        String fileName = null;
         
        //if(ie){
        //브라우저 정보에 따라 utf-8변경
        if(request.getHeader("User-Agent").indexOf("MSIE"> -1){
             
            fileName = URLEncoder.encode(file.getName(), "utf-8");
                         
        } else {
             
            fileName = new String(file.getName().getBytes("utf-8"));
        }// end if;
        
        response.setHeader("Content-Disposition""attachment; filename=\"" + fileName + "\";");
        response.setHeader("Content-Transfer-Encoding""binary");
        OutputStream out = response.getOutputStream();
        FileInputStream fis = null;
        
        //파일 카피 후 마무리
        try {
            fis = new FileInputStream(file);
            FileCopyUtils.copy(fis, out);
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            if(fis != null){
                try{
                    fis.close();
                }catch(Exception e){}
            }
        }// try end;
        out.flush();
        
    }
}
cs


home.jsp 

해당 파일이 db로 뿌려지고 있다면..

1
2
3
4
5
function fileDown(file){
            location.href = "http://localhost:8080/spring/fileDown.do?filecol="+encodeURI(file);
        }
 
<td onclick="fileDown('${list.FILECOL }')">${list.FILECOL }</td>
cs


감사합니다.


'SPRING' 카테고리의 다른 글

SPRING PROCEDURE 사용하기 1  (0) 2019.04.01
SPIRNG EXCEL UPLOAD 하기  (1) 2019.04.01
Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

퍼온글 : https://mkil.tistory.com/273

pom.xml

1
2
3
4
5
<dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.2</version>
        </dependency>
cs


servlet-context.xml

1
2
3
4
5
<!-- MultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name="maxUploadSize" value="100000000"/>
      <property name="maxInMemorySize" value="100000000"/>
    </bean>
cs


home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$("#fileUpForm").change(function(){
                var form = $("#fileUpForm")[0];
                var data = new FormData(form);
                $.ajax({
                   enctype:"multipart/form-data",
                   method:"POST",
                   url: './fileUp.do',
                   processData: false,   
                   contentType: false,
                   cache: false,
                   data: data,
                   success: function(result){  
                       alert("업로드 성공!!");
                   }
                });
            });
<form name="fileUpForm" id="fileUpForm" enctype="multipart/form-data" method="POST" action="./excelDown.do">
    <input type="file" id="upFile" name="upFile" value="엑셀 업로드" />
</form>
cs


commUtil.java

1
2
3
4
//uuid생성 
    public static String getUuid() { 
        return UUID.randomUUID().toString().replaceAll("-"""); 
    }
cs


FileController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@RequestMapping(value = "/fileUp.do", method = RequestMethod.POST)
    public void ExcelUp(HttpServletRequest req, HttpServletResponse rep){
        logger.info("@@@@@@@@@@@@@@@FileUp START@@@@@@@@@@@@@@@");
        
        //파일이 저장될 path 설정 
        String path = "D://"
        Map returnObject = new HashMap(); 
        
        try { // MultipartHttpServletRequest 생성 
            MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) req; 
            Iterator iter = mhsr.getFileNames(); 
            MultipartFile mfile = null
            String fieldName = ""
            List resultList = new ArrayList(); // 디레토리가 없다면 생성 
            File dir = new File(path); 
            
            if (!dir.isDirectory()) { 
                dir.mkdirs(); 
            } 
            
            // 값이 나올때까지
            while (iter.hasNext()) { 
                fieldName = iter.next().toString(); // 내용을 가져와서 
            mfile = mhsr.getFile(fieldName); 
            String origName; 
            origName = new String(mfile.getOriginalFilename().getBytes("8859_1"), "UTF-8"); //한글꺠짐 방지 // 파일명이 없다면 
            
            if ("".equals(origName)) { continue; } // 파일 명 변경(uuid로 암호화) 
            
                String ext = origName.substring(origName.lastIndexOf('.')); // 확장자
                String saveFileName = CommUtil.getUuid() + ext;//getUuid() + ext; // 설정한 path에 파일저장 
                File serverFile = new File(path + File.separator + saveFileName); 
                mfile.transferTo(serverFile); 
                Map file = new HashMap(); 
                file.put("origName", origName); 
                file.put("sfile", serverFile); 
                resultList.add(file); 
                
                //DB에 들어갈만한 건들
                System.out.println("복호화된 파일 이름 : "+serverFile.getName()); //복호화된 파일 이름 
                System.out.println("물리적 저장 경로  : "+serverFile.getAbsolutePath()); //물리적 저장 경로 
                System.out.println("파일 크기 : "+serverFile.length()); //파일 크기 
                System.out.println("원래 파일 명 : "+origName); //원래 파일 명
 
            }
            
            returnObject.put("files", resultList); 
            returnObject.put("params", mhsr.getParameterMap()); 
            
        } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }catch (IllegalStateException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (IOException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }
        logger.info("@@@@@@@@@@@@@@@FileUp End@@@@@@@@@@@@@@@");
    }
cs




감사합니다.

'SPRING' 카테고리의 다른 글

SPIRNG EXCEL UPLOAD 하기  (1) 2019.04.01
SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요

이번엔 DB에 있는 값을 EXCEL DOWN에 대해 써보겠습니다.


pom.xml

1
2
3
4
5
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
cs


HomeController.java가 있는 패키지에 ExcelController.java를 생성해 주세요.

ExcelController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Controller
public class ExcelController {
 
    private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);
    
    //Service 연동
    @Resource(name = "homeService")
    private HomeService homeService;
    
    @RequestMapping(value = "/excelDown.do", method = RequestMethod.POST)
    public void ExcelDown(HttpServletResponse response){
        logger.info("@@@@@@@@@@@@@@@ExcelDown START@@@@@@@@@@@@@@@");
        
        homeService.getExcelDown(response);
        
        logger.info("@@@@@@@@@@@@@@@ExcelDown END@@@@@@@@@@@@@@@");
        
    }
}
cs


HomeService.java

1
public void getExcelDown(HttpServletResponse response);
cs


HomeServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@Override
    public void getExcelDown(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<?> list = homeMapper.testDbList(map);
        
        try{
            //Excel Down 시작
            Workbook workbook = new HSSFWorkbook();
            //시트생성
            Sheet sheet = workbook.createSheet("게시판");
            
            //행, 열, 열번호
            Row row = null;
            Cell cell = null;
            int rowNo = 0;
            
            // 테이블 헤더용 스타일
            CellStyle headStyle = workbook.createCellStyle();
    
            // 가는 경계선을 가집니다.
            headStyle.setBorderTop(BorderStyle.THIN);
            headStyle.setBorderBottom(BorderStyle.THIN);
            headStyle.setBorderLeft(BorderStyle.THIN);
            headStyle.setBorderRight(BorderStyle.THIN);
    
            // 배경색은 노란색입니다.
            headStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex());
            headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    
            // 데이터는 가운데 정렬합니다.
            headStyle.setAlignment(HorizontalAlignment.CENTER);
    
            // 데이터용 경계 스타일 테두리만 지정
            CellStyle bodyStyle = workbook.createCellStyle();
            bodyStyle.setBorderTop(BorderStyle.THIN);
            bodyStyle.setBorderBottom(BorderStyle.THIN);
            bodyStyle.setBorderLeft(BorderStyle.THIN);
            bodyStyle.setBorderRight(BorderStyle.THIN);
    
            // 헤더 생성
            row = sheet.createRow(rowNo++);
    
            cell = row.createCell(0);
            cell.setCellStyle(headStyle);
            cell.setCellValue("번호");
    
            cell = row.createCell(1);
            cell.setCellStyle(headStyle);
            cell.setCellValue("이름");
    
            cell = row.createCell(2);
            cell.setCellStyle(headStyle);
            cell.setCellValue("제목");
    
            // 데이터 부분 생성
            for(Object map1 : list) {
                Map<String, Object> mapValue = (Map<String, Object>) map1;
                
                logger.info("DB DATA : "+mapValue.toString());
                
                row = sheet.createRow(rowNo++);
                cell = row.createCell(0);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("IDCOL"));
                cell = row.createCell(1);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("NAMECOL"));
                cell = row.createCell(2);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("VALUECOL"));
            }
    
            // 컨텐츠 타입과 파일명 지정
            response.setContentType("ms-vnd/excel");
            response.setHeader("Content-Disposition""attachment;filename=test.xls");
 
            // 엑셀 출력
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
cs


마지막으로

home.jsp

1
2
3
<form name="excelForm" id="excelForm" method="POST" action="./excelDown.do">
    <input type="submit" id="excelDown" value="EXCEL 다운"/>
</form>
cs

 

후에 실행해보면 ExcelFile을 Down 받아서 보여줍니다.


감사합니다.

'SPRING' 카테고리의 다른 글

SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring FileUpload 하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.



뿌려줄 데이터입니다.


HomeController.java

결과를 이부분에 저장했습니다.

1
model.addAttribute("dbList", list);
cs


home.jsp

저장한 것을 list라는 변수에 담아 처리했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <!-- 결과값 출력 -->
<table border="1">
    <tr>
        <td>번호</td>
        <td>작성자</td>
        <td>기타</td>
    </tr>
    <c:forEach var="list" items="${dbList }">
        <tr>
            <td>${list.IDCOL }</td>
            <td>${list.NAMECOL }</td>
            <td>${list.VALUECOL }</td>
        </tr>
    </c:forEach>
</table>
cs


감사합니다.

'SPRING' 카테고리의 다른 글

Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

이번엔 spring에서 resource 사용설정을 써볼꼐요


servlet-context.xml

1
<mvc:resources location="/resources/" mapping="/resources/**" />
cs



home.jsp

1
2
3
4
5
6
7
<script src="/spring/resources/js/jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function(){
            alert("start!");
        });
    </script>
 
cs



감사합니다.

'SPRING' 카테고리의 다른 글

Spring Excel down하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring DB 로그 추가하기  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

해당 에러시에는 spring URL및 RequestMethod가 똑같아서 나오는 에러이므로 변경하면 해결가능합니다.

 

'SPRING' 카테고리의 다른 글

SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring DB 로그 추가하기  (0) 2019.03.26
spring MVC DB 연결하기  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
출처 : http://mrjh.com/wiki/content.php?no=101

###############################################

# FaTAL : 가장 크리티컬한 에러가 일어 났을 때 사용합니다.
# ERROR : 일반 에러가 일어 났을 때 사용합니다.
# WARN : 에러는 아니지만 주의할 필요가 있을 때 사용합니다.
# INFO : 일반 정보를 나타낼 때 사용합니다.
# DEbUG : 일반 정보를 상세히 나타낼 때 사용합니다.

################################################



######################################################################
#%p  debug, info, warn, error, fatal 등의 priority 가 출력된다.  
#%m  로그내용이 출력됩니다
#%d  로깅 이벤트가 발생한 시간을 기록합니다.
#  포맷은 %d{HH:mm:ss, SSS}, %d{yyyy MMM dd HH:mm:ss, SSS}같은 형태로 사용하며 SimpleDateFormat에 따른 포맷팅을 하면 된다
#%t  로그이벤트가 발생된 쓰레드의 이름을 출력합니다.  
#%%  % 표시를 출력하기 위해 사용한다.  
#%n  플랫폼 종속적인 개행문자가 출력된다. \r\n 또는 \n 일것이다.  
#%c  카테고리를 표시합니다
#  예) 카테고리가 a.b.c 처럼 되어있다면 %c{2}는 b.c가 출력됩니다.
#%C  클래스명을 포시합니다.
#  예)클래스구조가 org.apache.xyz.SomeClass 처럼 되어있다면 %C{2}는 xyz.SomeClass 가 출력됩니다
#%F  로깅이 발생한 프로그램 파일명을 나타냅니다.
#%l  로깅이 발생한 caller의 정보를 나타냅니다
#%L  로깅이 발생한 caller의 라인수를 나타냅니다
#%M  로깅이 발생한 method 이름을 나타냅니다.
#%r  어플리케이션 시작 이후 부터 로깅이 발생한 시점의 시간(milliseconds)
#%x  로깅이 발생한 thread와 관련된 NDC(nested diagnostic context)를 출력합니다.
#%X  로깅이 발생한 thread와 관련된 MDC(mapped diagnostic context)를 출력합니다.

#######################################################################



#최상위 카테고리에 INFO로 레벨 설정 및 appender로 stdout, rolling을 정의
log4j.rootLogger=DEBUG, stdout, rolling

#stdout 어펜더는 콘솔에 뿌리겠다는 정의
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

#stdout 어펜더는 patternlayout을 사용하겠다는 정의
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

#페턴은 다음과 같이 포맷팅 하겠다는 것을 정의
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy\ub144 MM\uc6d4 dd\uc77c HH:mm(ss)}] _%-5p_ [%t] %-17c{2} (%13F:%L) %3x -->\ub0b4\uc6a9 : %m%n



#역시나 rolling 어펜더는 파일로 처리한다라고 정의
log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

#로그 파일 이름은 output.log
log4j.appender.rolling.File=output.log

#true면 톰캣을 내렸다 올려도 파일이 리셋되지 않습니다.
log4j.appender.rolling.Append=true

#파일 최대 사이즈는 500KB로 설정
log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

#역시나 rolling 어펜더는 패턴 레이아웃을 사용하겠다고 정의
log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

#rolling 어펜더는 패턴 레이아웃 포맷
log4j.appender.rolling.layout.ConversionPattern=[%d{yyyy\ub144 MM\uc6d4 dd\uc77c HH:mm(ss)}] _%-5p_ [%t] %-17c{2} (%13F:%L) %3x -->\ub0b4\uc6a9 : %m%n

 

'SPRING' 카테고리의 다른 글

SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
spring DB 로그 추가하기  (0) 2019.03.26
spring MVC DB 연결하기  (0) 2019.03.26
Eclipse 마켓(STS, spring Tool : STS) 설치하기  (0) 2015.05.28

+ Recent posts