简体   繁体   中英

Servlet filter change response?

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!

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" );                          
        }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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