Java

[JAVA + VUE.JS] 엑셀 다운로드 만드는 예제

[vue 단 호출 코드]

    excelDownload() {
      const params = {
        actionType: 'TEST01',
        userId: pUserId,
      };

      this.axiosExcelDownload(params, "테스트 엑셀파일");
    },
    
	axiosExcelDownload(params, fileName) {
      const param = params;
      param.fileName = fileName;

      axios({
        method: 'POST',
        url: '/excelDown.do',
        responseType: 'blob',
        headers: {
          'X-Requested-Type': 'XHR',
        },
        data: new URLSearchParams(param),
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
        const link = document.createElement('a');

        link.href = url;
        link.setAttribute('download', `${fileName}.xlsx`);
        document.body.appendChild(link);
        link.click();
      }).catch((err) => {
      }).finally(() => {
      });
    },

 


 

[Contorller코드]

public class ExcelController extends AbstractBaseService
{
	..........생략.........
	
	@RequestMapping(value={"/excelDown.do", "/buz/excelDown.do"},  method = RequestMethod.POST)
	public ExcelDownloadService excelDown(HttpServletRequest request, ModelMap model) throws Exception 
	{
		ArrayList<DataResult> result = "쿼리 결과데이터";
		model.addAttribute("DATALIST", result);
		model.addAttribute("request", request);
		
		return new ExcelDownloadService();		
	}
.........
}

 

[Service 코드]

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.AbstractView;


public class ExcelDownloadService extends AbstractView
{
	protected Logger log = LoggerFactory.getLogger(this.getClass());
	
	private static final String WRAP_STR = "¿";
	private static final String EXCE_WRAP_STR = "n";
	private static final String SPAN_GUBUN = "#";
	
	
	@Override
	@SuppressWarnings("unchecked")
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		ServletOutputStream out = null;
		
		ArrayList<ArrayList<CommonParamMap>> list = null;
		ArrayList<CommonParamMap> excelData = null;
		ArrayList<DataResult> result = (ArrayList<DataResult>)model.get("DATALIST");
		
		this.request = (HttpServletRequest)model.get("request");
		this.commonDAO = (CommonDAO)model.get("commonDAO");
		this.logService = (LogService)model.get("logService");
		
		SXSSFWorkbook wb = new SXSSFWorkbook(500);
		wb.setCompressTempFiles(true);
		
		try
		{
			String strFileName = request.getParameter("fileName").toString();
			for(int iSheet = 0; iSheet < result.size(); iSheet++) 
			{
				list = (ArrayList<ArrayList<CommonParamMap>>)result.get(iSheet).get("resultList");
				
				Sheet ds = wb.createSheet();
				
				if (list.size() == 2)
				{				
					createColHeader(wb, ds, (ArrayList<CommonParamMap>)list.get(0), null);
					makeRowData(wb, ds, (ArrayList<CommonParamMap>)list.get(1), (ArrayList<CommonParamMap>)list.get(0));
					
					excelData = (ArrayList<CommonParamMap>)list.get(1);
				}
				
				// Colspan/Rowspan
				else if (list.size() == 3)
				{
					createColHeader(wb, ds, (ArrayList<CommonParamMap>)list.get(1), (ArrayList<CommonParamMap>)list.get(0));
					makeRowData(wb, ds, (ArrayList<CommonParamMap>)list.get(2), (ArrayList<CommonParamMap>)list.get(1));
					
					excelData = (ArrayList<CommonParamMap>)list.get(2);
				}
			}
				
			res.setContentType("application/vnd.ms-excel; charset=UTF-8");
			res.setHeader("Content-Disposition", "attachment; filename="" + URLEncoder.encode(excelName, "utf-8") + "";");
			
			out = res.getOutputStream();
			wb.write(out);
		}
		catch (Exception e)
		{
			log.error("Excel Download Error", e);
		}
		finally
		{
			list = null;

			if (out != null)
			{
				out.close();
			}

			wb.dispose();
		}
		
		
	}
	
	@SuppressWarnings("unchecked")
	private void createColHeader(SXSSFWorkbook wb, Sheet sheet, ArrayList<CommonParamMap> data, ArrayList<CommonParamMap> headerInfo)
	{
		List<String> keys = data.get(0).keyList();
		Row headRow = null;
		CellStyle cs = null;
		Cell hCell = null;	
		
		String value = null;
				
		for (int i = 0; i < data.size() - 1; i++)
		{
			headRow = sheet.createRow(i);
			headRow.setHeightInPoints((2 * sheet.getDefaultRowHeightInPoints() + 5));
					
			for(int j = 0; j < keys.size(); j++) 
			{
				value = data.get(i).get(keys.get(j)).toString();
				
				if ("".equalsIgnoreCase(value))
				{
					continue;
				}
				
				value = value.replaceAll(WRAP_STR, EXCE_WRAP_STR);
				
				hCell = headRow.createCell(j);	
				cs = wb.createCellStyle();
				cs.setWrapText(true);
				cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
				
				hCell.setCellStyle(cs);
				hCell.setCellType(HSSFCell.CELL_TYPE_STRING);
				hCell.setCellValue(value);
				
				if (headerInfo == null)
				{
					continue;
				}
				else
				{
					setHeaderStyle(sheet, headerInfo, i, j);
				}
				
				sheet.setColumnWidth(j, 5000);
			}
		}
		
		headRow = null;
		keys = null;
		cs = null;
		hCell = null;
	}
	
	@SuppressWarnings("unchecked")
	private void setHeaderStyle(Sheet sheet, ArrayList<CommonParamMap> headerInfo, int i, int j)
	{
		List<String> keys = headerInfo.get(0).keyList();
		String value = headerInfo.get(i).get(keys.get(j)).toString();
		
		if (!"".equalsIgnoreCase(value))
		{
			String[] span = value.split(SPAN_GUBUN);
			
			int colspan = Integer.parseInt(span[0]) - 1;
			int rowspan = Integer.parseInt(span[1]) - 1;
			
			sheet.addMergedRegion(new CellRangeAddress(i, i + rowspan, j, j + colspan));
		}
	}
	
	@SuppressWarnings("unchecked")
	private void makeRowData(SXSSFWorkbook wb, Sheet sheet, ArrayList<CommonParamMap> data, ArrayList<CommonParamMap> header)
	{
		if(data.size() == 0) return;
		
		int headerSize = header.size() - 1;

		List<String> keys = data.get(0).keyList();
		
		Row dRow = null;
		Cell dCell = null;
		CellStyle style = null;
		
		String value = null;
		
		for(int i = 0; i < data.size(); i++)
		{
			dRow = sheet.createRow(i + headerSize);
			
			for(int j = 0; j < keys.size(); j++)
			{
				dCell = dRow.createCell(j);
				style = wb.createCellStyle();

				value = data.get(i).get(keys.get(j)).toString();
				
				if (value.length() > 0)
				{
					if(header.get(headerSize).get(keys.get(j)).toString().equals("numeric"))
					{				
						style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
						style.setAlignment(CellStyle.ALIGN_RIGHT);
						dCell.setCellStyle(style);
						dCell.setCellValue(Double.parseDouble(value));	
					}
					else
					{
						value = value.replaceAll(WRAP_STR, EXCE_WRAP_STR);
						
						style.setWrapText(true);
						style.setAlignment(CellStyle.ALIGN_LEFT);
						style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
						
						dCell.setCellStyle(style);		
						dCell.setCellType(HSSFCell.CELL_TYPE_STRING);
						dCell.setCellValue(value);						
					}
					
					sheet.setColumnWidth(j, 5000);
				}
			}
		}
		
		keys = null;		
		dRow = null;
		dCell = null;
		style = null;
	}
}

 

[공통 파라미터 클래스]

import egovframework.rte.psl.dataaccess.util.EgovMap;
	
public class CommonParamMap extends EgovMap implements Cloneable
{
	private static final long serialVersionUID = 3848851032730232522L;

	@Override
	public Object get(Object key)
	{
		if(super.containsKey(key))
		{
			Object obj = super.get(key) == null? "" : super.get(key);
			if(obj.getClass().getName().equals("java.sql.Date")) obj = obj.toString();
			return obj;
		}
		else
		{
			return "";
		}
	}
}

 

 

[공통 쿼리 데이터 결과 데이터 담는 class]

import java.util.List;

import egovframework.rte.psl.dataaccess.util.EgovMap;

public class DataResult extends EgovMap
{
	private static final long serialVersionUID = 5073470731816469287L;

	public DataResult(CommonParamMap statusCode, List<CommonParamMap> dataList)
	{
		super();
		this.put("statusCode",	statusCode.get("statusCode"));
		this.put("statusMsg",		statusCode.get("statusMsg");		
		this.put("rtnStr",	statusCode.get("rtnStr");
		this.put("rowCnt",		statusCode.get("rowCnt");	
		this.put("resultList",			dataList);
	}
}

 

다음은 보건 복지부 제품설명회 양식대로 엑셀 다운로드를 만들어보자


ALTER PROCEDURE SP_EXCEL_DN
(
	@P_ACTION_TP			VARCHAR(30) = 'Q'	
,	@P_USER_ID			VARCHAR(30) = ''

,	@P_ERROR_CD			VARCHAR(30)		= ''	OUTPUT	-- 사용자 에러코드 리턴  
,	@P_ROW_COUNT		INT				= 0		OUTPUT	-- 실행/리턴하는 레코드행수 
,	@P_RETURN_STR		NVARCHAR(100)	= ''	OUTPUT	-- 사용자 지정 반환값
)
AS 
SET NOCOUNT ON  
SET ANSI_WARNINGS OFF
SET ARITHIGNORE ON
SET ARITHABORT OFF

BEGIN
    BEGIN TRY
    
    
--프로시저 엑셀 다운로드
IF @P_ACTION_TP = 'EXCEL_DN'
BEGIN

	-- Colspan / Rowspan
	SELECT '1#2'				AS ROW_NUM
			, '1#2'				AS USER_NAME

			, '2#1'				AS COMAPNY_NAME
			, ''				AS DEPT_NAME

			, '4#1'				AS DATA3_AMT
			, ''				AS DATA2_AMT
			, ''				AS DATA4_AMT
			, ''				AS DATA1_AMT
			, '1#2'				AS LOC
			, '1#2'				AS SDATE					
	UNION ALL
	SELECT	''				AS ROW_NUM
			, ''			AS USER_NAME

			, ''			AS COMAPNY_NAME
			, ''			AS DEPT_NAME

			, ''			AS DATA3_AMT
			, ''			AS DATA2_AMT
			, ''			AS DATA4_AMT
			, ''			AS DATA1_AMT
			, ''			AS LOC
			, ''			AS SDATE

	-- 컬럼 헤더
	SELECT '연번'				AS ROW_NUM
			, '제품명(표준코드명칭)' AS USER_NAME

			, '의료인 정보'		AS COMAPNY_NAME
			, ''				AS DEPT_NAME

			, '지원금액'		AS DATA3_AMT
			, ''				AS DATA2_AMT
			, ''				AS DATA4_AMT
			, ''				AS DATA1_AMT

			, '장소'			AS LOC
			, '일시'			AS SDATE
	UNION ALL
	SELECT	''					AS ROW_NUM
			, ''				AS USER_NAME

			, '성명'			AS COMAPNY_NAME
			, '소속'			AS DEPT_NAME
			, '교통비'			AS DATA3__AMT
			, '기념품비'		AS DATA2_AMT
			, '숙박비'			AS DATA4_AMT
			, '식음료비'		AS DATA1_AMT

			, ''				AS LOC
			, ''				AS SDATE

	UNION ALL
	
	SELECT 'string','string','string','string','string','string','string','string','string','string';

	-- ROW 데이터 조회	
	SELECT 
		ROW_NUMBER() OVER(ORDER BY a.SEQ_ID ) AS ROW_NUM 
		, a.USER_NAME
		, a.COMAPNY_NAME	
		, a.DEPT_NAME						
		, FORMAT(a.DATA1_AMT, '#,#') +'원' AS DATA1_AMT 
		, FORMAT(a.DATA2_AMT, '#,#') +'원' AS DATA2_AMT 
		, FORMAT(a.DATA3_AMT, '#,#') +'원' AS DATA3_AMT 
		, FORMAT(a.DATA4_AMT, '#,#') +'원' AS DATA4_AMT 
		, ''				AS LOC
		, ''				AS SDATE				
	 FROM TB_TEST a
	; 

    -- 실행된레코드행수 받기
    SELECT @P_ROW_COUNT = @@ROWCOUNT;

    IF @P_ROW_COUNT > 0
        SET @P_ERROR_CD = 'MSG0001'; -- 정상적으로 조회가 되었습니다
    ELSE
        SET @P_ERROR_CD = 'MSG0006'; -- 조회된 자료가 없습니다
END	

	END TRY
    BEGIN CATCH
        SELECT ERROR_MESSAGE();
        DECLARE @V_EXEC_INFO NVARCHAR(MAX);

		-- 실행 조건
		SELECT @V_EXEC_INFO = N'SP_EXCEL_DN '
				+ N'  @P_ACTION_TP=N''' + ISNULL(@P_ACTION_TP, '') + ''' '		
				+ N', @P_USER_ID=N''' + ISNULL(@P_USER_ID, '') + ''' '

		-- SP에러로그 기록
		INSERT SYS_ERR_LOG (ERR_PROC, ERR_CD, ERR_STA, ERR_MSG, EXEC_PROC_INFO)
		SELECT
			ERR_PROC = ERROR_PROCEDURE(),
			ERR_CD = CONVERT(VARCHAR(100), ERROR_NUMBER()),
			ERR_STA = ISNULL(SUBSTRING(@P_WORK_TP,1,1), 'X') + '|' + CONVERT(VARCHAR(100), ERROR_SEVERITY()) + '|' + CONVERT(VARCHAR(100), ERROR_STATE()) + '|' + CONVERT(VARCHAR(100), ERROR_LINE()),
			ERR_MSG = ERROR_MESSAGE(),
			EXEC_PROC_INFO = @V_EXEC_INFO
		;

		-- CRUD 에러코드 반환
		SELECT @P_ERROR_CD = (CASE SUBSTRING(@P_WORK_TP,1,1)
									WHEN 'Q' THEN 'ERR0006'				 -- 조회시 에러가 발생하였습니다. 
									WHEN 'N' THEN 'ERR0008'			
									WHEN 'U' THEN 'ERR0009'			
									WHEN 'D' THEN 'ERR0010'			
									ELSE 'ERR0000'
								END);
    END CATCH;
END

 

[AbstractBaseService 클래스]

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;


public abstract class AbstractBaseService
{
	protected Logger log  = LoggerFactory.getLogger(this.getClass());
	
	@Autowired protected ApplicationContext appCtx;
	@Autowired protected ServletContext svlCtx;
	
	/** CommonDAO */
    @Resource(name="commonDAO")
    protected CommonDAO commonDAO;
    
	@Resource(name = "systemProp")
	private Properties systemProp;
	
    protected Object invokeInsert(String commandId, CommonParamMap map) throws DataAccessException
    {
    	return invokeInsert("", commandId, map);
    }
    
    protected int invokeUpdate(String commandId, CommonParamMap map) throws DataAccessException
    {
    	return invokeUpdate("", commandId, map);
    }

    protected int invokeDelete(String commandId, CommonParamMap map) throws DataAccessException
    {
    	return invokeDelete("", commandId, map);
    }
    
    protected Object invokePK(String commandId, CommonParamMap map) throws DataAccessException
    {
    	return invokePK("", commandId, map);
    }

    @SuppressWarnings("unchecked")
	protected List<CommonParamMap> invokeList(String dao, String commandId, CommonParamMap map) throws DataAccessException
    {
    	return commonDAO.list(dao, commandId, map);
    }
    
    protected Object invokeInsert(String dao, String commandId, CommonParamMap map) throws DataAccessException
    {
    	return commonDAO.insert(dao, commandId, map);
    }
    
    protected int invokeUpdate(String dao, String commandId, CommonParamMap map) throws DataAccessException
    {
    	return commonDAO.update(dao, commandId, map);
    }

    protected int invokeDelete(String dao, String commandId, CommonParamMap map) throws DataAccessException
    {
    	return commonDAO.delete(dao, commandId, map);
    }
    
    protected Object invokePK(String dao, String commandId, CommonParamMap map) throws DataAccessException
    {
    	return commonDAO.selectByPk(dao, commandId, map);
    }
    
	private class AjaxInkoveInfo
	{
		final CommonParamMap param;
		final String ajaxCode;
		AjaxInkoveInfo(CommonParamMap param, String ajaxCode)
		{
			this.param = param;
			this.ajaxCode = ajaxCode;
		}
	}
	
    protected ResponseEntity<String> requestAjax(String dao, HttpServletRequest request)
    {    	
    	ArrayList<DataResult> resultList = requestProcCall(dao, request);
    	
    	if(resultList == null || resultList.isEmpty())
    	{
    		return new ResponseEntity<>("[[]]", HttpStatus.OK);
    	}
    	else
    	{
    		return Utility.getJSONResponse(resultList.size() == 1 ? resultList.get(0) : resultList);
    	}
    }
    
    protected ArrayList<DataResult> requestDataResultAjax(String dao, HttpServletRequest request)
    {    	
    	ArrayList<DataResult> resultList = requestProcCall(dao, request);
    	
    	return resultList;
    }
    
    protected ArrayList<DataResult> requestProcCall(String dao, HttpServletRequest request)
    {
    	CommonParamMap resultCode = new CommonParamMap();
    	try
    	{
	    	AjaxInkoveInfo[] info = createAjaxParam(request);
	    	ArrayList<DataResult> resultList = new ArrayList<>();

	    	for(int ii = 0; ii < info.length; ii++)
	    	{
    			List<CommonParamMap> list = invokeList(dao, info[ii].ajaxCode, info[ii].param);
        		String returnCode = (String)info[ii].param.get(ComnConst.ARGS_ERROR_CODE);
        		
        		resultCode.put(ComnConst.ARGS_ERROR_CODE, returnCode);
        		resultCode.put(ComnConst.ARGS_RETURN_STRING, info[ii].param.get(ComnConst.ARGS_RETURN_STRING));
        		resultCode.put(ComnConst.ARGS_ROW_COUNT, info[ii].param.get(ComnConst.ARGS_ROW_COUNT));
        		
    			CommonParamMap m = new CommonParamMap(); 
    			m.put(ComnConst.ARGS_ERROR_CODE, returnCode);
    			List<CommonParamMap> msgList = invokeList("", ServiceGubunMap.getQueryId("SYSTEM_A_1"), m);
    			if(msgList != null && !msgList.isEmpty())
    			{
    				resultCode.put(ComnConst.ARGS_ERROR_MSG, msgList.get(0).get("errorStr"));
    			}
        		
        		resultList.add(new DataResult(resultCode, list));
    		}
    		return resultList;
    	}
    	catch(Exception ex)
    	{
    		StackTraceElement[] list = ex.getStackTrace();
    		
    		if(list.length > 0)
    		{
    			log.error(String.format("%s at %s - %d", ex.getClass().getName(), list[0].getFileName(), list[0].getLineNumber()));
    			log.info(ex.toString());
    			log.info(ex.getMessage());
    		}
    		return new ArrayList<>();
    	}
    }    
    
    protected ResponseEntity<String> requestAjaxN(HttpServletRequest request) throws DataAccessException
    {
    	int effected = 0;
    	AjaxInkoveInfo[] info = createAjaxParam(request);
    	try
    	{
    		for(int ii = 0; ii < info.length; ii++)
    		{
    			effected += invokeUpdate(info[ii].ajaxCode, info[ii].param);
    		}
    		CommonParamMap result = new CommonParamMap();
    		result.put("effected", effected);
    		return Utility.getJSONResponse(result);
    	}
    	catch(Exception ex)
    	{
    		return new ResponseEntity<>("[[]]", HttpStatus.OK);
    	}
    }
    
    protected void addAjaxRequestParam(CommonParamMap param)
    {
    	UserModel userSession = Utility.getPrincipal();
    	if(userSession == null)
    	{
    		param.put("dmn", "anonymous");
    		param.put("userId", "anonymous");
    		param.put("clientIp", "anonymous");
    	}
    	else
    	{
    		param.put("dmn", userSession.getDmn());
    		param.put("userId", userSession.getUserId());
    		param.put("clientIp", userSession.getClientIp());
    	}
    }
    
    private AjaxInkoveInfo[] createAjaxParam(HttpServletRequest request)
    {
    	ArrayList<AjaxInkoveInfo> infoList = new ArrayList<>();
    	
    	try
    	{
    		CommonParamMap[] map = Utility.getRequestMap(request);    	
        	for(int ii = 0; ii < map.length; ii++)
        	{
    	    	String ajaxCode = map[ii].get(ComnConst.ARGS_AJAX_CODE).toString();
    	    	if(ajaxCode == null || ServiceGubunMap.getQueryId(ajaxCode) == "")
    	    	{
    	    		return new AjaxInkoveInfo[0];
    	    	}
    	    	addAjaxRequestParam(map[ii]);
    	    	infoList.add(new AjaxInkoveInfo(map[ii], ServiceGubunMap.getQueryId(ajaxCode)));
        	}
    	}
    	catch(Exception ex)
    	{
    		log.info(ex.toString());
    		log.info(ex.getMessage());
    	}
    	return infoList.toArray(new AjaxInkoveInfo[infoList.size()]);
    }
    
    protected ResponseEntity<String> requestAjax(HttpServletRequest request)
    {    	
    	ArrayList<DataResult> resultList = requestFixAcProcCall(request);
    	if(resultList == null || resultList.isEmpty())
    	{
    		return new ResponseEntity<>("[[]]", HttpStatus.OK);
    	}
    	else
    	{
    		return Utility.getJSONResponse(resultList.size() == 1 ? resultList.get(0) : resultList);
    	}
    }
    
    protected ArrayList<DataResult> requestFixAcProcCall(HttpServletRequest request)
    {
    	CommonParamMap resultCode = new CommonParamMap();
    	try
    	{
	    	AjaxInkoveInfo[] info = createFixAcAjaxParam(request);
	    	ArrayList<DataResult> resultList = new ArrayList<>();

	    	for(int ii = 0; ii < info.length; ii++)
	    	{
    			List<CommonParamMap> list = invokeList("LIB005", info[ii].ajaxCode, info[ii].param);
        		String returnCode = (String)info[ii].param.get(ComnConst.ARGS_ERROR_CODE);
        		
        		resultCode.put(ComnConst.ARGS_ERROR_CODE, returnCode);
        		resultCode.put(ComnConst.ARGS_RETURN_STRING, info[ii].param.get(ComnConst.ARGS_RETURN_STRING));
        		resultCode.put(ComnConst.ARGS_ROW_COUNT, info[ii].param.get(ComnConst.ARGS_ROW_COUNT));        		
        		
    			CommonParamMap m = new CommonParamMap(); 
    			m.put(ComnConst.ARGS_ERROR_CODE, returnCode);
    			List<CommonParamMap> msgList = invokeList("", ServiceGubunMap.getQueryId("SYSTEM_A_1"), m);
    			if(msgList != null && !msgList.isEmpty())
    			{
    				resultCode.put(ComnConst.ARGS_ERROR_MSG, msgList.get(0).get("errorStr"));
    			}
        		
        		resultCode.put(ComnConst.ARGS_DOMAIN_URL, systemProp.getProperty("DOWNLOAD.URL"));
    			resultList.add(new DataResult(resultCode, list));
    		}
    		return resultList;
    	}
    	catch(Exception ex)
    	{
    		StackTraceElement[] list = ex.getStackTrace();
    		
    		if(list.length > 0)
    		{
    			log.error(String.format("%s at %s - %d", ex.getClass().getName(), list[0].getFileName(), list[0].getLineNumber()));
    			log.info(ex.toString());
    			log.info(ex.getMessage());
    		}
    		return new ArrayList<>();
    	}
    }    

    private AjaxInkoveInfo[] createFixAcAjaxParam(HttpServletRequest request)
    {
    	ArrayList<AjaxInkoveInfo> infoList = new ArrayList<>();
    	
    	try
    	{
    		CommonParamMap[] map = Utility.getRequestMap(request);    	
        	for(int ii = 0; ii < map.length; ii++)
        	{
    	    	addAjaxRequestParam(map[ii]);
    	    	infoList.add(new AjaxInkoveInfo(map[ii], ServiceGubunMap.getQueryId("LIB005")));
        	}
    	}
    	catch(Exception ex)
    	{
    		log.info(ex.toString());
    		log.info(ex.getMessage());
    	}
    	return infoList.toArray(new AjaxInkoveInfo[infoList.size()]);
    }
}

[UTility 클래스]

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import net.sf.json.JSONSerializer;


public class Utility
{
    @Resource(name="commonDAO")
    protected CommonDAO commonDAO;

	/** CryptoProperties */
	@Resource(name = "cryptoProp")
	private static Properties cryptoProp;
	
    private static final HttpHeaders _jsonHeader = new HttpHeaders();
    static
    {
    	_jsonHeader.add(ComnConst.HEADER_CONTENT_TYPE_NAME, ComnConst.HEADER_APP_JSON_VALUE);
    }
    
    public static <E extends Enum<E>> boolean enumContains(Class<E> _enumClass, String value)
	{
		try
		{
			return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));
		}
		catch (Exception e)
		{
			return false;
		}
	}

    public static final String SERIAL_UID = "6723434363565852261R";
	static protected Logger log = LoggerFactory.getLogger(Utility.class);
	
	public static CommonParamMap getSimpleRequestMap(HttpServletRequest request)
	{
		CommonParamMap map = new CommonParamMap();
		Enumeration<?> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements())
		{
			String parameterName = (String)parameterNames.nextElement();
			String[] parameterValues = request.getParameterValues(parameterName);
			if(parameterValues.length == 1)
			{
				map.put(parameterName, parameterValues[0]);
			}
			else
			{
				map.put(parameterName, parameterValues);
			}
		}
		
		UserModel userSession = Utility.getPrincipal();
		if(userSession != null)
		{
			map.put("userId", userSession.getUserId());
			map.put("userNm", userSession.getUserName());
			map.put("clientIp", userSession.getClientIp());
		}

		return map;
	}	
	
	public static CommonParamMap[] getRequestMap(HttpServletRequest request)
	{
		CommonParamMap[] pMap = null;
		if(request.getParameter(ComnConst.ARGS_SP_NAME) != null)
		{
			pMap = getSPRequestMap(request);
		}
		else
		{
			pMap = getBasicRequestMap(request);
		}
		
		if(pMap != null)
		{
			for(int i = 0; i < pMap.length; i++){
				pMap[i].put(ComnConst.ARGS_ERROR_CODE, "");
				pMap[i].put(ComnConst.ARGS_RETURN_STRING, "");
			}
		}
		return pMap;
	}
	
	private static CommonParamMap[] getBasicRequestMap(HttpServletRequest request)
	{
		CommonParamMap[] map = new CommonParamMap[1];
		map[0] = new CommonParamMap();
		Enumeration<?> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements())
		{
			String parameterName = (String)parameterNames.nextElement();
			String[] parameterValues = request.getParameterValues(parameterName);
		
			if(parameterName.indexOf('[') == -1 && parameterValues.length == 1)
			{
				map[0].put(parameterName, parameterValues[0]);
			}
			else
			{
				map[0].put(parameterName.replace("[", "").replace("]", ""), parameterValues);
			}
		}
		return map;
		
		/*
		 *  암호화 처리
			CommonParamMap[] map = getConvertMap(request);		
			return map;		
		*/
	}
	
	private static CommonParamMap[] getConvertMap(HttpServletRequest request)
	{
		CommonParamMap[] ubMap = new CommonParamMap[1];		
		ubMap[0] = new CommonParamMap();
		Enumeration<?> parameterNames = request.getParameterNames();		
		
		while(parameterNames.hasMoreElements())
		{
			String parameterName = (String)parameterNames.nextElement();
			String[] parameterValues = request.getParameterValues(parameterName);
			
			if(parameterName.indexOf('[') == -1 && parameterValues.length == 1)
			{
				ubMap[0].put(parameterName, parameterValues[0]);
			}
			else
			{
				int intFirstIndex  = parameterName.indexOf("[");
				
				if("[encYn]".equals(parameterName.substring(intFirstIndex, parameterName.length())))
				{
					String strParamName  = parameterName.substring(0, intFirstIndex);
					String strParamValue = request.getParameterValues(parameterName.substring(0, intFirstIndex)+"[data]")[0];					
					String strParamEncYn = request.getParameterValues(parameterName.substring(0, intFirstIndex)+"[encYn]")[0];
					
					if("Y".equals(strParamEncYn))
					{
						String strKeyStore = (String)request.getAttribute("hashKey");
						AriaSecurity clsAria = new AriaSecurity(strKeyStore);

						strParamValue = clsAria.Encrypt(strParamValue);						
					}						
					
					ubMap[0].put(strParamName, strParamValue);
				}
				else if("[data]".equals(parameterName.substring(intFirstIndex, parameterName.length()))){ }
				else
				{
					ubMap[0].put(parameterName.replace("[", "").replace("]", ""), parameterValues);	
				}
			}
		}
		
		return ubMap; 
	}
	
	private static CommonParamMap[] getSPRequestMap(HttpServletRequest request)
	{
		int iParams = 1;
		String spName, prmName;
		String[] prmValues;
		CommonParamMap mapObj = null;
		String[][] recordList = null;
		ArrayList<String[]> paramList = new ArrayList<>();
		ArrayList<CommonParamMap> mapList = new ArrayList<>();
		
		spName = request.getParameter(ComnConst.ARGS_SP_NAME).toString();		
		
		prmName = "p1";
		while(request.getParameterValues(prmName) != null)
		{			
			prmValues = convertSessionValue(request.getSession(), request.getParameterValues(prmName));
			paramList.add(prmValues);
			prmName = String.format("p%d", ++iParams);
		}
		
		recordList = convertRecordArray(paramList);
		 
		for(int i = 0; i < recordList.length; i++)
		{
			mapObj = new CommonParamMap();		
			mapObj.put(ComnConst.ARGS_AJAX_CODE, ServiceMap.getQueryId("COMMON_DIRECT_SP"));
			mapObj.put(ComnConst.DIRECT_SP_NAME, spName);
			mapObj.put(ComnConst.DIRECT_SP_PARAM, recordList[i]);
			mapList.add(mapObj);
		}
		return mapList.toArray(new CommonParamMap[mapList.size()]);
	}
	
	private static String[][] convertRecordArray(ArrayList<String[]> src)
	{
		int iMaxRank = 0;
		String[][] resultData;
		
		for(int i = 0; i < src.size(); i++) iMaxRank = Math.max(iMaxRank, src.get(i).length);
		resultData = new String[iMaxRank][src.size()];
		
		for(int iRank = 0; iRank < iMaxRank; iRank++)
		{
			for(int iCol = 0; iCol < src.size(); iCol++)
			{
				resultData[iRank][iCol] = src.get(iCol)[iRank];
			}
		}
		return resultData;
	}
	
	private static String[] convertSessionValue(HttpSession session, String src[])
	{
		for(int i = 0; i < src.length; i++)
		{
			if(src[i].equals("#CompID#"))
			{
				src[i] = getSessionAttribute(session, ComnConst.SESS_COMP_ID);
			}
			else if(src[i].equals("#UserID#")) src[i] = getSessionAttribute(session, ComnConst.SESS_USER_ID);
			else if(src[i].equals("#DeptCode#")) src[i] = getSessionAttribute(session, ComnConst.SESS_DEPT_ID);
		}
		return src;
	}
	
	private static String getSessionAttribute(HttpSession session, String key)
	{
		String result = (String)session.getAttribute(key);
		return result == null ? "" : result;
	}
	
    public static ResponseEntity<String> getJSONResponse(Object obj)
    {
    	return new ResponseEntity<>(getJSONString(obj), _jsonHeader, HttpStatus.OK);
    }
     
    public static String getJSONString(Object obj)
    {
        return JSONSerializer.toJSON(obj).toString();
    }
    
    public static UserModel getPrincipal()
    {
    	try
    	{
    		return (UserModel)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	}
    	catch(Exception ex)
    	{
    		return null;
    	}
    }
    
	public static String randomString(int len)
	{
		String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()";
		
		StringBuilder sb = new StringBuilder(len);
		for(int i = 0; i < len; i++)
		{
			sb.append(AB.charAt(new Random().nextInt(AB.length())));
		}
		return sb.toString();
	}
	
	public static JsonObject convertGoogleJsonObject(String jsonParameter)
	{
		String evalJson = jsonParameter.replaceAll("&quot;", """).replaceAll("&apos;", "'");		
		return (evalJson != null && !evalJson.equals("")) ? (JsonObject) new JsonParser().parse(evalJson) : null;
	}
	
	public static String mimeType(String fileName)
	{
		int pos = fileName.lastIndexOf( "." );
		String ext = fileName.substring( pos + 1 );
		
		MimetypesFileTypeMap mediaTypes = new MimetypesFileTypeMap();
		mediaTypes.addMimeTypes("application/msword doc dot");
		mediaTypes.addMimeTypes("application/vnd.ms-excel xls");
		mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx");
		mediaTypes.addMimeTypes("application/pdf pdf");
		mediaTypes.addMimeTypes("application/vnd.ms-powerpoint ppt");
		mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument.presentationml.presentation pptx");
		mediaTypes.addMimeTypes("image/png png");
		mediaTypes.addMimeTypes("image/bmp bmp");
		mediaTypes.addMimeTypes("image/jpeg jpg jpeg jpe");
		mediaTypes.addMimeTypes("video/mp4 mp4 mp4v mpg4 m4v");
		mediaTypes.addMimeTypes("video/x-msvideo avi");
		mediaTypes.addMimeTypes("text/plain txt");
		
		return mediaTypes.getContentType("mimeFile." + ext.toLowerCase());
	}
    
    /**
     * 파일다운로드 스트리밍에서 사용
     * @access FileDownloadStreaming.class
     */    
    public static boolean accepts(String acceptHeader, String toAccept)
    {
        String[] acceptValues = acceptHeader.split("s*(,|;)s*");
        Arrays.sort(acceptValues);
        return Arrays.binarySearch(acceptValues, toAccept) > -1
            || Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
            || Arrays.binarySearch(acceptValues, "*/*") > -1;
    }    	

    public static boolean matches(String matchHeader, String toMatch)
    {
        String[] matchValues = matchHeader.split("s*,s*");
        Arrays.sort(matchValues);
        return Arrays.binarySearch(matchValues, toMatch) > -1
            || Arrays.binarySearch(matchValues, "*") > -1;
    }
    
    public static boolean isEmpty(String str)
    {
    	return (str == null || str.equals("") ? true : false);
    }

    public static long sublong(String value, int beginIndex, int endIndex)
    {
        String substring = value.substring(beginIndex, endIndex);
        return (substring.length() > 0) ? Long.parseLong(substring) : -1;
    }
    
    /**
	 * Request 객체내에 Parameters 를 Map으로 Converting
	 * @param request Request 객체
	 * @return
	 */
	public static Map<String, Object> getRequestParamToMap(HttpServletRequest request)
	{
		Map<String, Object> map = new HashMap<>();
		Enumeration params = request.getParameterNames();
		while(params.hasMoreElements())
		{
		    String name = (String)params.nextElement();
		    map.put(name, request.getParameter(name));
		}
		return map;
	}
	
	public static String getSHA512(String value) throws Exception
	{
		String sha512Str = "";		
		MessageDigest digest = MessageDigest.getInstance("SHA-512");
		
		digest.reset();
		digest.update(value.getBytes("utf8"));
		sha512Str = String.format("%0128x", new BigInteger(1, digest.digest()));
		
		return sha512Str;
	}
	
	public static String getClientIpAddr(HttpServletRequest request)
	{
	    String ip = request.getHeader("X-Forwarded-For");
	 
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

	    return ip;
	}

	public static String getServerIp(){
	    String result = null;
	    try {
	        result = InetAddress.getLocalHost().getHostAddress();
	    } catch (UnknownHostException e) {
	        result = "";
	    }
	   return result; 
	}

	public static String getServerHostName(){
	    String result = null;
	    try {
	        result = InetAddress.getLocalHost().getHostName();
	    } catch (UnknownHostException e) {
	        result = "";
	    }
	   return result; 
	}	
}

Leave a Reply

error: Content is protected !!