[DEV] 기록

[SpringBoot] 컨트롤러에서 RequestParam으로 Date 타입 받는 방법

꾸준함. 2022. 4. 4. 17:56

개요

ajax를 통해 Date 타입을 RequestParam으로 보내는데 아래와 같이 400 에러가 발생했습니다.

HTTP Status 400: The request sent by the client was syntactically incorrect.

 

코드

 

html


<form id="pageForm" method="get">
<!-- 중략 -->
<input type="date" id="from" name="from" value="${searchCondition.getFrom()}"/>
-
<input type="date" id="to" name="to" value="${searchCondition.getTo()}">
</form>
<script type="text/javascript">;
function fnListPage(pageNo) {
$.ajax({
url: "/listAjax.do",
method: "get",
data: $("#pageForm").serialize(),
dataType: "html",
success: function (data) {
$("#ajaxPage").html(data);
},
error: function (xhr, status, error) {
alert(xhr.status + " : 서버와의 통신이 원활하지 않습니다. 다시 시도해 주십시오.");
}
});
}
</script>
view raw .html hosted with ❤ by GitHub

 

Controller


@GetMapping(value = "/listAjax.do")
public ModelAndView listAjax(
@RequestParam("from") LocalDate from,
@Requestparam("to") LocalDate to) {
// 생략
}
view raw .java hosted with ❤ by GitHub

 

해결 방법

아래와 같이 @DateTimeFormat 어노테이션을 추가하면 해결되는 문제입니다.


@GetMapping(value = "/listAjax.do")
public ModelAndView listAjax(
@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate from,
@Requestparam("to") @DateTimeFormat(pattern="yyyy-MM-dd")LocalDate to) {
// 생략
}
view raw .java hosted with ❤ by GitHub

 

참고

https://stackoverflow.com/questions/15164864/how-to-accept-date-params-in-a-get-request-to-spring-mvc-controller

 

How to accept Date params in a GET request to Spring MVC Controller?

I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows: @RequestMapping(value="/fetch" , method=RequestMethod.GET) public @Response...

stackoverflow.com

 

 

반응형