我有以下servlet过滤器。
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
}
}
我有abover过滤器。我的要求是我需要拦截请求。我需要检查请求中的一些布尔值。如果布尔变量为true,则应继续请求处理。如果boolean variale为false,则请求不应继续,我需要发送一些自定义响应,如下所示。
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);
}
}
如果请求布尔变量的值为false,那么我必须将上面的自定义状态设置为响应并返回而不处理请求。我怎么能这样做?
谢谢!
答案 0 :(得分:2)
如果您通过展开Filter来创建Filter
,则可以执行以下操作:
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" );
}
}
答案 1 :(得分:0)
使用过滤器界面:
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
}
}
不能更具体那个,因为你没有准确说明你要检查的布尔值的位置(是参数,或者是URL的一部分,还是cookie,还是标题?),也没有你准确地说出了你想要的回应。