BackEnd

@RequestParam 에 대한 정리

Taemin Kim 2022. 12. 18. 11:40

1. @ RequestParam

 

 

요청할 때 넘어온 파라미터를 매개변수에 연결할 때 쓰이는게 RequestParam 애너테이션이다

 

우리는 사용할 때 매개변수만 적어줬는데 원래는 괄호친 곳을 적어줘야하는데 생략이 가능하다

 

"year"는 파라미터 이름이고 required는 필수여부인데 false이니까 필수가 아니라는 뜻이다

생략했던 것과 아래에 (String year)는 같은 의미인데 간단히 쓰기위해 아래처럼 줄여서 쓸 수 있다 

 

 

아래에서 저렇게 URL을 적어줬을 때 year를 작성하지 않으면 null값이 뜨게된다

만약 year를 썻는데 값을 적어주지 않으면 "" 빈 문자열로 나오게 되는데

null과 빈문자열은 엄연히 다른 것이다 

 

 

위 이미지에서 보이는 코드처럼

@RequestParam String year 라고 써준 것이 위에서 작성된 긴 코드랑 동일한 코드이다

 

보통 아래처럼 생략해서 사용하지만 위에 길게 늘여놓은 코드도 알고 있어야 한다

 

 

이어서 설명해보면 required=true라고 적어줬음으로 year값을 필수로 적어줘야한다

그래서 밑에서 year를 적어주지 않으면 400에러가 나온다 필수값을 적지 않았기 때문이다

400에러는 알다시피 서버문제가 아닌 클라이언트쪽에서 제대로 된 값을 작성하지 않았을 경우 발생하는 에러이다

 

아래처럼 year는 적어줬지만 값을 적지 않으면 빈문자열이 들어가고 에러는 뜨지 않는다 필수값으로 year만 작성하도록 코드를 줬기 떄문이다 

 

 

이번에는 String이 아닌 int로 적어줬을 경우에 생기는 에러를 살펴보자

@RequestParam이라고 적어줬고 false로 적어줬으니 필수값이 아니라서 에러가 생기지 않아야한다

 

그런데 왜 에러가 발생하는걸까?

 

문제는 year값을 안주게 됬을 경우 null값이 발생하게 된다 null을 int로 바꿀수있을까? 불가능하다 

 

그러므로 500에러가 발생한다 서버쪽문제로 인식된다

 

이번에는 year라고만 적어줬다 그래도 에러가 발생한다 그 이유는 마찬가지로 year만 적어주게 되면 

 

빈 문자열로 값이 들어오게 되는데 "" 역시 int로 바꿀 수 없기 때문이다 서버쪽 문제가 아닌

클라이언트가 URL을 잘못줬기 때문에 400에러 클라이언트 에러로 인식되는 것이다

 

이 문제를 어떻게 해결 할 수 있을까?

 

기본값이라는 것을 적어주면 된다 

 

아무런 값이 없을 경우 기본값으로 1이라는 숫자를 default Value로 주게되면 

값을 안적으면 무조건 1이 찍히게 되고 1이라는 값은 문자열 "1"인데 문자열 "1"은 숫자1로 변환이 가능하다

그렇게되면 int가 되니까 문제를 해결 할 수 있게 되는 것이다

 

 

이런 전제조건은 우리가 필수입력이 아니라고 false를 줬을 경우 기본값 1을 꼭 넣어줘야한다는 것이다

이 방법이 싫다면 기본값을 false가 아닌 true로 주는 것도 가능하며 true일 경우에도 디폴트 값을 주는것 또한 가능하다는 것을 알고있자

 

테스트를 위해 예시 파일을 생성하고

 

 

해당파일안에 

 

package com.fastcampus.ch2;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class RequestParamTest {
    @RequestMapping("/requestParam")
    public String main(HttpServletRequest request) {
        String year = request.getParameter("year");
//    http://localhost/ch2/requestParam         ---->> year=null
//    http://localhost/ch2/requestParam?year=   ---->> year=""
//    http://localhost/ch2/requestParam?year    ---->> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam2")
// public String main2(@RequestParam(name="year", required=false) String year) {   // 아래와 동일
    public String main2(String year) {
//    http://localhost/ch2/requestParam2         ---->> year=null
//    http://localhost/ch2/requestParam2?year    ---->> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam3")
//    public String main3(@RequestParam(name="year", required=true) String year) {   // 아래와 동일
    public String main3(@RequestParam String year) {
//    http://localhost/ch2/requestParam3         ---->> year=null   400 Bad Request. required=true라서
//    http://localhost/ch2/requestParam3?year    ---->> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam4")
    public String main4(@RequestParam(required=false) String year) {
//    http://localhost/ch2/requestParam4         ---->> year=null
//    http://localhost/ch2/requestParam4?year    ---->> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam5")
    public String main5(@RequestParam(required=false, defaultValue="1") String year) {
//    http://localhost/ch2/requestParam5         ---->> year=1
//    http://localhost/ch2/requestParam5?year    ---->> year=1
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

// =======================================================================

    @RequestMapping("/requestParam6")
    public String main6(int year) {
//    http://localhost/ch2/requestParam6        ---->> 500 java.lang.IllegalStateException: Optional int parameter 'year' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
//    http://localhost/ch2/requestParam6?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam7")
    public String main7(@RequestParam int year) {
//    http://localhost/ch2/requestParam7        ---->> 400 Bad Request, Required int parameter 'year' is not present
//    http://localhost/ch2/requestParam7?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam8")
    public String main8(@RequestParam(required=false) int year) {
        // http://localhost/ch2/requestParam8        ---->> 500 java.lang.IllegalStateException: Optional int parameter 'year' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
        // http://localhost/ch2/requestParam8?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam9")
    public String main9(@RequestParam(required=true) int year) {
        // http://localhost/ch2/requestParam9        ---->> 400 Bad Request, Required int parameter 'year' is not present
        // http://localhost/ch2/requestParam9?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @RequestMapping("/requestParam10")
    public String main10(@RequestParam(required=true, defaultValue="1") int year) {
        // http://localhost/ch2/requestParam10        ---->> year=1
        // http://localhost/ch2/requestParam10?year   ---->> year=1
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";
    }

    @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";
    }
} // class

 

 

위 코드를 복사 붙여넣기 해주자 

이제 톰캣 서버를 실행해서 서버를 켜보면

 

이렇게 나오면 성공적이다

 

이제 requestParam을 호출해보면

 

이렇게 아무값도 나오지 않는데 그 이유는 year값을 주지 않았기 때문이다

 

확인하기 쉽게 하기위해서 코드를 다시 보면

이렇게 우리는 현재  yoil.jsp파일을 쓰고있다

그러니까 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>
<%-- 이렇게 미리 들어갈 값을 생각해서 만들어 놓는것을 EL이라고 한다 EL(Expression Language)--%>
<%-- 아래에 이렇게 출력될 자리를 만들어놓으면 모델 객체에 값이 아래에 들어가서 클라이언트에게 전달되는 것이다 --%>
<p> ${year}년 ${month}월 ${day}일은 ${yoil}입니다.</p>

</body>
</html>

 

위 코드를 보면 year값을 주지 않았다

 

여기에 이제 year값을 줘서 확인해보도록하자

<%@ 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>
<%-- 이렇게 미리 들어갈 값을 생각해서 만들어 놓는것을 EL이라고 한다 EL(Expression Language)--%>
<%-- 아래에 이렇게 출력될 자리를 만들어놓으면 모델 객체에 값이 아래에 들어가서 클라이언트에게 전달되는 것이다 --%>
year=<%=request.getParameter("year")%>
<p> ${year}년 ${month}월 ${day}일은 ${yoil}입니다.</p>

</body>
</html>

  이렇게 작성해주고 서버를 다시 켠 후 새로고침을 해보자

 

이렇게 null값이라고 잘 나오는 것을 알 수 있다 

 

이번에는 h1태그로 조금 더 잘보이게 키워보고 ?를 사용해서 쿼리스트링으로 year를 적어보면

 

year=null이 아닌 year=로 출력이된다 = 뒤에 값이 보이지는 않지만

실질적으로 "" 빈문자열이 들어간 것이다

인텔리제이 안에서 보면 이렇게 year=[]이라고 잘 나오는 것을 확인 할 수 있다

 

여기서 값이 제대로 안나오는데 에러가 안나오는 이유는 

필수값으로 설정하지 않았기 때문이다

 

이번에는 

    @RequestMapping("/requestParam3")
//    public String main3(@RequestParam(name="year", required=true) String year) {   // 아래와 동일
    public String main3(@RequestParam String year) {
//    http://localhost/ch2/requestParam3         ---->> year=null   400 Bad Request. required=true라서
//    http://localhost/ch2/requestParam3?year    ---->> year=""
        System.out.printf("[%s]year=[%s]%n", new Date(), year);
        return "yoil";

위 코드를 한번 요청해보도록 하자

 

보다시피 400에러가 나왔다 400에러는 클라이언트가 요청을 잘못했을 경우 나타나는 에러이다

 

위에 코드에서 3번을 요청했는데 코드를 자세히보면 required는 true로 필수이고 String이다

필수값인데 year를 안써줬기 때문인데 그럼 이번에는 뒤에 year를 붙여보자

 

이렇게 적어주면 에러가 나오지 않는다 String이라고 가능한 것이고 

빈문자열이지만 값이 넘어왔기 때문인다 만약 String이 아닌 int였다면 에러가 나오게 된다

빈문자열을 int로 변환할 수 없기 때문이다

 

이번에는 8번을 입력해보자

아래코드이다

@RequestMapping("/requestParam8")
public String main8(@RequestParam(required=false) int year) {
    // http://localhost/ch2/requestParam8        ---->> 500 java.lang.IllegalStateException: Optional int parameter 'year' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
    // http://localhost/ch2/requestParam8?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
    System.out.printf("[%s]year=[%s]%n", new Date(), year);
    return "yoil";
}

코드를 보면 required가 필수가 아닌 false이다 그리고 int로 적어줬다

이 상태에서 url요청을 8번을 해보면 http://localhost:8080/requestParam8 으로 요청했다

 

이번에는 이렇게 500에러가 나오게 된다 

그 이유는 필수값이 아니기때문에 year값을 주지 않아도 되어서 클라이언트 잘못이 아니기때문에

서버쪽 에러 코드인 500에러가 나오게되는 것이다 

 

그렇다면 이번에는 defaultValue를 써주고 다시 서버를 켠 다음 새로고침해보자

 

@RequestMapping("/requestParam8")
public String main8(@RequestParam(required=false, defaultValue = "2021") int year) {
    // http://localhost/ch2/requestParam8        ---->> 500 java.lang.IllegalStateException: Optional int parameter 'year' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
    // http://localhost/ch2/requestParam8?year   ---->> 400 Bad Request, nested exception is java.lang.NumberFormatException: For input string: ""
    System.out.printf("[%s]year=[%s]%n", new Date(), year);
    return "yoil";
}

똑같은 url을 주고 새로고침해보면?

이번에는 500에러가 아닌 null이라고 출력된다 인텔리제이를 들어가보면

 

이번에는 year=[]가 아닌 year=[2021]이라고 출력되고 있다 

 

실제로 입력한 값은 null인데 컨트롤러가 받은 값은 2021인 것이다

 

만약 이 상태에서 다시 year값을 주면 어떻게 될까?

이번에는 400에러가 발생했다

 

이전에 설명한 것 처럼 현재 코드는 String이 아닌 int인데 year만 주게되면 빈문자열 " " 이 들어오게되는데

String이기 때문에 서버 에러가 아닌 요청한 클라이언트쪽 에러인 400에러가 나오는 것이다

 

하지만 서버쪽 잘못이 아닌 클라이언트의 잘못된 요청이라고 할지라도 사용자에게 이런 에러를 보여주는 것은

바람직하다고 볼 수는 없다 그러므로 우리는 예외처리라는 것을 사용해서 개선을 해볼 수 있는데

 

@Controller
public class RequestParamTest {
    @ExceptionHandler(Exception.class)
    public String catcher(Exception ex){
        return "yoilError";
    }

ExceptionHandler를 통해서 예외가 발생했을 경우 yoilError.jsp파일을 호출해서 사용자에게 에러내용을 전달 할 수 있다

괄호안에 에러가 발생했을 경우 아래에 있는 catcher가 실행되게 되는 것이다

 

그리고 서버를 껏다 켠 후 다시 실행해보면?

이전이랑 다르게 문자열로 잘 설명되어지고 있다

 

int year처럼 변환이 필요할 경우 예외처리를 통해 사용자친화적인 에러를 보여줄 필요가 있다

 

이렇게 예외처리가 발생했는데 인텔리제이 내부에서는 예외처리가 없다고 나온다

 

그 이유는 예외처리가 발생되었지만 출력이 되지 않은 것이다

 

조금 더 자세하게 예외처리 된 내용을 보고싶을 경우에는 

아래 경로로 들어가서 

resources안에 log4j.xml을 열어보자

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

   <!-- Appenders -->
   <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <param name="Target" value="System.out" />
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%-5p: %c - %m%n" />
      </layout>
   </appender>
   
   <!-- Application Loggers -->
   <logger name="com.fastcampus.ch2">
      <level value="info" />
   </logger>
   
   <!-- 3rdparty Loggers -->
   <logger name="org.springframework.core">
      <level value="info" />
   </logger>
   
   <logger name="org.springframework.beans">
      <level value="info" />
   </logger>
   
   <logger name="org.springframework.context">
      <level value="info" />
   </logger>

   <logger name="org.springframework.web">
      <level value="info" />
   </logger>

   <!-- Root Logger -->
   <root>
      <priority value="warn" />
      <appender-ref ref="console" />
   </root>
   
</log4j:configuration>

 

이렇게 코드가 나오는데 level value를 보면 info라고 적혀있는 것을 볼 수 있다

 

아래쪽에 있는 springframework.web에 해당하는 info를 지우고 trace라고 적어주자

 

debug도 있는데 trace가 가장 디테일하게 출력이 되기 때문에 trace로 바꿔주고 저장해주고

 

다시 서버를 꼇다 켠 후 새로고침을 해보면

 

이렇게 방대한 에러가 나오는데 위로 조금 올려가다보면

 

int를 String으로 변환하는데 에러가 발생했다고 나오고 있다

org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: ""

 

여기서 for input string : "" 이라고 하는 것은 입력된 값은 빈문자열이라는 뜻이다

 

말그대로 너 입력을 string으로 했는데 그걸 내가 int로 바꾸는 과정에서 문제가 발생했어 ! 라는 의미이다

 

정리하자면 필수입력이 아닐 경우 defaultValue="1"이라고 줘야한다

 

"1" 은 숫자 1로 변환이 가능하다

 

만약 디폴트값을 주지 않았다면 사용자친화적인 에러내용 확인을 위해 예외처리라도 꼭 해줘야 한다는 것을 잊지말자

 

이번에는 인텔리제이로 돌아가서 YoilTellerMVC파일을 조금 수정해보자

 

@Controller
public class YoilTellerMVC {//http://localhost:8080/getYoil?year=2021&month=10&day=1
    @RequestMapping("/getYoilMVC") // 맵핑주소를 MVC로 바꿔준다 맵핑은 중복되면 충돌다니까 중복되지 않게 해야한다
    public ModelAndView main(int year, int month, int day) throws IOException { // 모델을 적어주고 기존에 사용중이던 response는 더이상 필요없으니 지워줬다

 

해당 코드에도 똑같이 @RequestParam을 붙여보고

 

public class YoilTellerMVC {//http://localhost:8080/getYoil?year=2021&month=10&day=1
    @RequestMapping("/getYoilMVC") // 맵핑주소를 MVC로 바꿔준다 맵핑은 중복되면 충돌다니까 중복되지 않게 해야한다
    public ModelAndView main(@RequestParam(required = true) int year,
                             @RequestParam(required = true) int month,
                             @RequestParam(required = true) int day) throws IOException { // 모델을 적어주고 기존에 사용중이던 response는 더이상 필요없으니 지워줬다

 

서버를 껏다 켠 후 재실행해보자

 

보이는 바와 같이 필수값이 true인데 값을 적지 않아서 400에러가 떳다

 

이제 이 에러가 아닌 사용자 친화적인 에러로 바꿔보자

@Controller
public class YoilTellerMVC {//http://localhost:8080/getYoil?year=2021&month=10&day=1
    @ExceptionHandler(Exception.class)
    public String catcher(Exception ex){
        ex.printStackTrace();
        return "yoilError";
    }
    @RequestMapping("/getYoilMVC") // 맵핑주소를 MVC로 바꿔준다 맵핑은 중복되면 충돌다니까 중복되지 않게 해야한다
    public ModelAndView main(@RequestParam(required = true) int year,
                             @RequestParam(required = true) int month,
                             @RequestParam(required = true) int day) throws IOException { // 모델을 적어주고 기존에 사용중이던 response는 더이상 필요없으니 지워줬다

 

이렇게 상단에 예외처리를 해주고 예외처리 시 프린트로 찍어서 어떻게 나오는지도 적어줬다 

 

서버를 꼇다 켠 후 새로고침해보면

 

이렇게 yoilError에서 작성된 내용으로 잘 출력되고있다

 

그리고 인텔리제이를 보면

 

에러코드가 잘 나오는 것을 볼 수 있다

 

ex print를 지우고 다시 출력해보면

 

기본적으로 log4에서 수정한 trace가 에러를 잡아주긴 하지만 빨간색으로 출력된 에러 코드는 사라지게 된다

 

 

자 이번에는 

 

YoilTellerMVC파일을 복사해서 2번 그리고 4번으로 만들어주자

2번 파일

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Calendar;

//년월일을 입력하면 요일을 알려주는 프로그램
@Controller
public class YoilTellerMVC2 {
    @ExceptionHandler(Exception.class)
    public String catcher(Exception ex){
        ex.printStackTrace();
        return "yoilError";
    }
    @RequestMapping("/getYoilMVC2") // 맵핑주소를 MVC로 바꿔준다 맵핑은 중복되면 충돌다니까 중복되지 않게 해야한다 
    public ModelAndView main(@RequestParam(required = true) int year,
                             @RequestParam(required = true) int month,
                             @RequestParam(required = true) int day) throws IOException { // 모델을 적어주고 기존에 사용중이던 response는 더이상 필요없으니 지워줬다

        ModelAndView mv = new ModelAndView();
//         1. 유효성 검사
        if (!isValid(year,month,day))
            return mv;

        // 2. 요일 계산
        char yoil = getYoil(year, month, day);

        // 3. 계산한 결과를 model에 저장
        mv.addObject("year", year);
        mv.addObject("month", month);
        mv.addObject("day", day);
        mv.addObject("yoil", yoil);

        // 4. 결과를 보여줄 view를 지정
        mv.setViewName("yoil");
        return mv;

//        return "yoil"; //WEB-INF/views/yoil.jsp 를 이용해서 작업처리된 결과를 출력해라는 의미이고 반환타입은 문자열이므로 상단에 public void를 public String으로 변경해야함
    }
    // 메서드가 Private으로 설정되는 이유는 이 클래스 안에서만 사용되게 하기위해서이다
    private boolean isValid(int year, int month, int day) {
        return true;
    }
    private char getYoil(int year, int month, int day) {
        Calendar cal= Calendar.getInstance();
        cal.set(year, month -1, day -1); // 위에서 직접 선언해줬으니까 원래 이름 그대로 적어줘야한다

        int dayOfweek = cal.get(Calendar.DAY_OF_WEEK); //1:일요일 2:월요일 ...
        return "일월화수목금토".charAt(dayOfweek);
    }
}

4번파일에서는 year, month, day를 Mydate로 하나로 만들어주고 

 

 

커맨드 숫자 1을 눌러서 class를 생성해준다

 

 

생성한 다음 Generate를 이용해서 getter setter toString 모두 설정을 해준다

 

 

우클릭해주면 Generate라고 나오는데 

 

위쪽에서 getter , setter 그리고 마지막 toString까지 모두 눌러주면

 

package com.fastcampus.ch2;

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

    public int getYear() {
        return year;
    }

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

    public int getMonth() {
        return month;
    }

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

    public int getDay() {
        return day;
    }

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

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


이렇게 코드가 자동으로 나오게 된다

 

그리고 지금 보면 하단에 빨간색으로 에러 표시가 나오게된다

 

위에서 date로 한번에 받았으니 아래에도 다 고쳐줘야한다

 

3번에서는 year, month, day 모두 쓰고있는데 month, day는 지워준다

 

// 3. 계산한 결과를 model에 저장
mv.addObject("myDate", date);
mv.addObject("yoil", yoil);

 

이렇게 두줄로 만들어주고 키를 myDate value를 date로 적어준다 

지금처럼 커맨드 숫자 1을 눌러서 메서드를 만들어준다

 

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

 

그리고 return을 위 코드처럼 get으로 다 받아준다

 

isValid도 똑같이 적어주고 이름만 바꿔주자

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

 

모두 저장해주고 서버를 꼇다 켠 후 MVC4를 호출해보자

 

 

정상적으로 잘 호출되는 것을 알 수 있다

 

그럼이번에는 빈값이 아니라 쿼리스트링으로 값을 직접 줘보도록 하자

 

이제 이렇게 년월일 정상적으로 값이 나오고있다 

 

요 며칠 블로그에 포스팅을 하면서 모든 것들을 하나하나 다 캡쳐해서 여기다 적으면서 정리하고있는데

처음에는 이게 맞는 방법이라고 생각했는데 진도가 너무 느려진다

 

물론 학습하는 방법에 정답은 없지만 내가 실제적으로 사용해보고 익힌것을

한번 해본거 완전히 내 것으로 만들 수는 없다

 

그말은 즉 여기에 정리 할 때 이게 무엇인지 

 

개념

동작원리

흐름

 

정도만 작성하고 실습같은 것은 각자 하는게 맞다고 생각이 든다

 

내가 듣고있는 강의 또는 책에 나오는 예제가 모든 사람들에게 있는 것 또한 아니기에

 

다음 포스팅부터는 이론, 개념, 동작원리 정도로만 작성하고

 

진행하면서 겪은 에러사항이나 문제점을 추가하면서 살을 붙이는 식으로 진행할 생각이다

 

그럼 이것으로 @RequestParam에 대한 정리를 마친다