본문 바로가기
코드

ServletFilter를 통한 URI 재구성 (Blog처럼)

by umaking 2009. 2. 22.
 
package com;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter를 통한 URL 재구성
 *
 * @author ChangYeol.Kim
 * @date 2009.02.22
 *
 */
public class UmaFilter implements Filter {
    private    Map map;

    public UmaFilter() {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse)response;
        String uri = req.getServletPath();
        String jsp = "";

        String stri;
        Iterator i = map.keySet().iterator();
        while(i.hasNext()) {
            stri = (String)i.next();

            Pattern p = Pattern.compile(stri, Pattern.UNICODE_CASE|Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
            Matcher m = p.matcher(uri);

            if(m.find()) {
                jsp = m.replaceAll( (String) map.get(stri) );
                break;
            }
        }

        RequestDispatcher disp = request.getRequestDispatcher( jsp );
        if(disp != null) {
            disp.forward(request, response);
        }else
            chain.doFilter(request, response);
    }
    public void init(FilterConfig fConfig) throws ServletException {
        String name;
        map = new HashMap<String, String>();
        map.put("/blog/([0-9]+)$", "/uma.jsp?seq=$1");
    }
}
-------------------------------------------------------------------
 
 <display-name>UmaFilter</display-name>
    <filter-name>UmaFilter</filter-name>
    <filter-class>com.UmaFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UmaFilter</filter-name>
    <url-pattern>/blog/*</url-pattern>
  </filter-mapping>
-------------------------------------------------------------------

암튼 대충 끝났다.


내용은 대충 이렇다.

http://www.umaking.com/blog/1

이렇게 해주면

Servlet Filter를 거치면서

http://www.umaking.com/uma.jsp?seq=1

이렇게 구성 되도록 하였다.

위의 붉은색 부분을 보면 알겠지만

정규식으로 해당 부분을 필터링해 전달한다.


글쿠 몇가지 생각해 볼 부분이 있는데 고민 중.


설정파일을 외부로 뺄까 생각 중인데


뭘로 뺄까!!