Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
axcdnt Avatar asked Mar 15 '11 13:03

axcdnt


People also ask

How do you intercept a URL?

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.

What is HTTP interceptor in Javascript?

Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more.


2 Answers

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:

  • Servlet filters info page
like image 120
BalusC Avatar answered Sep 27 '22 17:09

BalusC


Perhaps look at UrlRewriterFilter?

like image 36
Buhake Sindi Avatar answered Sep 27 '22 19:09

Buhake Sindi