我有jsp页面search-menu.jsp,带有输入和一个按钮。当用户输入一个值并单击输入应该传递给REST API的按钮。然后响应应该传递给另一个名为search-results.jsp的jsp。
搜索引入了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>
以下是控制器类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());
REST调用的响应类似于
"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"
}
]
我的问题是如何获取输入并将REST响应传递给search-results.jsp.And我的控制器看起来没有正确调用REST模板。
以下是修改后的控制器方法。
@RequestMapping(value = "/search-menu",method = RequestMethod.GET)
public ModelAndView loadSearchMenuPage(){
return new ModelAndView("/home/search-menu", "searchitemdata", new SearchItemData());
}
@RequestMapping(value = "/search-menu/{searchItem}", method = RequestMethod.GET)
public ModelAndView generateSearchItem(@PathVariable String searchItem){
ModelAndView modelAndView = new ModelAndView("/home/search-results");
// modelAndView.addObject("searchItem", searchItem);
RestTemplate restTemplate = new RestTemplate();
String getItemUrl = baseUrl + searchItemNameUrl + searchItem;
ServerResponseMessage searchItemResponse = restTemplate.getForObject(getItemUrl, ServerResponseMessage.class);
modelAndView.addObject(searchItemResponse.getData());
return new ModelAndView("/search-results");
}
当我提交表单时,它会给出状态404。
答案 0 :(得分:0)
您的方法没有任何问题。在您的search-menu.jsp中,将控制器方法作为ajax请求调用。
$.ajax( "home/search-menu" )
.done(function(result) {
alert(result.data[0].itemName);
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});