Spring启动拦截器返回JSON

时间:2016-01-13 13:46:07

标签: spring spring-boot interceptor

我有一个Spring Web服务的Spring启动应用程序。

我想添加一个拦截器,以便每个没有特定操作权限的角色返回401错误代码。

    @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

    logger.info("Request URL::" + httpServletRequest.getRequestURL().toString()
            + ":: Start Time=" + System.currentTimeMillis());

    UsernamePasswordAuthenticationToken token  = (UsernamePasswordAuthenticationToken) httpServletRequest.getUserPrincipal();
    String roleStr =  token.getAuthorities().iterator().next().getAuthority();
    String action = httpServletRequest.getServletPath();


    Role role = roleRepository.findOne(Long.parseLong(roleStr));

    if (role.getActions().contains(action)) {
        return true;
    }

    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}

问题是响应总是返回HTML,如何使响应像JSON一样返回,就像用@RestController注释的控制器一样?

由于

1 个答案:

答案 0 :(得分:3)

package com.sha.home;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sha.model.Message;

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler)
        throws Exception {

        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
  System.out.println("start time"+startTime);

  ObjectMapper mapper = new ObjectMapper();
  Message msg = new Message("invalid","userinvalid");// customised pojo for error json message
  response.setContentType("application/json");
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  response.getWriter().write(mapper.writeValueAsString(msg));

  return false;


    }

    //after the handler is executed
    public void postHandle(
        HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView)
        throws Exception {

        long startTime = (Long)request.getAttribute("startTime");

        long endTime = System.currentTimeMillis();

        long executeTime = endTime - startTime;

        //modified the exisitng modelAndView


        //log it
        if(logger.isDebugEnabled()){
           logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
        }
    }
}

    enter code here