简体   繁体   中英

How to intercept a request by URL base?

I have a buzz to solve and need some help. Suppose I have a URL from my domain, something like: http://mydomain.com/any_page.xhtml for example. I'd like to intercept the user request when clicking the link, that theoretically directs to my domain and need it to intercept and redirect it to determined new URL based in my criterion. I'm working with simple Servlets. During my investigation I've seen that Filter may help me. Does anybody know how to create something for this proposal?

Just implement javax.servlet.Filter .

If you map this on an URL pattern of /* it will be executed on every request.

<url-pattern>/*</url-pattern>

or when you're already on Servlet 3.0

@WebFilter(urlPatterns = { "/*" })

You can obtain the request URI by HttpServletRequest#getRequestURI() in filter's doFilter() method as follows:

HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
// ...

You can use any of the methods provided by java.lang.String class to compare/manipulate it.

boolean matches = uri.startsWith("/something");

You can use if/else keywords provided by the Java language to control the flow in code.

if (matches) {
    // It matches.
} else {
    // It doesn't match.
}

You can use HttpServletResponse#sendRedirect() to send a redirect.

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect(newURL);

You can use FilterChain#doFilter() to just let the request continue.

chain.doFilter(request, response);

Do the math. You can of course also use a 3rd party one, like Tuckey's URL rewrite filter which is, say, the Java variant of Apache HTTPD's mod_rewrite .

See also:

也许看看UrlRewriterFilter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM