Filter를 이용한 multipart/form-data 처리 및 파일 업로드 처리


package com.xo.ddm.front.util.fileUtil;


import java.io.IOException;


import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;


public final class FileUploadFilter implements Filter{


public void init(FilterConfig aConfig) throws ServletException{

}


public void destroy(){

}


public void doFilter(

ServletRequest aRequest, ServletResponse aResponse, FilterChain aChain)

throws IOException, ServletException{


HttpServletRequest request = (HttpServletRequest) aRequest;

if(isFileUploadRequest(request)){

FileUploadWrapper wrapper = new FileUploadWrapper(request);

aChain.doFilter(wrapper, aResponse);

}else{

aChain.doFilter(aRequest, aResponse);

}

}


private boolean isFileUploadRequest(HttpServletRequest aRequest){

return

aRequest.getMethod().equalsIgnoreCase("POST") &&

aRequest.getContentType().startsWith("multipart/form-data");

}

}




package com.xo.ddm.front.util.fileUtil;


import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;

import java.util.LinkedHashMap;

import java.util.LinkedHashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletRequestWrapper;


import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadWrapper extends HttpServletRequestWrapper{


/*

* 생성자 설정

    */

public FileUploadWrapper(HttpServletRequest aRequest)

 throws IOException{


super(aRequest);

aRequest.setCharacterEncoding("UTF-8");

ServletFileUpload upload = new ServletFileUpload(

new DiskFileItemFactory());


try{

List<FileItem> fileItems = upload.parseRequest(aRequest);

convertToMaps(fileItems);

}catch (FileUploadException e){

//TODO Auto-generated catch block

throw new IOException("Cannot parse underlying request : "

+ e.toString());   

}

}

/*

     * 모든 파라메터 이름을 리턴 한다.(file type 필드 까지)

     */


@Override public Enumeration getParameterNames(){

Set<String> allNames = new LinkedHashSet<String>();

allNames.addAll(fRegularParams.keySet());

allNames.addAll(fFileParams.keySet());

return Collections.enumeration(allNames);

}


/*

     * file type 필드가 아닌 모든 파라메터 값(value)를 리턴 한다.

     * 

     * 파라메터가 존재 하지 않으면 null 리턴

     * 파라메터가 존재 하나 값이 없으면 공백 리턴

     * 파라메터가 여러개 일경우 최초의 값만 리턴

     */


@Override public String getParameter(String aName){

String result = null;

List<String> values = fRegularParams.get(aName);

if(values == null){

result = "";

}else if(values.isEmpty()){

result = "";

}else{

try{

result = new String(values.get(FIRST_VALUE).getBytes("ISO-8859-1"), "UTF-8");

}catch(UnsupportedEncodingException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return result;

}


/*

     * parameterValues[] 리턴

     */

@Override public String[] getParameterValues(String aName){

String[]result = null;

List<String> values = fRegularParams.get(aName);

if(values != null){

result = values.toArray(new String[values.size()]);

}

return result;

}

/*

     * 파라메터 Map 리턴

     */

@Override public Map getParameterMap(){

return Collections.unmodifiableMap(fRegularParams);

}

/*

     * fileItems 리턴

     */

public List<FileItem> getFileItems(){

return new ArrayList<FileItem>(fFileParams.values());

}


public FileItem getFileItem(String aFieldName){

return fFileParams.get(aFieldName);

}


private final Map<String, List<String>> fRegularParams = new

LinkedHashMap<String, List<String>>();


private final Map<String, FileItem>fFileParams = new

LinkedHashMap<String, FileItem>();


private static final int FIRST_VALUE = 0;


private void convertToMaps(List<FileItem> aFileItems){

for(FileItem item: aFileItems){

if(isFileUploadField(item)){

fFileParams.put(item.getFieldName(), item);

}else{

if(alreadyHasValue(item)){

addMultiValuedItem(item);

}else{

addSingleValueItem(item);

}

}

}

}


private boolean isFileUploadField(FileItem aFileItem){

return !aFileItem.isFormField();

}


private boolean alreadyHasValue(FileItem aItem){

return fRegularParams.get(aItem.getFieldName()) != null;

}


private void addSingleValueItem(FileItem aItem){

List<String> list = new ArrayList<String>();

list.add(aItem.getString());

fRegularParams.put(aItem.getFieldName(), list);

}


private void addMultiValuedItem(FileItem aItem){

List<String> values = fRegularParams.get(aItem.getFieldName());

values.add(aItem.getString());

}

}



'JAVA' 카테고리의 다른 글

[JAVA]filter에서 파라미터 받기  (1) 2017.11.23
[JAVA]Filter를 이용한 request 파라미터 변경 방법  (0) 2017.11.23
[JAVA]filter 필터  (0) 2017.11.23
[JAVA]filter 파일 업로드 -egov  (0) 2017.11.23
[JAVA]Filter 응용  (0) 2017.11.21
블로그 이미지

마크제이콥스

초보 개발자의 이슈및 공부 내용 정리 블로그 입니다.

,

[JAVA]filter 필터

JAVA 2017. 11. 23. 10:17

filter 필터


webApplication에서 request 전체 필터 하기

web.xml 설정


<filter>

<filter-name>RequestFilter</filter-name>

     <filter-class>

          egovframework.com.utl.RequestFilter

     </filter-class>

</filter>

<filter-mapping>

<filter-name>RequestFilter</filter-name>

     <url-pattern>*.do</url-pattern>

</filter-mapping>




package egovframework.com.utl; 

import java.io.IOException;

import java.util.Enumeration;


import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.logging.Log;  // Logging 처리를 위한 import

import org.apache.commons.logging.LogFactory;

import org.springframework.web.filter.OncePerRequestFilter;


public class RequestFilter extends OncePerRequestFilter{


 protected Log log = LogFactory.getLog(this.getClass());

 

 @Override

 protected void doFilterInternal(HttpServletRequest request,

   HttpServletResponse response, FilterChain filterchain)

   throws ServletException, IOException {

  

  

  

  if (request.getRequestURI()!=null){

   if (request.getRequestURI().indexOf("/common")==-1 &&

     request.getRequestURI().toLowerCase().indexOf("index.")==-1 &&

     request.getRequestURI().toLowerCase().indexOf("main.")==-1 &&

     request.getRequestURI().toLowerCase().indexOf("loginpage.")==-1 &&

     request.getRequestURI().toLowerCase().indexOf("/error")==-1){


    if (request.getParameter("menuId")==null || request.getParameter("menuId").equals("") ||

      request.getParameter("pcode")==null || request.getParameter("pcode").equals("")){

     

     log.debug("==========================================");

     log.debug("메뉴번호 /pcode 없으면 안됨.");

     log.debug("==========================================");

     

     HttpUtil.goUrl(response, "/error/noParam.do", "메뉴번호 /pid 없으면 안됨.");

    }


   }

  }

  

  if (request.getRequestURI().indexOf("/admin")==-1){

   Enumeration<Object> keys = request.getParameterNames();

   

   while(keys.hasMoreElements()) {

    String key = (String)keys.nextElement();

    String value = (String)request.getParameter(key);

    if (value.indexOf("<(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)")>-1){

     request.setAttribute(key, unscript(value));

    }

   } 

  }

 

     filterchain.doFilter(request, response);

 }

 

    

    /**

     * XSS 방지 처리

     * MethodName : unscript

     * @return String

     * @exception 

     * @param data

     * @return

     * @desc

     */

    protected String unscript(String data) {

        if (data == null || data.trim().equals("")) {

            return "";

        }

        

        String ret = data;

        

        ret = ret.replaceAll("<(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)", "&lt;script");

        ret = ret.replaceAll("</(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)", "&lt;/script");

        

        ret = ret.replaceAll("<(O|o)(B|b)(J|j)(E|e)(C|c)(T|t)", "&lt;object");

        ret = ret.replaceAll("</(O|o)(B|b)(J|j)(E|e)(C|c)(T|t)", "&lt;/object");

        

        ret = ret.replaceAll("<(A|a)(P|p)(P|p)(L|l)(E|e)(T|t)", "&lt;applet");

        ret = ret.replaceAll("</(A|a)(P|p)(P|p)(L|l)(E|e)(T|t)", "&lt;/applet");

        

        ret = ret.replaceAll("<(E|e)(M|m)(B|b)(E|e)(D|d)", "&lt;embed");

        ret = ret.replaceAll("</(E|e)(M|m)(B|b)(E|e)(D|d)", "&lt;embed");

        

        ret = ret.replaceAll("<(F|f)(O|o)(R|r)(M|m)", "&lt;form");

        ret = ret.replaceAll("</(F|f)(O|o)(R|r)(M|m)", "&lt;form");


        return ret;

    }

}

블로그 이미지

마크제이콥스

초보 개발자의 이슈및 공부 내용 정리 블로그 입니다.

,

filter 파일 업로드 -egov


package kr.co.egov.upb.web;


import java.io.IOException;


import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;

import org.springframework.web.filter.OncePerRequestFilter;


import kr.co.egov.upb.service.ProgressCapableMultipartResolver;

import kr.co.egov.upb.service.ProgressDescriptor;



public class UploadProgressFilter extends OncePerRequestFilter{


Logger log = Logger.getLogger(this.getClass());


private final String PROGRESS_TAIL = ".progress"; 


protected void doFilterInternal(HttpServletRequest request,

HttpServletResponse response, FilterChain filterChain)

throws ServletException, IOException {


String requestUri = request.getRequestURI();

String originalUrl = requestUri.substring(0, requestUri.length()

- PROGRESS_TAIL.length());


String attributeName = ProgressCapableMultipartResolver.PROGRESS_PREFIX + originalUrl;


Object progress = request.getSession().getAttribute(attributeName);


if(progress != null){

ProgressDescriptor descriptor = (ProgressDescriptor)progress;

log.debug("[pBytesRead=" + descriptor.getBytesRead() + ",

pContentLength=" + descriptor.getBytesTotal() + "]");



response.getOutputStream().write(descriptor.toString().getBytes() );

response.getOutputStream().flush();

response.getOutputStream().close();

}

}

}

블로그 이미지

마크제이콥스

초보 개발자의 이슈및 공부 내용 정리 블로그 입니다.

,