How to intercept a request based on a URL base?

I have a noise to solve and you need help. Suppose I have a URL for my domain, for example: http://mydomain.com/any_page.xhtml . I would like to intercept a user request by clicking on a link that theoretically goes to my domain and needs to intercept it and redirect to a specific new URL based on my criteria. I work with simple servlets. During my investigation, I saw that the Filter can help me. Does anyone know how to create something for this proposal?

+4
source share
2 answers

Just execute javax.servlet.Filter .

If you match this with the URL pattern /* , it will run for every request.

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

or when you are already in Servlet 3.0

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

You can get the HttpServletRequest#getRequestURI() request URI in the doFilter() method as follows:

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

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

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

You can use if/else keywords provided by the Java language to control the flow of 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 simply continue the request.

 chain.doFilter(request, response); 

Do the math. Of course, you can also use a third-party one, such as the Tuckey URL rewrite filter, which, say, is a Java version of Apache HTTPD mod_rewrite .

See also:

+7
source

Maybe take a look at UrlRewriterFilter ?

+1
source

Source: https://habr.com/ru/post/1343766/


All Articles