java拦截器返回自定义数据
时间: 2023-09-15 18:17:33 浏览: 55
要在 Java 拦截器中返回自定义数据,可以通过在拦截器中使用 HttpServletResponse 对象来设置响应内容。以下是一个示例:
```java
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// do something before the request is handled
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// do something after the request is handled
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("{\"message\": \"Custom response data\"}");
out.flush();
out.close();
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// do something after the response is sent back to the client
}
}
```
在上面的示例中,我们在 postHandle() 方法中设置了响应头的内容类型和编码,并使用 PrintWriter 对象将自定义数据输出到响应中。在此之后,拦截器将继续执行其它操作。
阅读全文