Frage

Using Restlet 2.1 for Java EE, I am discovering an interesting problem with its ability to handle attributes.

Suppose you have code like the following:

cmp.getDefaultHost().attach("/testpath/{attr}",SomeServerResource.class);

and on your browser you provide the following URL:

http://localhost:8100/testpath/command

then, of course, the attr attribute gets set to "command".

Unfortunately, suppose you want the attribute to be something like command/test, as in the following URL:

http://localhost:8100/testpath/command/test

or if you want to dynamically add things with different levels, like:

http://localhost:800/testpath/command/test/subsystems/network/security

in both cases the attr attribute is still set to "command"!

Is there some way in a restlet application to make an attribute that can retain the "slash", so that one can, for example, make the attr attribute be set to "command/test"? I would like to be able to just grab everything after testpath and have the entire string be the attribute.

Is this possible? Someone please advise.

War es hilfreich?

Lösung

For the same case I usually change the type of the variable :

Route route = cmp.getDefaultHost().attach("/testpath/{attr}",SomeServerResource.class);
route.getTemplate().getVariables().get("attr") = new Variable(Variable.TYPE_URI_PATH);

Andere Tipps

You can do this by using url encoding.

I made the following attachment in my router:

router.attach("/test/{cmd}", TestResource.class);

My test resource class looks like this, with a little help from Apache Commons Codec URLCodec

@Override
protected Representation get() {
    try {
    String raw = ResourceWrapper.get(this, "cmd");
    String decoded = new String(URLCodec.decodeUrl(raw.getBytes()));
    return ResourceWrapper.wrap(raw + " " + decoded);
    } catch(Exception e) { throw new RuntimeException(e); }
}

Note my resource wrapper class is simply utility methods. The get returns the string of the url param, and the wrap returns a StringRepresentation.

Now if I do something like this:

http://127.0.0.1/test/haha/awesome

I get a 404.

Instead, I do this:

http://127.0.0.1/test/haha%2fawesome

I have URLEncoded the folder path. This results in my browser saying:

haha%2fawesome haha/awesome

The first is the raw string, the second is the result. I don't know if this is suitable for your needs as it's a simplistic example, but as long as you URLEncode your attribute, you can decode it on the other end.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top