반응형

# 웹 서버 (Web Server)

  • HTTP 기반으로 동작
  • 정적 리소스 제공, 기타 부가기능 (정적(파일) HTML, CSS, JS, 이미지, 영상)
  • 예) NGINX, APACHE

# 웹 애플리케이션 서버 (WAS : Web Application Server)

  • HTTP 기반으로 동작
  • 웹 서버 기능 포함
  • 프로그램 코드를 실행해서 애플리케이션 로직 수행 (동적 HTML, HTTP API(JSON) / 서블릿, JSP, 스프링 MVC)
  • 예) 톰캣(Tomcat) Jetty, Undertow

# 웹 서버와 웹 애플리케이션 서버의 차이점.

  • 웹 서버는 정적 리소스(파일), WAS는 애플리케이션 로직
  • 웹 서버와 웹 애플리케이션 서버의 용어 및 경계가 모호함 (웹 서버도 프로그램을 실행하는 기능을 포함하기도 함 / 웹 애플리케이션 서버도 웹 서버의 기능을 제공함)
  • 자바는 서블릿 컨테이너 기능을 제공하면 WAS
  • 서블릿 없이 자바코드를 실행하는 서버 프레임워크도 있음
  • WAS는 애플리케이션 코드를 실행하는데 더 특화
반응형

'메모장' 카테고리의 다른 글

오라클 문자셋, 언어셋 확인방법  (0) 2022.07.11
오라클 일련번호 증가 쿼리  (0) 2022.05.10
zip 파일 다운로드  (0) 2022.04.26
엑셀 다운로드 (자바, 자바스크립트)  (0) 2022.04.24
context-util properties 관련  (0) 2022.04.24
반응형

# 파일 다운로드 (zip)

## context-util.xml

<util:properties id="fileUploadProp">
	<prop key="hrPhotoUploadPath">/APP/mis/MIS_DATA/upload/hr/photo</prop>
	<prop key="hrPhotoUploadPath">/APP/mis/MIS_DATA/upload/photoZip</prop>
</util:properties>

## JAVA

@Value("#{fileUploadProp['hrPhotoUploadPath']}")
private String photoAccessUrl;
@Value("#{fileUploadProp['hrPhotoAccessPath']}")
private String photoAccessPath;

@RequestMapping(value="goAllDownload.ex")
public void allDownload(HttpServletRequest request, HttpServletResponse response, @RequestParam("imgEmpNo") String tmpEmpNo) throws Exception {
String[] empNos = tmpEmpNo.split(",");
for (int i = 0; i < empNos.length; i++) {
	if (empNos[i] == null || "".equals(empNos[i].trim())) {
		throw new BusinessException("errors.required", new String[]{"@title.bmp"});
	}
}

// 파일 저장 경로.
String path = photoAccessPath;
String zipFileName = "파일명_" + System.currentTimeMillis() + ".zip";
String zipFile = path + zipFileName;

File file = null;

ArrayList<String> fileList = new ArrayList<String>();

for (int i = 0; i < empNos.length; i++) {
	String fileUrl = photoAccessUrl + "P" + empNos[i] + ".BMP";

	file = new File(fileUrl);

	// 파일 존재여부 체크
	if (file.exists()) {
		if (file.isFile()) {
			fileList.add(fileUrl);
		}
	}
}

if (fileList.size() != 0) {
 FileOutputStream fos = null;
 FileInputStream fis = null;
 ZipOutputStream zipOut = null;

	try {
  fos = new FileOutputStream(zipFile);
		zipOut = new ZipOutputStream(fos);

		for (int i = 0; i < fileList.size(); i++) {
  File fileSize = new File(fileList.get(i));
  byte[] buf = new byte[(int)fileSize.length()];
  
			fis = new FileInputStream(fileList.get(i));
			path p = paths.get(fileList.get(i));
			String fileName = p.getFileName().toString();
   
			ZipEntry ze = new ZipEntry(fileName);
			zipOut.putNextEntry(ze);

			int len = 0;
			while((len = in.read(buf)) != -1) {
				zipOut.write(buf, 0, len);
			}

			fis.close();
   zipOut.closeEntry();
		}

  zipOut.close();
  fos.close();
  
		response.setContentType("application/zip");
		response.setHeader("Content-Transfer-Encoding:", "binary");
		response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");

  // 다운로드 위해 추가.
		FileInputStream fiss = new FileInputStream(zipFile);
  BufferedInputStream bis = new BufferedInputStream(fiss);
  ServletOutputStream so = response.getOutputStream();
  BufferedOutputStream bos = new BufferedOutputStream(so);
  
 File fileSizeZip = new File(zipFile);
 byte[] data = new byte[(int)fileSizeZip.length()];
  int input = 0;
  while((input = bis.read(data)) != -1) {
    bos.write(data, 0, input);
    bos.flush();
  }
  
  if (bos != null) bos.close();
  if (bis != null) bis.close();
  if (so != null) so.close();
  if (fiss != null) fiss.close();
	} catch(IOException e) {
		e.printStackTrace();
	} finally {
   // 저장경로에 임시저장 된 zip 파일 삭제.
   File createZipFile = new File(zipFile);
   if (createZipFile.exists()) createZipFile.delete();
 }
}

}


## 문제점

  • 정해진 위치에 zip 파일 다운로드 정상적으로 수행(정해진 경로에서 파일 열었을땐 이상 없음). 하지만, 파일 다운로드 수행 시 열기, 저장 클릭 후 해당 파일 열 경우 zip 파일이 아니라는 에러 발생.
  • 파일사이즈 관련 문제 발생.

## 해결방법

  • 다운로드 위한 코드 추가하여 해결.
  • 추가로 별도의 경로에 임시 저장된 zip파일 삭제 코드 추가.
  • 고정된 파일 사이즈에서 해당 파일의 사이즈로 변경
반응형
반응형

# 엑셀 다운로드 관련

  • 엑셀 다운로드 기능 구현 관련 자바소스
@RequestMapping(value="goExcelFileDown.ex", method=RequestMethod.POST)
public void goExcelFileDown(HashMap map, HttpServletRequest req, HttpServletResponse response) throw Exception {
String columnIdsArray = req.getParameter("columnArr");
String titleArray = req.getParameter("titleArr");

List<String> columnIdList = new ArrayList<String>(Arrays.asList(columnIdsArray.split(",");
List<String> titleList = new ArrayList<String>(Arrays.asList(titleArrayArray.split(",");

XSSFWorkbook xlsWb = new XSSFWorkbook(); // xlsx 엑셀 2007 이상
Sheet sheet1 = xlsWb.createSheet("시트1이름");
Sheet sheet2 = xlsWb.createSheet("시트2이름");

// 폰트
Font hFont = xlsWb.createFont();
hFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

// xlsx 스타일
// 제목 스타일
CellStyle hstyle = xlsWb.createCellStyle();
hStyle.setAlignment(CellStyle.ALIGN_CENTER);
hStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
hStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
hStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
hStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
hStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
hStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
hStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
hStyle.setFont(hFont);

// 내용 스타일
CellStyle bstyle = xlsWb.createCellStyle();
bStyle.setAlignment(CellStyle.ALIGN_CENTER);
bStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
bStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
bStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
bStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
bStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

// 내용 스타일 - 조건에 따라 다른 스타일 적용위함.
CellStyle dstyle = xlsWb.createCellStyle();
dStyle.setAlignment(CellStyle.ALIGN_CENTER);
dStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
dStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
dStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
dStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
dStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
dStyle.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
dStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

Row row1 = null;
Row row2 = null;

Cell cell1 = null;
Cell cell2 = null;

int colIndex1 = 0;
int colIndex2 = 0;

row1 = sheet1.createRow(0);
row1.setHeight((short)450);
sheet1.addMergeRegion(new CellRangeAddress(0, 0, 3, 4)); // 셀 병합
sheet1.addMergeRegion(new CellRangeAddress(0, 0, 5, 6)); // 셀 병합

for (Iterator iterator = titleList.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    
    cell1 = row.createCell(colIndex1);
    cell1.setCellValue(string);
    cell1.setCellStyle(hStyle);

     // 셀에 따라 넓이 다르게 설정
    if (colIndex1 == 2) {
        sheet1.setColumnWidth(colIndex1, 14000);
    } else if (colIndex1 == 6) {
        sheet1.setColumnWidth(colIndex1, 10000);
    } else  {
        sheet1.setColumnWidth(colIndex1, 4500);
    }
    colIndex1++;
}

row2 = sheet2.createRow(0);
row2.setHeight((short)450);
sheet2.addMergeRegion(new CellRangeAddress(0, 0, 3, 4)); // 셀 병합
sheet2.addMergeRegion(new CellRangeAddress(0, 0, 5, 6)); // 셀 병합

for (Iterator iterator = titleList.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    
    cell2 = row.createCell(colIndex2);
    cell2.setCellValue(string);
    cell2.setCellStyle(hStyle);

     // 셀에 따라 넓이 다르게 설정
    if (colIndex2 == 2) {
        sheet2.setColumnWidth(colIndex2, 14000);
    } else if (colIndex2 == 6) {
        sheet2.setColumnWidth(colIndex2, 10000);
    } else  {
        sheet2.setColumnWidth(colIndex2, 4500);
    }
    colIndex2++;
}

Liist<Map<String, String>> resultMap1 = new ArrayList<Map<String, String>>();
Liist<Map<String, String>> resultMap2 = new ArrayList<Map<String, String>>();

resultMap1 = (List<Map<String, String>>) dao.selectResult1();
resultMap2 = (List<Map<String, String>>) dao.selectResult2();

int rowIndex1 = 0;
int rowIndex2 = 0;

for (Map<String, String> forMap : resultMap1) {
    row1 = sheet1.createRow(rowIndex1);
    row1.setHeight((short)450);

    colIndex1 = 0;
    for (Iterator iterator = columnIdList.iterator(); iterator.hasNext();) {
        String string = (String) iterator.next();
        
         cell1 = row1.createCell(colIndex1);
        String cellVal = (EgovStringUtil.isNull(String.valueOf(forMap.get(string)))  || String.valueOf(forMap.get(string)).equals("null")) ? "" : string.valueOf(forMap.get(string));
        cell1.setCellValue(cellVal);
        celll1.setCellStyle(bStyle);

        colIndex1++;
    }
    rowIndex1++;
}

for (Map<String, String> forMap : resultMap2) {
    row2 = sheet2.createRow(rowIndex2);
    row2.setHeight((short)450);

    colIndex2 = 0;
    for (Iterator iterator = columnIdList.iterator(); iterator.hasNext();) {
        String string = (String) iterator.next();
        
         cell2 = row2.createCell(colIndex2);
        String cellVal = (EgovStringUtil.isNull(String.valueOf(forMap.get(string)))  || String.valueOf(forMap.get(string)).equals("null")) ? "" : string.valueOf(forMap.get(string));
        cell2.setCellValue(cellVal);
        celll2.setCellStyle(bStyle);

        colIndex2++;
    }
    rowIndex2++;
}

try {
    String pathDir = JProperties.getString(GlobalVariables.DEFAULT_FILE_UPLOAD_PATH_KEY) + File.separator + "fi" + File.separator + "9999" + File.separator + "99" File.separator + "99";

    String fileName = File.separator + ".xlsx";
    String readlFileName = "파일명입력.xlsx";

    File xlsFileDir = new File(pathDir);
    
    if (!xlsFileDir.exists()) xlsFileDir.mkdirs();
    
    File xlsFile = new File(pathDir + fileName);

    if (xlsFile.exists()) xlsFileDir.delete();

    if (xlsFile.createNewFile()) {
        FileOutputStream fileOut = new FileOutputStream(xlsFile);
        xlsWb.write(fileOut);

        String strFileName = URLEncoder.encode(new String(realFileName.getBytes("8859_1"), "euc-kr"), "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename = " + strFileName + ";");

        FileInputStream fis = new FileInputStream(xlsFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ServletOutputStream so = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(so);

        byte[] data = new byte[2048];
        int input = 0;
        while ((input = bis.read(data)) != -1) {
                bos.write(data, 0, input);
                bos.flush();
        }    

        if (bos != null) bos.close();
        if (bis != null) bis.close();
        if (so != null) so.close();
        if (fis != null) fis.close();
    }
} catch (FileNotFoundException e) {
        e.printStackTrace();
} catch (IOException e) {
        e.printStackTrace();
}

}

## 자바스크립트

  • 엑셀 다운로드 관련 자바 스크립트.
function excelDown() {
    if (!confirm("다운로드 하시겠습니까?")) return;

    var columnIdsArray = new Array();
    var titleArray = new Array();

    columnIdsArray.push("PROJECT_NO");
    columnIdsArray.push("PROJECT_NAME");
    columnIdsArray.push("ACCOUNT_OWNER");

    titleArray.push("사업부호");
    titleArray.push("사업명");
    titleArray.push("책임자");

    var paramMap = "";
    
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readSate == 4 && this.status == 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');

            if (disposition && disposition.indexOf('attachment') != -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
        }

        window.navigator.msSaveOrOpenBlob(this.response, "파일명입력.xlsx");
    }

    xhr.open('POST', '<c:url value="goExcelFileDown.ex" />');
    xhr.responseType = 'blob';
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(paramMap + "columnIdsArray=" + columnIdsArray + "&titleArray=" + titleArray);
}
반응형
반응형

# context-util.xml

<util:properties id="fileUploadProp">
    <prop key="fileUploadPath">/APP/pms/upload/temp</prop>
    <prop key="viewPath">http://100.100.100.30:8250/pms/images/upload/temp</prop>
</util:properties>

 

## JSP에서 사용 시

  • context-util 에 설정한 properties JSP에서 사용 시 아래와 같이 사용.
<spring:eval var="fileUploadPath" expression="@fileUploadProp['fileUploadPath']" scope="page"/>

사용 시 "${fileUploadPath}"로 사용.

## JAVA에서 사용 시

  • context-util 에 설정한 properties JAVA에서 사용 시 아래와 같이 사용.
@Value("#{fileUploadProp['fileUploadPath']}")
private String uploadPath;

사용 시 uploadPath 변수 이용해서 사용.



반응형

+ Recent posts