Issue
I'm using the functional web framework for a non-reactive application. Consuming JSON seems simple enough as request.body(FormModel.class)
However, when the data is x-www-form-urlencoded
, I'm trying
default RouterFunction<ServerResponse> submit() {
return RouterFunctions.route(POST(submitRoute()),request -> {
var request.body(new ParameterizedTypeReference<FormModel>() {});
return temporaryRedirect(allRoute()).build();
});
}
And I'm getting:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Using MVC, this would work just by declaring a FormModel
parameter and annotating it with @ModelAttribute
Solution
Apparently, "binding" is not the same as "converting" for Spring, and the systems involved are different. There's no easy way of getting binding to work with router functions. There's an open issue about it targeting Spring 6. As per the workaround given there, my code would work with
default RouterFunction<ServerResponse> submit() {
return RouterFunctions.route(POST(submitRoute()).and(accept(MediaType.APPLICATION_FORM_URLENCODED)), request -> {
var form = formService().emptyForm();
var binder = new ExtendedServletRequestDataBinder(form, "editing");
binder.bind(request.servletRequest());
return temporaryRedirect(allRoute()).build();
});
}
Note that you have to get an empty FormModel
instance from somewhere. It's not the best, but it works.
Answered By - Haf
Answer Checked By - Senaida (JavaFixing Volunteer)