问题
This is my current Guice configuration:
public class MyServletModule extends ServletModule {
@Override
protected void configureServlets() {
bind(MyRest.class);
serveRegex(".+(?<!\\.(html|css|png|jpg))")
.with(HttpServletDispatcher.class);
}
}
However I want that my Rest resource is only access in form of http://127.0.0.1:8888/{hashcode_or_filename}
and the only form accepted and processed (well, plus the /create method below).
Right now, I can deal with hashcode and filename properly in this path pattern.
However I am not sure how to deal the kind or scenario below, where the client is requesting path that is not mapped, which returns this in my case:
Could not find resource for relative : /examples/foo of full path:
http://127.0.0.1:8888/examples/foo
or
Could not find resource for relative : /examples/bar/foo of full path:
http://127.0.0.1:8888/examples/bar/foo
What I need is to be able to be able to handle unmapped paths so I can return a error HTML page or something and not show these error text in the browser.
Also if the request is: http://127.0.0.1:8888/
I need to forward to http://127.0.0.1:8888/index.html
automatically. As right now I have to manually put the index.html in the tail.
My Resteasy resource is configure or wired with just:
@Singleton
@Path("/")
public class MyRest {
@GET
@Path({hashcode})
public Response getSomething(...){}
@POST
@Path("create")
public Response createSomething(...){}
}
回答1:
Easiest way is to register filter to handle responses with error code other that 200 (OK). Or add to your web.xml something like this:
<error-page>
<error-code>404</error-code>
<location>/ErrorPage.jsp</location>
</error-page>
Also if the request is:
http://127.0.0.1:8888/
I need to forward tohttp://127.0.0.1:8888/index.html
automatically. As right now I have to manually put the index.html in the tail.
You can use this module http://tuckey.org/urlrewrite/
WEB-INF/web.xml
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confPath</param-name>
<param-value>/WEB-INF/urlrewrite.xml</param-value>
</init-param>
<!--...omitted...-->
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
WEB-INF/urlrewrite.xml
<?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 match-type="regex">
<from>^/$</from>
<to type="redirect">/index.html</to>
</rule>
</urlrewrite>
来源:https://stackoverflow.com/questions/15874698/handling-un-mapped-rest-path