Spring Boot拦截器返回JSON

我有一个弹簧启动应用程序,它是REST Web服务.

我想添加一个拦截器,以便每个没有特定操作权限的角色都返回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,如何像使用@RestController注释的控制器那样使响应以JSON形式返回?

谢谢

解决方法:

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
上一篇:java-休眠拦截器-加载事件后


下一篇:SpringMVC----执行流程+底层解析