https://howtodoinjava.com/servlets/java-cors-filter-example/
create the class:
import
java.io.IOException;
import
javax.servlet.Filter;
import
javax.servlet.FilterChain;
import
javax.servlet.FilterConfig;
import
javax.servlet.ServletException;
import
javax.servlet.ServletRequest;
import
javax.servlet.ServletResponse;
import
javax.servlet.annotation.WebFilter;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class CORSFilter
*/
public
class
CORSFilter
implements
Filter {
/**
* Default constructor.
*/
public
CORSFilter() {
}
/**
* @see Filter#destroy()
*/
public
void
destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public
void
doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws
IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println(
"CORSFilter HTTP Request: "
+ request.getMethod());
((HttpServletResponse) servletResponse).addHeader(
"Access-Control-Allow-Origin"
,
"*"
);
((HttpServletResponse) servletResponse).addHeader(
"Access-Control-Allow-Methods"
,
"GET, OPTIONS, HEAD, PUT, POST"
);
HttpServletResponse resp = (HttpServletResponse) servletResponse;
if
(request.getMethod().equals(
"OPTIONS"
)) {
resp.setStatus(HttpServletResponse.SC_ACCEPTED);
return
;
}
chain.doFilter(request, servletResponse);
}
/**
* @see Filter#init(FilterConfig)
*/
public
void
init(FilterConfig fConfig)
throws
ServletException {
}
}
add im web.xml
Now register this filter in web.xml
.
< filter >
< filter-name >CorsFilter</ filter-name >
< filter-class >com.howtodoinjava.examples.cors.CORSFilter</ filter-class >
</ filter >
< filter-mapping >
< filter-name >CorsFilter</ filter-name >
< url-pattern >/*</ url-pattern >
</ filter-mapping >
|