URL Rewrite : 동적 URL 지정 : creating Dynamic URL

만일 Http://comphy.kr/indexi.htm&key=somthing 의 url을 http://comphy.kr/somthing 등으로

간단하게 표현하는 방법을 알아보쟈...

* Java [출처] http://jace.tistory.com/59

urlrewrite를 사용한지가 대략 1년 반정도 인것 같다.
이번에 진행하고 있는 프로젝트에서 다시 사용하면서 늦었지만 포스팅을 해본다.

사이트 : http://tuckey.org/urlrewrite/

UrlRewrite는 apache의 mod_rewrite 모듈에 기반하며
이것을 J2EE환경에서 사용할 수 있도록 구성한 것이다.

현재 version은 2.6, 3.0이 존재한다.
두 version 사용법에 있어 크게 다른점이 없으므로 아무거나 다운받아 사용해도 무관한다.
beta version이긴 하지만 새로운 3.0을 소개해 본다.

Install

  1. urlrewrite파일을 다운로드 한다. (다운로드 후 zip파일 압축해제)
  2. 다음구문을 WEB-INF/web.xml에 추가한다.
    
        <filter>
           <filter-name>UrlRewriteFilter</filter-name>
           <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
        </filter>
        <filter-mapping>
           <filter-name>UrlRewriteFilter</filter-name>
           <url-pattern>/ *</url-pattern>
        </filter-mapping>
            
  3. urlrewrite.xml 파일을 WEB-INF/ 하위에 생성한다.

Filter Parameters

filter에기술 될 수 있는 parameter들은 다음과 같다.


    <filter>
        <filter-name>UrlRewriteFilter</filter-name>
        <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>

        <!-- set the amount of seconds the conf file will be checked for reload
        can be a valid integer (0 denotes check every time,
        -1 denotes no reload check, default -1) -->
        <init-param>
            <param-name>confReloadCheckInterval</param-name>
            <param-value>60</param-value>
        </init-param>

        <!-- 설정파일 경로 (2.6버전에선 설정파일의 위치를 변경시킬 수 없었음
        본인의 경우 2.6소스를 다운받아 설정파일을 로드하는 클래스를 변경했던 기억이...
        (default /WEB-INF/urlrewrite.xml) -->
        <init-param>
            <param-name>confPath</param-name>
            <param-value>/WEB-INF/urlrewrite.xml</param-value>
        </init-param>

        <!-- 로그레벨임. log4j를 이용하므로 log4j의 레벨과 동일함.
        (default WARN) -->
        <init-param>
            <param-name>logLevel</param-name>
            <param-value>DEBUG</param-value>
        </init-param>

        <!-- you can change status path so that it does not
        conflict with your installed apps (note, defaults
        to /rewrite-status) note, must start with / -->
        <init-param>
            <param-name>statusPath</param-name>
            <param-value>/status</param-value>
        </init-param>

        <!-- you can disable status page if desired
        can be: true, false (default true) -->
        <init-param>
            <param-name>statusEnabled</param-name>
            <param-value>true</param-value>
        </init-param>

        <!-- you may want to allow more hosts to look at the status page
        statusEnabledOnHosts is a comma delimited list of hosts, * can
        be used as a wildcard (defaults to "localhost, local, 127.0.0.1") -->
        <init-param>
            <param-name>statusEnabledOnHosts</param-name>
            <param-value>localhost, dev.*.myco.com, *.uat.mycom.com</param-value>
        </init-param>

    </filter>

    <filter-mapping>
        <filter-name>UrlRewriteFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>

WEB-INF/urlrewrite.xml 설정

샘플은 다음과 같다.


    <?xml version="1.0" encoding="utf-8"?>

    <!DOCTYPE urlrewrite
        PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN"
        "http://tuckey.org/res/dtds/urlrewrite3.0.dtd">

    <urlrewrite>

        <rule>
           <from>^/some/olddir/(.*)$</from>
           <to type="redirect">/very/newdir/2194</to>
        </rule>

        <rule match-type="wildcard">
           <from>/blog/archive/ **</from>
           <to type="redirect">/roller/history/2194</to>
        </rule>

        <outbound-rule>
            <from>^/world.jsp?country=([a-z]+)&amp;city=([a-z]+)$</from>
            <to>/world/2194/142</to>
        </outbound-rule>

    </urlrewrite>



    rule과 outbount-rule을 주로 사용하여 설정을 구성하며
rule은 from 패턴으로 요청시 to를 통해서 처리토록 설정하는것이며,
반대로 outbount-rule은 from 패턴의 uri가 요청시 to패턴으로 display하게 된다.

예를 들어 http://domain/rss/feed/1 이라는 uri를
http://domain/rss.jsp?feed=1 로 처리토록 한 경우
사용자의 브라우저의 주소는 http://domain/rss.jsp?feed=1 요렇게 display되는데
이때 outbount-rule를 이용하여 다시 http://domain/rss/feed/1 요렇게
보여지도록 구성할때 사용되는것이다.
자세한 사항은 해당 사이트의 manual을 참조하도록한다.

* 닷넷. MS dotNet [출처] http://www.dotnetfunda.com/articles/article1568-url-rewritingvirtual-url.aspx

URL REWRITING/VIRTUAL URL

Let us assume that ,we need to display the user public profile information in viewprofile.aspx page

Generally we pass the user id in the qurey string like ”viewprofile.aspx?id=100” . We fetch data using id value and displays the information .

If client request s you to url format to be like http://yoursite.com/ publicprofile /username

For that type of cases we use the url rewriting concepts .


Introduction

In this article we will learn url rewriting ,virtual url concepts

URL rewriting is the process of accepting an incoming Web request and automatically redirecting it to a different URL.


Using the code

Create publicprofile” directory in your web application.

Global.asax

voidApplication_BeginRequest(object sender, EventArgs e)

{

stringCurrentPath = Request.Url.ToString();

if(CurrentPath.Contains("/publicprofile/"))

{

HttpContextMyContext = HttpContext.Current;

stringurl = CurrentPath.Substring(0,CurrentPath.LastIndexOf("/"));

stringusername = CurrentPath.Substring(CurrentPath.LastIndexOf("/"));

username = username.Replace("/", "");

if(CurrentPath[CurrentPath.Length - 1].ToString() == "/")

{

HttpContext.Current.Response.Status = "301 Moved Permanently";

HttpContext.Current.Response.AddHeader("Location",

Request.Url.ToString().Replace(CurrentPath, url));

}

else

{

MyContext.RewritePath("index.aspx?uname=" + username);

}

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

}

}

Place “Index.aspx” in “publicprofile”directory.

Index.aspx.cs

protected void Page_Load(objectsender, EventArgs e)

{

if(Request.QueryString["uname"] != "")

{

int id = Validateuser.getId(Request.QueryString["uname"].ToString());

if(id != 0)

{

ProfileInfo(id);

}

else

{

Response.Redirect(“http://yoursite.com/?err=1");

}

}

else

{

Response.Redirect(“http://yoursite.com/?err=1");

}

}

protected void ProfileInfo(intproID){

DataTable dt = Validateuser.getprofile(proID);

//Code to assign values to controls……

}

Web.config:

<httpModules>

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

</httpModules>



Conclusion

The above code works for the following urls http://yoursite.com/ publicprofile /username,

publicprofile /username/,publicprofile /username//…

<script> function hrefMark(){ } function hrefPageGo(mark){ try{ if(mark == 'top'){ parent.window.scrollTo(0,0); }else{ document.location.href="this.location.href+"#comment"; } }catch(e){} } //포스트 글로딩후 top포커수 주기 setTimeout('hrefPageGo("top")',300); </script>
본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
1135 Spring 3 MVC Hello World Example file 가을의 곰을... 2011.11.01 14983
1134 스프링 - 아이바티스 연동 가을의 곰을... 2011.11.02 7972
1133 spring + iBatis 연동하기 가을의 곰을... 2011.11.02 8004
1132 kernel.org가 아닌 구글에서 안드로이드 소스 다운로드 및 빌드 가을의 곰을... 2011.11.07 10169
1131 Java Spring 2.0 Web 예제(Hello World) file 가을의 곰을... 2011.11.09 7726
1130 Android : Source Code Overview 가을의 곰을... 2011.11.10 10041
1129 XCode 간단 설치와 사용법 - Objective-C의 예제 개발하기 file 가을의 곰을... 2011.11.13 10727
1128 자바에서 x86 어셈블리로 프로그래밍: x86 Assembly Programming in Java Platform 가을의 곰을... 2011.11.15 20535
» URL Rewrite : 동적 URL 지정 : creating Dynamic URL 가을의 곰을... 2011.11.16 10520
1126 특허/실용신안 출원 절차 가을의 곰을... 2011.11.17 7073
1125 특허 등록 절차 가을의 곰을... 2011.11.17 7811
1124 특허출원 직접특허출원 가을의 곰을... 2011.11.20 7104
1123 오픈 소스 클라우드 분석 file 가을의 곰을... 2011.11.22 6109
1122 보왕삼매론 가을의 곰을... 2011.11.24 6657
1121 한 페이지 기획서 : one page proposal 가을의 곰을... 2011.11.27 6278
1120 게임소설이란 무엇인가? 위키백과에서 가을의 곰을... 2011.12.04 5870
1119 게임소설 쓰는 법 file 가을의 곰을... 2011.12.04 5572
1118 자바 입출력( java stream ) 가을의 곰을... 2011.12.08 6845
1117 [공부] Tcpdump & pcap분석 file 가을의 곰을... 2011.12.08 10687
1116 C 코드 분석 툴 file 가을의 곰을... 2011.12.18 11336
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED