D.Dev D.Dev - 29 days ago 10
reST (reStructuredText) Question

controller for pass jsp input to Rest API and pass the response to another jsp using spring MVC

I have jsp page search-menu.jsp with input and a button.When user inputs a value and click the button that input should pass to the REST API.Then the response should pass to another jsp called search-results.jsp.

search-menu.jsp

<form:form method="POST" modelAttribute="searchitemdata">

<form:input path="searchItem" id="txt-menu-search" name="txt-menu-search" type="text"/>
<button class="btn btn-primary input-sm" id="btn-menu-search"></button>
</form:form>


Below is the controller class SearchMenuController.java

@RequestMapping(value = "/search-menu", method = RequestMethod.POST)
public ModelAndView sendSearchItem(@ModelAttribute("searchitemdata") @Valid SearchItemData searchitemdata, BindingResult result, Model model) {

JSONObject jsonObject = new JSONObject();
jsonObject.put("searchItem", searchitemdata.getSearchItem());

RestTemplate restTemplate = new RestTemplate();

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Content-Type", "application/json");
HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(jsonObject, headers);

String searchUrl = baseUrl + searchItemNameUrl;

try {
ReplyFromServer data = restTemplate.postForObject(searchUrl, httpEntity, ReplyFromServer.class);
model.addAttribute("items", data);
logger.info("{}", data);

} catch (Exception e) {
logger.info(e.getMessage());

}


return new ModelAndView("/search-results", "searchitemdata", new SearchItemData());


The response from the REST call looks like

"status": "success",
"code": 200,
"message": "records found for the search key thanduri",
"data": [
{
"itemName": "Thanduri Pizza",
"description": "Lorem Ipsum is simply dummy text of the printing and ",
"type": "non-carbonated",
"categoryName": "Pizza",
"subCategoryName": "aaaaa"
}
],
"links": [
{
"rel": "self",
"link": "http://localhost:2222/xxxxxxx/api/v1.0/items/search/thanduri"
}
]


My problem is how to pass the response to search-results.jsp.And my controller looks like it doesn't work properly.

Answer

There is nothing wrong with your method.In your search-menu.jsp, call the controller method as a ajax request.

$.ajax( "home/search-menu" )
  .done(function(result) {
    alert(result.data[0].itemName);
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });