2014-10-08 38 views
1

我有一個CustomerController.java如何添加HTTP生命週期中間件處理程序到spring?

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

那麼如何註冊一個可以訪問響應對象的全局處理程序?

回答

相關問題