简体   繁体   English

Servlet过滤器更改响应?

[英]Servlet filter change response?

I have below servlet filter. 我下面有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
}


}

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. 如果布尔变量为true,则应继续进行请求处理。 If boolean variale is false then request should not continue and i need to send some custom response as below. 如果布尔变量是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);
    }

}

If request boolean variable's value is false then i have to set above custom status into response and return without processing the request. 如果请求布尔变量的值为false,那么我必须将上述自定义状态设置为响应并返回,而不处理请求。 How can i do that? 我怎样才能做到这一点?

Thanks! 谢谢!

If you create a Filter by extending Filter , you can do: 如果通过扩展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" );                          
        }
}

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. 不能更具体地说明这一点,因为您没有确切说出要检查的布尔值在哪里(是参数,URL的一部分,cookie还是标头?),您也没有说清楚您想对响应做些什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM