Catch-all URL rewrite on Google App Engine (Java)

人盡茶涼 提交于 2019-12-22 18:52:16

问题


I'm trying to create a short URL for a GAE app, so I used UrlRewriteFilter, but I can't get it set up correctly. Basically, the user is given this:

  • test.com/012a-bc

and the page that they should be redirected to is

  • test.com/vote.jsp?id=012a-bc

At the moment it's working with the urlrewrite.xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite>

    <rule>
        <from>/([0-z]+)</from>
        <to last="true">/vote.jsp?id=$1</to>
    </rule>

</urlrewrite>

The problem is that all URLs now redirect to this, so for example

  • test.com/thankyou.jsp?id=0123

still runs the page at vote.jsp. What should I do to get it to redirect only when the URL isn't found?


回答1:


What about the following rule:

<rule>
   <from>^/([\w-]+)$</from>
   <to last="true">/vote.jsp?id=$1</to>
</rule>

Where [\w-]+ is at least one any word character (letter, number, underscore) including - (dash character). You use ^ and $ to anchor beginning and end of checked text.


UrlRewriteFilter documentation says

When executing a rule the filter will (very simplified) loop over all rules and for each do something like this psuedo code:

Pattern.compile(<from> element); pattern.matcher(request url);
matcher.replaceAll(<to> element); 
if ( <condition> elements match && matcher.find() ) {
    handle <set> elements (if any)
    execute <run> elements (if any)
    perform <to> element (if any) 
}

That's why you have to use beginning (^) and end ($) string regular expression anchors



来源:https://stackoverflow.com/questions/14523117/catch-all-url-rewrite-on-google-app-engine-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!