Reputation: 6815
I have below servlet filter.
public class MyFilter extends BaseServletRequestFilter {
@Override
protected void afterExecutingFilterChain(final ServletRequest requset, FilterResponseWrapper response) throws ServletException {
//To do
}
@Override
protected void beforeExecutingFilterChain(final ServletRequest requset, final FilterResponseWrapper response) throws ServletException{
//Here request needs to be intercepted
//To do
}
}
I have abover filter. My requirement is i need to intercept the request. I need to check some boolean value in the request. If boolean variable is true then request processing should be continued. If boolean variale is false then request should not continue and i need to send some custom response as below.
public enum CustomStatus {
OK("Ok"),
BAD_REQUEST("BadRequest");
private final String value;
CustomStatus(String v) {
value = v;
}
public String value() {
return value;
}
public static CustomStatus fromValue(String v) {
for (CustomStatus c: CustomStatus.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
If request boolean variable's value is false then i have to set above custom status into response and return without processing the request. How can i do that?
Thanks!
Upvotes: 1
Views: 6103
Reputation: 9559
Use the Filter interface:
public final class XssFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
//check request...
if (ok) {
chain.doFilter(request, response);
} else {
// do something with the response
}
}
Can't be more specific that that, because you don't say exactly where the boolean value you are checking is (is a parameter, or part of the URL, or a cookie, or a header?), neither do you say exactly what you want done with the response.
Upvotes: 0
Reputation: 2871
If you create a Filter
by extending Filter, you can do:
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
if(your status is ok) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendError(the error code,
"the error message" );
}
}
Upvotes: 2