기능 설명

JD Method URI
고객의 목록 조회 GET /customer
고객 조회 GET /customer/{custName}
고객 생성 POST /customer
고객 수정 PUT /customer/{custName}
고객 삭제 DELETE /customer/{custName}

 

 

컨트롤러

Customer.java

 

public class Customer {

    private String custName;	
    private String custAddress;		
    
    public String getCustName() {
    	return custName;	
    }		
    
    public void setCustName(String custName) {
    	this.custName = custName;	
    } 	
    
    public String getCustAddress() {
   		return custAddress;	
    } 	
    
    public void setCustAddress(String custAddress) {
    	this.custAddress = custAddress;	
    }	
    
}

 

CustomerController.java

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder; 


@RestController
public class CustomerController { 	

    @Autowired	
    private CustomerService customerService;		
    
    @RequestMapping(value = "/customer", method = RequestMethod.GET) 	
    public ResponseEntity<List<Customer>> listAllCustomers() {
    	final List<Customer> allCustomers = customerService.findAllCustomers();
        if (allCustomers.isEmpty()) {
        	return new ResponseEntity<List<Customer>>(HttpStatus.NO_CONTENT);
        }				
        
        return new ResponseEntity<List<Customer>>(allCustomers, HttpStatus.OK);	
    }		
    
    @RequestMapping(value = "/customer/{custName}", method = RequestMethod.GET)	
    public ResponseEntity<Customer> getCustomer(@PathVariable("custName") final int custName) {
    	final Customer fetchedCustomer = customerService.findByName(custName);
        if (fetchedCustomer == null) {
        	return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
        }				
        
        return new ResponseEntity<Customer>(fetchedCustomer, HttpStatus.OK);	
    }		
    
    @RequestMapping(value = "/customer", method = RequestMethod.POST)	
    public ResponseEntity<Void> createCustomer(@RequestBody Customer customer, UriComponentsBuilder ucBuilder) {
        if (customerService.isCustomerExist(customer)) {
        	return new ResponseEntity<Void>(HttpStatus.CONFLICT);		
        }		
        customerService.saveCustomer(customer);
        
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/customer/{custName}").buildAndExpand(customer.getCustName()).toUri());
        
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);	
    }		
    
    @RequestMapping(value = "/customer/{custName}", method = RequestMethod.PUT)	
    public ResponseEntity<Customer> updateCustomer(@PathVariable("custName") final int custName,
					@RequestBody Customer customer) throws Exception {
    
    	int count = customerService.updateCustomer(custName, customer);
        if (count == 0) {
        	return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);		
        }				
        
        return new ResponseEntity<Customer>(customer, HttpStatus.OK);	
    }		
    
    @RequestMapping(value = "/customer/{custName}", method = RequestMethod.DELETE)	
    public ResponseEntity<Void> deleteCustomer(@PathVariable("custName") final int custName) {
    	Boolean deleteResult = customerService.deleteCustomer(custName);
        if (deleteResult == null || !deleteResult) {
        	return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);		
        }				
        
        return new ResponseEntity<Void>(HttpStatus.OK);	
    }
}

 

@RestController는 Spring4 부터 지원을 하는 어노테이션으로 Controller 클래스에서 이것만 붙이면 메서드에 @ResponseBody를 붙이지 않아도 문자열, 객체 등을 리턴할 수 있다.

 

위의 Controller는 ResponseEntity를 사용해서 리턴을 해주고 있는데, 이는 단순 Value만 리턴하는 것이 아닌 상태코드, 응답메세지 등을 같이 보내주기 위한 용도로 보면 된다. ResponseEntity는 상태코드는 필수로 리턴을 해워햐 한다.

 

 

객체를 리턴하는데 객체는 보통 Json 형태로 변환하여 전달을 하기 때문에 이것을 사용하기 위해서는 jackson Library를 추가해서 사용을 해야 한다.

 

pom.xml

<dependency>    
    <groupId>com.fasterxml.jackson.core</groupId>    
    <artifactId>jackson-databind</artifactId>    
    <version>2.5.3</version>
</dependency>

 

 

추가로. PUT, DELETE 등의 Method를 지원하지 않는 구형 브라우저는 web.xml HiddenHttpMethodFilter 를 추가해 줘야 사용이 가능하다.

<filter>	
    <filter-name>httpMethodFilter</filter-name>	
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>	
    <filter-name>httpMethodFilter</filter-name>	
    <url-pattern>/</url-pattern>
</filter-mapping>

 

 

 

출처 : https://oingdaddy.tistory.com/15

'Backend > Spring Framework' 카테고리의 다른 글

[Spring] Swagger(스웨거) (2/2)  (0) 2022.07.29
[Spring] Swagger(스웨거) (1/2)  (0) 2022.07.28
[Spring] REST API  (0) 2022.07.25
[Spring] REST / RESTful  (0) 2022.07.25
[Spring] IoC (제어권 역전) 와 DI (의존성 주입)  (0) 2022.01.24

+ Recent posts