Format LocalDateTime with spring, jackson - spring

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).

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

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

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

BindingResult requires dates input even without not null or validation

I got an issue with a web application in Spring.
I am writing a search jsp form with related controller and service.
I do not need some datas to be necessary, and it goes all fine but dates.
It requires me to insert dates into dates input tags, if I leave that boxes empty I got an error in BindingResult and my search service stops.
Why does it not accept empty values?
In the domain the attributes are not set to NotNull, and I even remove the #Valid annotation from the service, but it does continues to ask me for some datas into that fields.
Can anyone try to explain me where should I look to solve this issue?
Here is the code:
jsp form:
<form:form commandName="colloquioRicerca" action="colloquio_ricerca" method="post">
<fieldset>
<legend>Cerca un colloquio</legend>
<p class="errorLine">
<form:errors path="codiceFiscale" cssClass="error"/>
</p>
<p>
<label for="codiceFiscale">Codice Fiscale del Docente: </label>
<form:input id="codiceFiscale" path="codiceFiscale" tabindex="1"/>
</p>
<h5>Ricerca avanzata:</h5>
<p>
<label for="nome">Nome:<br><small>(accetta parziali)</small> </label>
<form:input id="nome" path="nome" tabindex="2"/>
</p>
<p>
<label for="cognome">Cognome:<br><small>(accetta parziali)</small></label>
<form:input id="cognome" path="cognome" tabindex="3"/>
</p>
<p>
<label for="dataColloquio">Cerca per data: </label>
<form:input id="dataColloquio" path="dataColloquio" tabindex="4" placeholder="dd/MM/yyyy"/>
</p>
<p>Cerca per periodo:</p>
<p>
<label for="dataIniz">Dal:</label>
<form:input id="dataIniz" path="dataIniz" tabindex="5" placeholder="dd/MM/yyyy"/>
<label for="dataFin">Al:</label>
<form:input id="dataFin" path="dataFin" tabindex="6" placeholder="dd/MM/yyyy"/>
</p>
<p>
<label for="esitoColloquio">Al:</label>
<form:input id="esitoColloquio" path="esitoColloquio" tabindex="7" placeholder="dd/MM/yyyy"/>
<!--
<label for="esitoColloquio">Esito del Colloquio:</label>
<form:select id="esitoColloquio" name="esitoColloquio" path="esitoColloquio" tabindex="7">
<form:option value="positivo" >Positivo</form:option>
<form:option value="negativo" >Negativo</form:option>
<form:option value="altro"></form:option>
</form:select>-->
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="8">
<input id="submit" type="submit" tabindex="9"
value="Search">
</p>
</fieldset>
</form:form>
domain:
public class ColloquioSearch {
#Size(min=16, max=16)
private String codiceFiscale;
private String nome;
//#Size(min=1, max=50)
private String cognome;
private Date dataColloquio;
private Date dataIniz;
private Date dataFin;
private String esitoColloquio;
service:
public List<Colloquio> getAllColloquio()
throws SQLException {
List<Colloquio> result = new ArrayList<Colloquio>();
Statement s= con.createStatement();
ResultSet rs = s.executeQuery(
"SELECT doc.codice_fiscale, col.data_colloquio, col.esito_colloquio, col.note_colloquio FROM colloqui_pj col, docenti_pj doc where doc.id_docente=col.id_docente");
while(rs.next());{// il getTime per convertirla in util.date
result.add(new Colloquio(rs.getString(1), rs.getTime(2), rs.getString(3), rs.getString(4)));
System.out.println("rs has next");
}
return result;
}
search method called by submit button:
#RequestMapping(value="prova")
public String goSearch(Model model){
logger.info("here we are");
model.addAttribute("colloquioRicerca", new ColloquioSearch());
return "ColloquioSearchForm";
}
#RequestMapping(value="colloquio_ricerca")
public String cerca(#ModelAttribute ColloquioSearch colloquioRicerca, BindingResult br, Model model){
logger.info("modelattribute:"+colloquioRicerca.toString()+"/"+colloquioRicerca.getCodiceFiscale());
logger.info("entered");
if (br.hasErrors()) {
FieldError fieldError = br.getFieldError();
logger.info("Code:" + fieldError.getCode() + ", object:"
+ fieldError.getObjectName() + ", field:"
+ fieldError.getField()+"siamo qui");
model.addAttribute("colloquioRicerca", colloquioRicerca);
return "ColloquioSearchForm";
}//validare datafine minore data inizio
String codiceFiscale = colloquioRicerca.getCodiceFiscale();/*
Date dataColloquio = colloquioRicerca.getDataColloquio();
Date dataIniz = colloquioRicerca.getDataIniz();
Date dataFin = colloquioRicerca.getDataFin();*/
String nome = "%"+colloquioRicerca.getNome()+"%";
String cognome = "%"+colloquioRicerca.getCognome()+"%";
String esitoColloquio = colloquioRicerca.getEsitoColloquio();
Colloquio colloquioTrovato = null;
logger.info("siamo prima dell'if isEmpty");
if (!codiceFiscale.isEmpty()){
logger.info("dentro if is empty");
try{
logger.info("dentro il try:"+colloquioRicerca.getCodiceFiscale());
List<Colloquio> lista = colloquiService.getAllColloquio();
if(lista.isEmpty()){logger.info("lista nulla");}
for(Colloquio colloquio : lista){
logger.info("colloquio su db cf:"+colloquio.getCodiceFiscale());
if(colloquio.getCodiceFiscale().equals(codiceFiscale)){
colloquioTrovato=colloquio;
logger.info("siamo dentro l'if: colloquio trovato"+colloquioTrovato.getCodiceFiscale());
}
}
}
catch(SQLException e){logger.info(e.getMessage()+"siamo qui?");}
}
if (colloquioTrovato == null){
model.addAttribute("colloquioRicerca", colloquioRicerca);
return "ColloquioSearchForm";
}
return "Daje";
}
Below is the error I got in console when jsp processing stops:
/*dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: modelattribute:project.domain.search.ColloquioSearch#5d2ca87b/hereitwritesthecorrectparam
dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: entered
dic 21, 2016 9:52:00 AM project.controller.ColloquioSearchController cerca
INFORMAZIONI: Code:typeMismatch, object:colloquioSearch, field:dataColloquiosiamo qui
dic 21, 2016 9:52:00 AM org.springframework.web.servlet.tags.form.InputTag doStartTag
GRAVE: Neither BindingResult nor plain target object for bean name 'colloquioRicerca' available as request attribute*/
above is the error I got in console since i leave empty the date fields on form; I got the error for DataColloquio, then for DataFin, and then for DataIniz, subsequently. The only way to avoid this error is by filling the form imput fields related
I hope to be into the lines of this site asking for this, thank You all.
P.S.: I know the code is bad structured, and it is not a good way to code the way it is written, I just wanted to explain the issue, meanwhile I am changing the structure, I just do not understand why it is asking me for not leaving empty date fields, and not the others.
It might be better if you print these
Date dataColloquio = colloquioRicerca.getDataColloquio();
Date dataIniz = colloquioRicerca.getDataIniz();
Date dataFin = colloquioRicerca.getDataFin();
directly in your controller, as I kinda doubt that spring will parse the string format coming from your input into Date object without customization.
In short, if you want to bind the Date fields you could register custom data binding for the date via WebDataBinder by simply adds
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
in your controller, with this, even if your input is empty, spring will do the rest for you. You have to notice that the format would be yyyy-MM-dd or just change it if you want. As an alternative, you can also do
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataColloquio;
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataIniz;
#DateTimeFormat(pattern = "yyyy-MM-dd") // Spring 4.0
private LocalDate dataFin;
And about your error, this probably caused from your service as there's a rs.getTime(..) there, meanwhile the string date from your input cannot be parsed correctly into Date object thus your model object cannot be targetted hence thrown error. As previous my suggestion, try to put #InitBinder annotated method that I give above into your controller and let's hope it solves everything.

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 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.

Resources