Created
May 2, 2020 09:01
-
-
Save seunggabi/d0fb4570b3d87334647a67c403f9ca79 to your computer and use it in GitHub Desktop.
[Spring] request url filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class FilterConfiguration { | |
@Bean | |
public FilterRegistrationBean<CountryFilter> perfFilter() { | |
FilterRegistrationBean<CountryFilter> registration = new FilterRegistrationBean<>(); | |
registration.setFilter(new CountryFilter()); | |
registration.addUrlPatterns("/*"); | |
return registration; | |
} | |
} | |
@Component | |
public class CountryFilter implements Filter { | |
@Value("${country}") | |
String country; | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | |
List<Country> except = Country.except(Country.get(country)); | |
for(Country c : except) { | |
String path = String.format("/%s/", StringUtils.lowerCase(c.name())); | |
if(getUrl(request).contains(path)) { | |
throw new IOException(); | |
} | |
} | |
chain.doFilter(request, response); | |
} | |
public static String getUrl(ServletRequest request) { | |
if (!(request instanceof HttpServletRequest)) | |
return null; | |
return getUrl((HttpServletRequest) request); | |
} | |
public static String getUrl(HttpServletRequest request) { | |
StringBuffer requestURL = request.getRequestURL(); | |
String queryString = request.getQueryString(); | |
if (queryString == null) | |
return requestURL.toString(); | |
return requestURL.append('?').append(queryString).toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment