在Filter中返回json数据,网上搜到的都是通过response获取流,再写入数据。
这边提供另外一个方法,通过“forward”来实现。将请求forward到Controller,Controller中返回json。
@Component public class Filter1 extends OncePerRequestFilter { private static final Logger log = LoggerFactory.getLogger(Filter1.class); @Override protected void initFilterBean() throws ServletException { super.initFilterBean(); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Map<String, Object> data = new HashMap(); data.put("key1", "val1"); data.put("key2", 1_000); request.setAttribute("data", data); request.getRequestDispatcher("/common/tojson").forward(request, response); } } @RestController public class CommonController { @RequestMapping("/common/tojson") @ResponseBody public Map<String, Object> error(HttpServletRequest request) { Map<String, Object> data = (Map<String, Object>) request.getAttribute("data"); return data; } }返回如下:
{ "key1": "val1", "key2": 1000 }