gpt4 book ai didi

java - 如何将 HTTP 生命周期中间件处理程序添加到 spring?

转载 作者:搜寻专家 更新时间:2023-11-01 02:08:03 25 4
gpt4 key购买 nike

我有一个CustomerController.java:

package com.satisfeet.http;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.satisfeet.core.model.Address;
import com.satisfeet.core.model.Customer;
import com.satisfeet.core.service.CustomerService;

@RestController
@RequestMapping("/customers")
public class CustomerController {

@Autowired
private CustomerService service;

@RequestMapping(method = RequestMethod.GET)
public Iterable<Customer> index() {
return this.service.list();
}

@RequestMapping(method = RequestMethod.POST)
public Customer create(@RequestBody Customer customer) {
this.service.create(customer);

return customer;
}

@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public Customer show(@PathVariable Integer id) {
return this.service.show(id);
}

@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
public void update(@PathVariable Integer id, @RequestBody Customer customer) {
this.service.update(id, customer);
}

@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void destroy(@PathVariable Integer id) {
this.service.delete(id);
}

}

和一个ExceptionController.java:

package com.satisfeet.http;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.satisfeet.core.exception.NotFoundException;

@ControllerAdvice
public class ExceptionController {

@ExceptionHandler(NotFoundException.class)
public ResponseEntity notFoundError() {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}

}

我现在想添加某种在写入响应之前执行的 HTTP 请求-响应中间件,并在 json 中写入 HTTP 状态代码:

HTTP/1.1 404 OK
Connection: close
Content-Type: application/json

{"error":"not found"}

我知道如何将 HttpStatus 转换为 String 但我不知道在哪里可以使用 @ControllerAdvice 全局执行此操作。

那么我该如何注册一个可以访问响应对象的全局处理程序呢?

最佳答案

我想你要找的是 spring Interceptor

请检查这个tutorial这是描述如何使用拦截器。

并检查 spring 文档 Intercepting requests with a HandlerInterceptor .

最后检查这个答案here

希望对您有所帮助。

关于java - 如何将 HTTP 生命周期中间件处理程序添加到 spring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26252155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com