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?
You use onBeforeRequest to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means you intercept HTTP requests to all URLs.
Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more.
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
.
Perhaps look at UrlRewriterFilter?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With