无法拦截和操作Spring Boot中的HttpServletResponse
我需要Base64
解码我的Spring Boot服务收到的每个JSON请求负载。 在使用HTTP POST
方法发布之前,JSON负载将在客户端上进行Base64
编码。 此外,我还需要Base64
对提交给调用客户端应用程序之前的JSON响应进行编码。
我需要通过使用处理程序拦截器来减少样板代码。 我已经通过使用拦截器实现了操作的请求/传入段,但尚未实现响应段的操作。 我已经发布了下面的代码片段。 拦截响应的代码和base64对它的编码是在拦截器类的postHandle方法中。
我在这里做错了什么?
拦截器类:
public class Base64ResponseEncodingInterceptor implements HandlerInterceptor {
private static final String DECODED_REQUEST_ATTRIB = "decodedRequest";
private static final String POST = "POST";
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3) throws Exception {
try {
if (POST.equalsIgnoreCase(request.getMethod())) {
CharResponseWrapper res = new CharResponseWrapper(response);
res.getWriter();
byte[] encoded = Base64.encodeBase64(res.toString().getBytes());
byte[] encoded = Base64.encodeBase64(response.getHeader(ENCODED_RESPONSE_ATTRIB).getBytes());
response.getWriter().write(new String(encoded));
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
// preHandle and afterCompletion methods
// Omitted
}
上面使用的CharResponseWrapper
类:
public class CharResponseWrapper extends HttpServletResponseWrapper {
protected CharArrayWriter charWriter;
protected PrintWriter writer;
protected boolean getOutputStreamCalled;
protected boolean getWriterCalled;
public CharResponseWrapper(HttpServletResponse response) {
super(response);
charWriter = new CharArrayWriter();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (getWriterCalled) {
throw new IllegalStateException("getWriter already called");
}
getOutputStreamCalled = true;
return super.getOutputStream();
}
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return writer;
}
if (getOutputStreamCalled) {
throw new IllegalStateException("getOutputStream already called");
}
getWriterCalled = true;
writer = new PrintWriter(charWriter);
return writer;
}
@Override
public String toString() {
String s = null;
if (writer != null) {
s = charWriter.toString();
}
return s;
}
}
拦截器注册的JavaConfig类:
@Configuration
@EnableJpaRepositories(repositoryBaseClass = BaseRepositoryBean.class, basePackages = "")
@EntityScan(basePackages = { "com.companyname", "com.companyname.productname"})
public class RestConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Base64ResponseEncodingInterceptor());
}
}
使用拦截器的控制器类(此处仅显示工作请求段):
@Autowired
HttpServletRequest request;
String decodedRequest = null;
@ModelAttribute("decodedRequest")
public void getDecodedParam(){
decodedRequest = (String) request.getAttribute("decodedRequest");
}
postHandle
方法中的代码不起作用。 它可能是HttpServletResponse
为null
或者我收到一条异常消息:
已经调用getOutputStream
更新:解决方案直接在ResponseBodyAdvice中读取响应在Controller类中,我添加了以下内容:
@RestController
@RequestMapping("/api/ipmanager")
public class IPProfileRestController extends AbstractRestController {
@Autowired
HttpServletResponse response;
String encodedResponse = null;
@ModelAttribute("encodedResponse")
public void getEncodedResponse(){
response.setHeader("encodedResponse", StringUtils.EMPTY);
}
@RequestMapping(value = "/time", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }, consumes = {
MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody String saveAccessClientTime(@RequestBody String ecodedRequest) {
// Some code here
String controllerResponse = prettyJson(iPProfileResponse);
response.setHeader("encodedResponse", controllerResponse);
return controllerResponse;
}
}
在ResponseBodyAdvice中我有以下内容
@ControllerAdvice
public class Base64EncodedResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> converterType,
ServerHttpRequest request,
ServerHttpResponse response) {
String body1 = StringUtils.EMPTY;
// Encode the response and return
List<String> listOfHeaderValues = response.getHeaders().get("encodedResponse");
body1=new String(Base64.encodeBase64(listOfHeaderValues.get(0).getBytes()));
return body1;
}
}
正如Spring MVC文档所述:
HandlerInterceptor
的postHandle
方法并不总是非常适合与@ResponseBody
和ResponseEntity
方法一起使用。 在这种情况下, HttpMessageConverter
在postHandle
之前写入并提交响应,从而无法更改响应 ,例如添加标题。 相反,应用程序可以实现ResponseBodyAdvice
并将其声明为@ControllerAdvice
bean或直接在RequestMappingHandlerAdapter
上进行配置。
有人说:
我在这里做错了什么?
由于响应已经被提交,所以你不能改变它。 为了改变响应,你应该注册一个ResponseBodyAdvice<T>
并在那里放置你的响应编码逻辑:
@ControllerAdvice
public class Base64EncodedResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> converterType,
ServerHttpRequest request,
ServerHttpResponse response) {
// Encode the response and return
}
}
链接地址: http://www.djcxy.com/p/78455.html
上一篇: Unable to intercept and manipulate HttpServletResponse in Spring Boot