Backend/SpringBoot

Controller 에서 각종 파라메터 받기 + Cookie

Dean83 2025. 9. 12. 17:10
  • @RequestParam
    • 주소 뒤에 ? 로 추가하는 쿼리 파라메터의 경우 사용
    • required 설정 가능
    • defaultValue 설정 가능
@RestController
public class testController
{

	.....
	@GetMapping("test")
    public String testMethod(@RequestParam(required = false, defaultValue = 10) Integer age)
    {
    	....
    }
    
    @GetMapping("test1")
    public String testMethod(@RequestParam String name)
    {
    	....
    }
    ....
}
  • @PathVariable
    • Get 요청의 명시된 인자값을 받을때, url 경로상에 존재하는 경우
    • 다수의 파라메터를 Map으로 한번에 받을 수 있다.
    • 이름이 같을 경우 이름 명시를 생략할 수 있다.
@RestController
public class testController
{

	.....
	@GetMapping("test/{age}")
    public String testMethod(@PathVariable Integer age)
    {
    	....
    }
    
    @GetMapping("test/{name}")
    public String testMethod(@PathVariable("name") String sirName)
    {
    	....
    }
    ....
    
    @GetMapping("test/{name}/{age}")
    public String testMethod(@PathVariable Map<String,String> names)
    {
    	names.get("name");
        names.get("age");
    	....
    }
}

 

  • @RequestBody
    • 본문에 json 형식으로 오는 항목 추출
    • post 요청에서 사용
    • DTO로 묶어서 받을 수 있다. 
    • @Valid 와 함께 요청값이 DTO와 맞는지 검증도 할 수 있다.
...
@Data
public class testDTO
{
	....
}

@RestController
public class testController
{

	.....
	@PostMapping("test")
    public String testMethod(@RequestBody @Valid testDTO dtoItem)
    {
    	....
    }
    
    	.....

}
  • @CookieValue
    • 요청에 포함된 쿠키값을 받아올때 사용. 세션 식별자, 사용자 설정값 등을 추출.
    • 없는 쿠키는 기본값으로 대체
    • 보통 프론트엔드에서 쿠키를 추가 함
    • 백앤드에서 처리해야 하는 쿠키는 보안 관련된 JWT 토큰 등만 추가.
      • 추가를 위해서는 HTTPSurvletResponse를 받아 .addCookie를 호출해야함
      • 보안을 위해서
        • setHTTPOnly(true) 설정 : JS에서 접근 불가
        • setSecure(true) 설정 : HTTPS 환경에서만 쿠키 전송
        • sameSite("Strict") 또는 sameSite("Lax") 설정 필요 (CSRF 공격 방지)
    • SessionID는 Spring Security를 사용한다면 자동으로 추가됨 
      • HTTPSession 자료형의 인자값을 통해 추출 가능
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class JwtController {

    private static final String SECRET_KEY = "MySecretKey12345"; // 실제 서비스에서는 환경변수 사용
    private static final long EXPIRATION_TIME = 1000 * 60 * 30;  // 30분

    // 1. 로그인 → JWT 발급 & 쿠키 저장
    @GetMapping("/login")
    public String login(HttpServletResponse response) {
        // JWT 생성
        String jwt = Jwts.builder()
                .setSubject("jgpark") // 사용자 아이디 (여기선 예제)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        // 쿠키에 담기
        Cookie cookie = new Cookie("jwt", jwt);
        cookie.setHttpOnly(true);  // JS 접근 불가 → XSS 방어
        cookie.setSecure(false);   // HTTPS에서 true 권장
        cookie.setPath("/");       
        cookie.setMaxAge(60 * 30); // 30분
        response.addCookie(cookie);

        return "로그인 성공! JWT 쿠키 발급됨";
    }

    // 2. 이후 요청에서 쿠키로 JWT 읽기
    @GetMapping("/mypage")
    public String myPage(@CookieValue("jwt") String jwt) {
        try {
            // JWT 검증
            String user = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(jwt)
                    .getBody()
                    .getSubject();

            return "JWT 인증 성공! 사용자: " + user;
        } catch (Exception e) {
            return "JWT 검증 실패: " + e.getMessage();
        }
    }
    
    ...
    
     @GetMapping("/mypage")
    public String myPage(@CookieValue(value = "theme", required = false, defaultValue = "light") String theme) {
        return "현재 설정된 테마는: " + theme;
    }

}