Spring

20. @RequestParam - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 2. 6. 16:31

1. @RequestParam

  • 요청의 파라미터를 연결할 매개변수에 붙이는 애너테이션
  • 필수여부:false
@Controller
public class RequestParamTest {
    @RequestMapping("/requestParam2")
//  name:파라미터 이름, required:필수여부
//  public String main2(@RequestParam(name="year", required=false) String year) {
    public String main2(String year){
//      http://localhost:8080/ch2/requestParam2      -> year=null
//      http://localhost:8080/ch2/requestParam2?year -> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }
}
  • 필수여부:true
@Controller
public class RequestParamTest {
    @RequestMapping("/requestParam3")
//  public String main3(@RequestParam(name="year", required=true) String year) {
    public String main3(@RequestParam String year){
//      http://localhost:8080/ch3/requestParam2      -> year=null	400 Bad Request.
//      http://localhost:8080/ch3/requestParam2?year -> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }
}
  • int타입 매개변수
@Controller
public class RequestParamTest {
    @RequestMapping("/requestParam8")
    public String main8(@RequestParam(required=false) int year) {
//      http://localhost/ch2/requestParam8      -> 500 java.lang.IllegalStateException
//      http://localhost/ch2/requestParam8?year -> year="" -> int? -> 400 Bad Request
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }
}
  • 필수입력X -> 기본값 지정
@Controller
public class RequestParamTest {
    @RequestMapping("/requestParam11")
    public String main11(@RequestParam(required=false, defaultValue="1") int year) {
//      http://localhost/ch2/requestParam11      -> year=1
//      http://localhost/ch2/requestParam11?year -> year=1
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }
}
  • 필수입력 -> 에러 처리 - @ExceptionHandler
    // Exception에러가 발생하면 메서드 호출됨
    @ExceptionHandler(Exception.class)
    public String catcher(Exception ex) {
        return "yoilError";
    }

  • 에러가 안보이지만 에러가 발생함

  • 대부분 info로 되어있다.

  • trace(가장 자세한 디버그)로 변경

  • 예외 발생

  • 예제
package com.fastcampus.ch2;

public class MyDate {
    private int year;
    private int month;
    private int day;

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    @Override
    public String toString(){
        return "MyDate [year=" + year + ", month=" + month + ", day=" + day + "]";
    }

}
package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Calendar;

@Controller
public class YoilTellerMVC4 {
    @ExceptionHandler(Exception.class)
    public String catcher(Exception e){
        e.printStackTrace();
        return "yoilError";
    }

    @RequestMapping("/getYoilMVC4") // http://localhost/ch2/getYoilMVC4
    public String main(MyDate date, Model model) {

        // 1. 유효성 검사
        if(!isValid(date))
            return "yoilError";  // 유효하지 않으면, /WEB-INF/views/yoilError.jsp로 이동

        // 2. 처리
        char yoil = getYoil(date);

        // 3. Model에 작업 결과 저장
        model.addAttribute("myDate", date);
        model.addAttribute("yoil", yoil);

        // 4. 작업 결과를 보여줄 View의 이름을 반환
        return "yoil"; // /WEB-INF/views/yoil.jsp
    }

    private boolean isValid(MyDate date) {
        return isValid(date.getYear(), date.getMonth(), date.getDay());
    }

    private char getYoil(MyDate date) {
        return getYoil(date.getYear(), date.getMonth(), date.getDay());
    }

    private char getYoil(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return " 일월화수목금토".charAt(dayOfWeek);
    }

    private boolean isValid(int year, int month, int day) {
        if(year==-1 || month==-1 || day==-1)
            return false;

        return (1<=month && month<=12) && (1<=day && day<=31); // 간단히 체크
    }
}
  • yoil.jsp
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<P> ${myDate.year}년 ${myDate.month}월 ${myDate.day}일은 ${yoil}입니다.</P>

</body>
</html>