Problem while posting data in spring boot Rest Api- org.springframework.web.bind.MethodArgumentNotValidException - spring-boot

I am new to spring boot rest api.
I have create a category Rest controller using which i am posting data to my backend mysql database.
I also added spring-jpa and hibernate in my project and its working fine.
When I am posting data using Bootstrap form and JqueryAjax, i am gettting org.springframework.web.bind.MethodArgumentNotValidException in intellij console and 400 in browser console when i am hitting submit button in my form.
my rest cotroller code
private CategoryRepository categoryRepository;
//#GetMapping("/Categories")
#RequestMapping(value="/Categories", method=RequestMethod.GET)
public Page<Category> getAllCategories(Pageable pageable) {
return categoryRepository.findAll(pageable);
}
//#PostMapping("/Categories")
#RequestMapping(value="/Categories", method=RequestMethod.POST)
public Category createCategory( #Valid #RequestBody Category Category) {
return categoryRepository.save(Category);
}
my js-ajax file
$(document).ready(
function() {
// SUBMIT FORM
$("#Cateform").submit(function(event) {
// Prevent the form from submitting via the browser.
event.preventDefault();
ajaxPost();
});
function ajaxPost() {
// PREPARE FORM DATA
var formData = {
CategoryId : $("#CatId").val(),
CategoryName : $("#CatName").val(),
CategoryDescription : $("#Catdesc").val()
}
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080/Categories",
data : JSON.stringify(formData),
dataType : 'json',
success : function(result) {
if (result.status == "success") {
$("#postResultDiv").html(
"" + result.data.CategoryName
+ result.data.CategoryDescription
+ "Post Successfully! <br>"
+ "---> Congrats !!" + "</p>");
} else {
$("#postResultDiv").html("<strong>Error</strong>");
}
console.log(result);
},
error : function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
})
My Bootstrap form
<form id="Cateform">
<div class="form-group">
<input type="hidden" class="form-control" id="CatId" placeholder="Enter Book Id" name="CategoryId">
</div>
<div class="form-group">
<label for="CatName">Category Name:</label>
<input type="text" class="form-control" id="CatName" name="CategoryName">
</div>
<div class="form-group">
<label for="Catdesc">Category Desc:</label>
<input type="text" class="form-control" id="Catdesc" name="CategoryDescription">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my category model
#Entity
#Table(name = "Categories")
public class Category extends AuditingModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer categoryId;
public String CategoryName;
#NotNull
#Size(max = 250)
public String Description;
//gettter and setters
}
The good thing is that...i am able to post data using swagger-UI and PostMan but i dont know what is happeing when i am posting data using form and getting method argument not valid exception for the my description field of category model.
i have set this field as notnull in model but why its giving error from posting the data from UI and not from Swagger-UI and Postman.
below is the exxact error i get in intellij console when i am hitting submit in form
**
Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public edu.ait.shoppingCart.Dto.Category edu.ait.shoppingCart.Controllers.CategoryController.createCategory(edu.ait.shoppingCart.Dto.Category): [Field error in object 'category' on field 'Description': rejected value [null]; codes [NotNull.category.Description,NotNull.Description,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [category.Description,Description]; arguments []; default message [Description]]; default message [must not be null]] ]
**
browser error

Please note that the problem is variable name miss match. The ajax call sends the CategoryDescription while the entity expects Description also note the case sensitive C on categoryId. Ajax call sends a capital C while the entity was declared with a small letter c

Related

Validation messages don't show in Thymeleaf - kotlin - spring boot

I return the template of a form with this controller suspend method:
#GetMapping("/checkout/customer")
suspend fun checkoutCustomerView(model: Model): String {
model["cart"] = shoppingCartService.getShoppingCartWithItems()
model["checkout"] = checkoutService.getCheckout()
return "checkout/checkoutCustomer"
}
I post form data with:
#PostMapping("/checkout/customer")
suspend fun updateCustomerData(
request: ServerHttpRequest,
response: ServerHttpResponse,
model: Model,
#Valid #ModelAttribute customerData: CheckoutCustomerData,
bindingResult: BindingResult
): String {
if (bindingResult.hasErrors()) {
model["cart"] = shoppingCartService.getShoppingCartWithItems()
model["checkout"] = checkoutService.getCheckout()
return "checkout/checkoutCustomer"
}
model["checkout"] = checkoutWizardCookieService.updateCustomerData(customerData, request, response)
return "redirect:/checkout/shipping"
}
the binding gets populated when there's an error, I can see it in debug mode.
Data is:
data class CheckoutCustomerData(
#field:NotBlank
val firstName: String?,
)
and html file is:
<form id="customer-form" th:action="#{/checkout/customer}" th:object="${checkout}"
method="post">
<div class="mb-3 d-flex flex-row">
<input type="text" class="form-control me-3" th:field="*{firstName}" placeholder="First Name">
<p th:if="${#fields.hasErrors('firstName')}"
th:errorclass="invalid-feedback"
th:errors="*{firstName}" >The first name is mandatory</p>
</div>
</form>
when I submit the form without a value for the field "firstName", I should expect some error showing under the input field, which doesn't happen, because the form is considered valid, so #fields.hasErrors() returns false.
I am not sure what I am doing wrong.
I am using Spring Boot Webflux with kotlin and coroutines. Is there some extra configuration due to the reactive nature of the project, maybe?
Thanks
Is

Using $.ajax to send data via HttpPost in aspnet5, is not working

Ok basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
newColumnData = "{
'ColumnName': 'columnName'
'ColumnNumber': 'columnNumber'
}"
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST'
dataType: 'json',
data: newColumnData,
success: (data) ->
#res = $.parseJSON(data);
alert "Hit the Success part";
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The controller actions are
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public IActionResult ChangeColumnName(ColumnModel newColumnData)
{
string name = newColumnData.ColumnName;
m_Board.ColumnList[newColumnData.ColumnNumber].ColumnName = name;
return View("Show", m_Board);
}
Also the modelS if needed
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
So I have debugged both the Javascript and the controller action ChangeColumnName, and it is not hitting it. The javascript also does not hit the success part of the ajax call also. I have tried everything that comes to mind and done a lot of googling but it just won't work. I feel like it is because of the way I am sending the data for the $.ajax call but really I just don't know why this doesn't work.
Also if i want to update the column name, by removing the input and adding the normal HTML to display the name, am I right to return a view in the action method ChangeColumnName? I mean will it reload the page or add it dynamically. Will I have to add JS code in the success attribute of the $.ajax call to change it dynamically?
Any help will be greatly appreciated. Thank you.
Edit: Added the board model
Edit2: Updating showing the html code as a request of Stephen.
Using bootstrap column/grid design, and also bootstrap panels. I basically have column shown by html
<div id="1" class="panel panel-default BoardColumn">
<div class="panel-heading">
<h3 class="panel-title">Something1</h3>
</div>
</div>
I want to change the header class 'panel-title' and update it dynamically without reloading the page. I have set up another ajax call, so when the header is clicked a few input tags are added and and the html is changed to the following. In minimal explaining I have done this using jquery append and remove functions.
<div id="1" class="panel panel-default BoardColumn">
<div class="panel-heading">
<input class="PreviousColumnName" type="hidden" style="display: none;" value="Something1">
<input class="NewColumnName" name="ColumnName">
<input class="ColumnTitleSumbit" type="submit" value="Continue">
</div>
</div>
Now I want to get the value of the input with class name 'NewcolumnName', update the current column name in the model and place its new name. When the submit button is clicked, I want to remove the input tags and go back to the original html before that, showings it new column name without reloading.

Spring mvc Ajax search Form with Thymeleaf

I'm trying to add a search form in the navbar on every page in my spring mvc web app, just like the one here on stackoverflow, and I'm having issues. Right now I have a working search functions on a couple of my pages, using the typical mvc forms. I take the inputted string and store a variable called "searchString" in an object I created called "searchForm.java". Then I try to query that inputted string in the database using spring data's findbycontaing method, and then put that result on the model, and then represent that on the view, using thymeleaf. However I think that the navbar should be done using ajax, since it's on every page and pages with other forms.
So I think I'm sending the string that was submitted to the search form in the navbar to the controller where I queried it in the repository to bring back search results, then I tried to put the search results on the model, but I get nothing, all it does is redirect me to the search page. I may not be making very much sense, but I'll show my code, and if anyone could let me know if I'm going about my problem in the right way or not, and if you guys see any errors in my code. Thanks in advance.
So here's my ajax and jquery to submit the form.
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "navSearch",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
There may be an issue here, because in the console in the chrome developer tools, before it redirects, a message pops up very quickly that says uncaught TypeError: Cannot read property 'toLowerCase' of undefined, and it's coming from jquery.min.js:5 so that could be my issue, but I have no idea how to go about fixing this, and I've searched for answers so far with no luck.
Here's my html form, I think this shouldn't be a problem, but who knows, so I'll put it up anyways. And I'm using thymeleaf for this view.
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="submit" class="btn btn-default" id="searchButton">Search</button>
</form>
Here's my searchForm.java class, where I temporarily store the string to be queried in the database.
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
And Here's my controller, where I'm trying to handle the ajax submission and return it as search results on the setSearch.html page. What I'm thinking here is that the string "newSearch" from the form could be matched using the Spring Data query methods, and then be able to return it and add it to the model, but it's not working, it's just redirecting me to the /searchSet page with no data, because that's where the form action goes and that's what I tell it to return. So honestly I'm no sure if any data is even getting to this point.
#RequestMapping(value="setSearch/navSearch", method=RequestMethod.POST)
public #ResponseBody String navSearch (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
And here's an example of a working search method that I have in my controller that I use on a regular form, with no ajax, on the /searchSet page.
#RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
#RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(#ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
UPDATE
I've changed my code in the form from <button type="submit" class="btn btn-default" id="searchButton">Search</button> to <button type="button" class="btn btn-default" id="searchButton">Search</button> and now I get the Uncaught TypeError: Cannot read property 'toLowerCase' of undefined from earlier and nothing happens with the page.
UPDATE
I can now submit the ajax form without a problem, I was missing meta tags in the header, so the csrf wasn't submitting correctly, so now I get this error in the chrome developer tools console XHR Loaded (navSearch - 405 Method Not Allowed - 7.265999971423298ms - 634B)
UPDATE
Now everything works on the Ajax side, I needed to adjust my url to match the url I had in the request mapping on the controller and it runs through all the code fine. However the overall search function still doesn't work, here's my updated controller.
I know my issue here is that I'm returning a string and not an object, but I'm not sure how to return the object and then redirect the url to the /setSearch page. It's running through the code and returning a string "setSearch" in the console, because I told it to at the end of the controller.
#RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public #ResponseBody String search (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Here's my working ajax
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
but it's not working, it's just redirecting me to the /searchSet page
with no data, because that's where the form action goes and that's
what I tell it to return
You are right, it is because you are submitting the form and in the action you specify it to submit to setSearch, that is why the page is getting redirected to the same page. Just replace button type="submit" with button type="button" so that the form will not be submitted when searchButton is clicked.

Spring MVC Ajax Search Form Thymeleaf

So I'm trying to create a search form in the navbar of my site, and I'm using ajax to submit the form. I have other working search forms in my web app so I know how to do that. And I have the ajax submitting properly. I just don't know how to get the data from the form and use it in the controller to get the result that I want.
The way I'm doing the search function is by creating a searchForm.java object that has a string variable called searchString and I populate that and then query it against the database in the controller using spring data methods in my repository class.
So here's what my jquery ajax form looks like, and in the console on the chrome developer tools it returns "setSearch" like I tell it to in the controller, and I know that's an issue, I just don't really know how to fix it.
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
Here's my thymeleaf html page
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="button" class="btn btn-default" id="searchButton">Search</button>
</form>
This is my searchForm.java object
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
Here's my controller, and I know this won't work, because I'm returning a string and not a json object(I think that's right). But I tried to change it and I get a lot of errors, and I'm not sure how I should go about this.
#RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public #ResponseBody String search (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Here's a working example of a non ajax search function in my controller, so you guys can see what I'm trying to do.
#RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
#RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(#ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Let me know if I left anything out or if you would need to see any more code to see my issue. Thanks in advance.
If you are only submitting one parameter and it will be restfull there is no need for form or POST
Here is a simple example of how I would do a search that returns a array of objects from database. I hope you can use it to implement what you need.
HTML
<form>
<label for="search_input">Search:</label>
<input type="text" id="search_input">
</form>
Javascript
<script>
$.get("/search", {term: $('#search_input').val()}, function(data) {
// do your data manipulation and transformation here
});
</script>
Controller
RequestMapping("/search")
public #ResponseBody List searchPost(#RequestParameter("term") String query) {
List<Object> retVal = getListOfObjectFromDbBasedOnQuery(query);
return retVal;
}
Lot simpler (from a logical perspective), remember in RESTfull terms post is used to create objects. Retrieving data use GET only.

Format LocalDateTime with spring, jackson

In a spring rest application, i send a objet who contain a date
{ appointmentId: "", appointmentTypeId: "1", appointmentDate:
"2015-12-08T08:00:00-05:00" }
In my dto side
for my appointmentDate i have
#DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME)
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime appointmentDate;
In my dependencies i have
jackson-datatype-jsr310-2.6.3
I get this error
rg.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Text '2015-12-08T13:00:00.000Z' could not be
parsed, unparsed text found at index 23 (through reference chain:
server.dto.AppointmentDto["appointmentDate"]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Text
'2015-12-08T13:00:00.000Z' could not be parsed, unparsed text found at
index 23 (through reference chain:
server.dto.AppointmentDto["appointmentDate"])
tried only with DateTimeFormat, only with JsonDeserialize and both, but get the same error.
Edit
#RequestMapping(value = "/rest")
#RestController
public class LodgerController {
#RequestMapping(value = "/lodgers/{lodgerId}/appointments", method = RequestMethod.POST)
public Long createAppointmentsByLodgerId(#PathVariable("lodgerId") Long lodgerId, #RequestBody AppointmentDto appointmentDto) {
return appointmentService.save(appointmentDto);
}
}
public class AppointmentDto {
private Long appointmentId;
private Long appointmentTypeId;
private Long lodgerId;
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime appointmentDate;
public AppointmentDto() {
}
}
<form id="lodgerAppointmentForm" class="form-horizontal" role="form">
<input type="hidden" id="lodgerId" name="lodgerId">
<input type="hidden" id="lodgerAppointmentId" name="appointmentId">
<div class="form-group">
<label for="lodgerAppointmentDate" class="col-sm-2 control-label">Date</label>
<div class="col-sm-10">
<div class="input-group date" id="appointmentDatepicker" >
<input type="text" class="form-control" id="lodgerAppointmentDate" name="appointmentDate">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar">
</span>
</span>
</div>
</div>
</div>
</form>
var locale = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage);
moment().locale(locale);
$('#appointmentDatepicker').datetimepicker({
format: 'DD/MM/YYYY H:mm',
allowInputToggle: true
});
var lodgerId = $('#lodgerId').val();
var type = "post";
var url = "http://localhost:8080/rest/lodgers/" + lodgerId + "/appointments";
var data = transForm.serialize('#lodgerAppointmentForm');
data.appointmentDate = $('#appointmentDatepicker').data('DateTimePicker').date().format();
data.lodgerId = lodgerId;
data = JSON.stringify(data);
jQuery.ajax({
type: type,
url: url,
contentType: "application/json",
data: data,
success: function (data, status, jqXHR) {
},
error: function (jqXHR, status) {
}
});
transform.js come from https://github.com/A1rPun/transForm.js/blob/master/src/transForm.js
bootstrap datetimepicker come from https://github.com/Eonasdan/bootstrap-datetimepicker
Moment use 2015-12-09T08:00:00-05:00 (ISO 8601)
DateTimeFormatter.ISO_LOCAL_DATE_TIME who is: 2015-12-09T08:00:00 (ISO 8601)
both don't seem to use the same format
I think that your problem is described here:
https://github.com/FasterXML/jackson-datatype-jsr310/issues/14
I encounter the same error when was playing around with LocalDateTime and REST API. The problem is that you can serialize LocalDateTime to something like this:
2015-12-27T16:59:29.959
And you can create valid Date object in JavaScript from that string.
On the other hand if you try to POST/PUT JavaScript date to server then this:
var myDate = new Date();
JSON.stringify(myDate);
will create string like this (with extra Z - which stands for zulu time/UTC time zone):
2015-12-27T16:59:29.959Z
And that extra time zone info causes error in your case during deserialization because LocalDateTime don`t have time zone.
You can try to use ZonedDateTime on ther server or format by yourself date string on client side before sending (without Z suffiks).

Resources