Blankman
Blankman

Reputation: 267190

How to send response from an interceptor, and halt further execution?

I have an interceptor, and under a certain condition I want to send a string response to the browser and then halt execution completely.

How can I do this?

Upvotes: 12

Views: 9982

Answers (2)

Sheshan Gamage
Sheshan Gamage

Reputation: 634

You can do like this which will return a json response to the client

@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
    response.getWriter().write("{ \"error_description\": \"Invalid Value\"}");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(400);
    return false;
}

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Override the preHandle method and return false if you want to stop execution.

@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
    response.getWriter().write("something");
    return false;
}

Upvotes: 19

Related Questions