HTTP는 HyperText Transfer Protocol의 약자로, 웹에서 클라이언트와 서버 간 데이터를 주고받는 프로토콜이다. 스프링 프레임워크는 HTTP 기반으로 동작하는 웹 애플리케이션을 쉽게 개발할 수 있도록 다양한 기능을 제공한다.
HTTP는 요청(Request)과 응답(Response) 구조를 가지며, 주로 다음과 같은 특징이 있다.
HTTP 통신은 Request(요청)와 Response(응답)을 주고받는 방식으로 이루어진다.
요청은 클라이언트(브라우저, 앱 등)에서 서버로 보내는 메시지이다. 기본적인 HTTP 요청 형식은 다음과 같다.
GET /hello HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: text/html
서버는 클라이언트 요청을 처리한 후 응답을 반환한다.
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 123
<html>
<body>Hello, World!</body>
</html>
스프링 MVC에서는 HTTP 요청과 응답을 쉽게 처리할 수 있도록 다양한 기능을 제공한다.
스프링에서는 @RestController 또는 @Controller를 사용하여 HTTP 요청을 처리한다.
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring!";
}
}
@RestController: JSON이나 문자열을 응답하는 컨트롤러.@RequestMapping("/api"): 기본 URL을 /api로 지정.@GetMapping("/hello"): GET 요청을 처리.@GetMapping("/greet")
public String greet(@RequestParam String name) {
return "Hello, " + name;
}
/greet?name=John → 응답: Hello, John@PostMapping("/user")
public User createUser(@RequestBody User user) {
return user;
}
@RequestBody를 사용하면 JSON 데이터를 받을 수 있음.스프링에서는 다양한 방법으로 HTTP 응답을 반환할 수 있다.
@GetMapping("/text")
public String textResponse() {
return "Hello, World!";
}
@GetMapping("/json")
public Map<String, String> jsonResponse() {
Map<String, String> map = new HashMap<>();
map.put("message", "Hello, JSON!");
return map;
}
Map을 사용하면 JSON 형태로 변환됨.@GetMapping("/custom-response")
public ResponseEntity<String> customResponse() {
return ResponseEntity.status(HttpStatus.OK)
.header("Custom-Header", "CustomValue")
.body("Custom Response");
ResponseEntity를 사용하면 상태 코드, 헤더 등을 자유롭게 설정 가능.서버는 응답을 보낼 때 상태 코드(Status Code)를 포함한다.
| 상태 코드 | 설명 |
|---|---|
| 200 OK | 요청 성공 |
| 201 Created | 리소스 생성됨 |
| 400 Bad Request | 잘못된 요청 |
| 401 Unauthorized | 인증 필요 |
| 403 Forbidden | 접근 금지 |
| 404 Not Found | 리소스 없음 |
| 500 Internal Server Error | 서버 내부 오류 |
javax.servlet.Filter를 구현하여 요청 및 응답을 가로챔.@Component
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("필터 실행됨");
chain.doFilter(request, response);
}
}
HandlerInterceptor를 구현하여 특정 요청을 가로챔.@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("인터셉터 실행됨");
return true;
}
}
스프링에서는 HTTP를 기반으로 한 REST API 개발이 가능하며, @RestController와 @RequestMapping을 활용하여 API를 만들 수 있다.
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
return ResponseEntity.status(HttpStatus.CREATED).body(user);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User usre = new User(id, "John Doe");
return ResponseEntity.ok(user);
}
}
@PostMapping: 사용자 생성@GetMappping("/{id}"): 사용자 조회스프링에서는 HTTP 프로토콜을 사용하여 웹 애플리케이션을 개발할 때, 요청과 응답을 처리하는 다양한 기능을 제공하며, REST API 개발도 쉽게 가능하도록 지원한다.
필터와 인터셉터를 활용하면 요청을 가로채거나 변형할 수도 있다.