Spring - 处理访问被拒绝的异常

时间:2014-05-29 10:51:01

标签: java spring spring-mvc spring-security

在我的应用程序中,我想处理AccessDeniedException并返回Json内容以作出回应。有人可以解释如何做到这一点?我找不到答案。我尝试使用@ExceptionHandler捕获异常但我总是重定向到登录页面。我正在写api所以我不需要整个mvc。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以引入能够将AccessDeniedException转换为JSON响应的HandlerExceptionResolver

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component("handlerExceptionResolver")
public class RestExceptionResolver implements HandlerExceptionResolver {
    private final ObjectMapper objectMapper;

    @Autowired
    public RestExceptionResolver(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
        if (exception instanceof AccessDeniedException) {
            try {
                //you can use a pojo instead of a map too
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("status", HttpServletResponse.SC_FORBIDDEN);
                data.put("message", "my custom message");

                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);

                objectMapper.writeValue(response.getOutputStream(), data);

                //exception handled
                return new ModelAndView();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        //default processing
        return null;
    }
}