I have a problem. I pass index value from JSP to controller successfully with ajax. When I click 'pass' button, the 'index' value is increasing and it passes to controller successfully with ajax. According to this index, I add list[index] to model.(with model.addAttribute) Although I have used ${nextWord} in the JSP, I cannot see this value in the view. How can I fix it? Thanks for your answer.
Controller
private List<Map<String, Object>> list;
#RequestMapping(value="/practice/{category}", method = RequestMethod.GET)
public String practicePageStart(#PathVariable("category") String category,
ModelMap model, HttpSession session){
// return 10 value from DB. Example;
// [{idWord=1},{word='exampleWord'},{meaning='turkishMeaning'},{type='NOUN'}]
list = wordService.getRandomWords(Integer.parseInt(String.valueOf(session.getAttribute("wordCount"))));
model.addAttribute("wordList", list);
return "practiceCategory";
}
#RequestMapping(value="/practice/{category}", method = RequestMethod.POST)
public String practicePagePost(#PathVariable("category") String category,
#RequestParam("index") int index, ModelMap model, HttpSession session){
model.addAttribute("nextWord", list.get(index).get("word"));
return "practiceCategory";
}
JSP
<script>
$(document).ready(function() {
$('#pass').click(function(event) {
var inputIndex = $('#index').val();
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/practice/${category}",
async: false,
data: { index: inputIndex }
complete: function(){
alert("${nextWord}");
$('#label').text("${nextWord}");
}
});
document.getElementById("index").value = (parseInt(document.getElementById("index").value) + 1).toString();
});
});
</script>
Change your controller method to this:
#RequestMapping(value="/practice/{category}", method = RequestMethod.POST)
#ResponseBody
public String practicePagePost(#PathVariable("category") String category,
#RequestParam("index") int index, ModelMap model, HttpSession session){
return list.get(index).get("word");
}
And your ajax to this:
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/practice/${category}",
async: false,
data: { index: inputIndex }
success: function(data){
alert(data);
$('#label').text(data);
}
});
Use #ResponseBody and return the object rather then returning a ViewResolver.
Returning a ViewResolver will resolve the view and send the html content while doing an Ajax call. Hence, it is not recommended if u need only value.
#ResponseBody example
public #ResponseBody Integer retriveValue(-,-,-){
return Integer.valueOf(5);
}
In my opinion you mix different:
(1) rendring phase (servlet container - background - java) vs.
(2) running in browser (js, no request attribute existing here).
You need one another jsp file just for rendering the data. Or you return it as json in practicePagePost method.
#ResponseBody
#RequestMapping(value="/practice/{category}", method = RequestMethod.POST)
public String practicePagePost(#PathVariable("category") String category,
#RequestParam("index") int index, ModelMap model, HttpSession session){
return list.get(index).get("word");
}
Related
I want to get an object from the form right away in ajax. Where object has name, booleans. But after the transfer, in Controller for some reason it comes with null fields.
Here HTML code:
<form id="profileStats" name="profileStats" action="#" th:action="#{/profile/{id}}" th:object="${profileStats}"
method="get">
<div class="photo">
<img src="./static/img/icon.ico" th:src="*{photoPath}" width="200px" height="200px"/>
</div>
<div class="info">
</div>
</form>
Controller, where i send object to HTML:
#GetMapping("/{id}")
public String getProfile(#PathVariable("id") long id, Model model) {
ProfileStats stats = new ProfileStats(userClient.getClient());
model.addAttribute("profileStats", stats);
return "profile";
}
Ajax, where i send object from HTML to Controller:
function setStatistic() {
var $form = $('#profileStats');
$.ajax({
url: window.location.pathname + '/progress',
method: 'GET',
cache: false,
data: $form.serialize(),
success: function (data) {
$('.info').html(data);
if (data.search("done") >= 0) {
stopProgress();
}
},
error: function (e) {
console.log("error", e)
}
});
}
Controller, where i get object from AJAX:
#GetMapping("/{id}/progress")
public ModelAndView getProgress(#ModelAttribute("profileStats") ProfileStats stats) {
ModelAndView modelAndView;
if (stats.isHaveAllMessage()) {
// HERE I GET NULL EXCEPTION
}
return modelAndView;
}
What am I doing wrong?
In debugging console.log($form.serialize()) I get nothing
You should not use ModelAttribute and ModelAndView in your GetMapping method if you want to use this from an AJAX call.
Use a #RequestBody and return a #ResponseBody instead. And in your AJAX call, create JSON from the form data to send and receive.
#ResponseBody
#GetMapping("/{id}/progress")
public ProgressResponse getProgress(#PathVariable("id) String id, #RequestBody ProfileStatsRequestBody requestBody) {
//.. do whatever needs to be done here
return new ProgressResponse(...)
}
With ProgressResponse and ProfileStatsRequestBody 2 new classes that map onto the JSON you want to send/receive.
You may want to include some fields as part of the form so Spring can do the mapping to the respective fields in the ProfileStats object. See the example in here: https://spring.io/guides/gs/handling-form-submission/
This question is follow up of Returning ModelAndView in ajax spring mvc
As the only answer says that we need to return json from Controller not ModelAndView. So the question is
what can be done to return ModelAndView ?
How the page will be rendered:-
will it have to be handled in success section of ajax call
Or Spring Controller will return the page as usually it does in Spring MVC
How the post data from ajax can be read in Controller.
Update 1:
As explained, I tried example. here is my code.
#Controller
public class AppController
{
#RequestMapping(value="/greeting",method=RequestMethod.POST)
#ResponseBody
public ModelAndView getGreeting(#RequestBody String json) throws IOException
{
JSONObject inputjsonObject = new JSONObject(json);
String name = inputjsonObject.getString("name");
ModelAndView modelAndView = new ModelAndView();
String result = "Hi "+name;
modelAndView.addObject("testdata", result);
modelAndView.addObject("user", getPrincipal());
modelAndView.setViewName("greetingHtmlPage");
return modelAndView;
}
// other stuff
}
In above controller method i can get data sucessfully. This method is called from a javascript on home.html. Below is javascript function
function callGreeting(){
var nameData={
name : document.getElementById("name").value
}
var dataInJson = JSON.stringify(nameData);
var csrf_token = document.getElementById("token").value;
$.ajax({
type: 'POST',
url: "greeting",
data: dataInJson,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function (response) {
document.open();
document.write(response);
document.close();
},
error: function (data) {
alert("failed response");
}
}); }
I have the page rendered successfully. But the url of application does not changes from AjaxSpringMVC:8080/home to AjaxSpringMVC:8080/greeting even after new page was loaded. This happens by itself in Spring MVC if using without Ajax.
what can be done to return ModelAndView ?
You can return ModelAndView As usual:
public ModelAndView returnView( Model model ) {
model.addAttribute( "myStaff", "my staff as string" );
return new ModelAndView( "myView" );
}
How the page will be rendered:
You control how it is rendered, .
When you return ModelAndView, the response has an HTML page.
After the Ajax call, you can do $("#container").html(response) or something like that to display the HTML page wherever you want.
In other words, you get a whole html page of content from the controller.
However, I highly recommend that you just return json object and update your view with the json object. Ajax is mostly used to create good user experience by updating part of the view asynchronously, so getting a whole page with Ajax does not make sense to me.
How the post data from ajax can be read in Controller.
There are many ways, I like to send json body directly to controller
#ResponseBody
#RequestMapping(value = "/saveObj", method = RequestMethod.POST, consumes = "application/json")
public String saveObj(Model model, #RequestBody MyObj myObj) {
// do staff..
}
I have a form in Bootstrap Modal and I want my Spring MVC controller to listen that. My problem is that the modal doesn't generate href because it's inside current page so I can't map just the modal in my Spring MVC controller.
I need it, because I want to show errors from bindingresult object. How can I do this?
This is my modal: http://www.bootply.com/zerZIYpNAF Let's say it's located in index.jsp so imaginary path would be /index#myModal.jsp or something like that.
#RequestMapping(value="/send", method = RequestMethod.GET)
public String get(Dummybean bean){
return "??"; //index#myModal
}
#RequestMapping(value="/send", method = RequestMethod.POST)
public String post(#Valid #ModelAttribute("dummy") DummyBean bean, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "??"; //index#myModal
}
//do something
}
public class DummyBean{
#NotNull
private String name;
public String getName() {
return username;
}
public void setName(String name) {
this.name = name;
}
You can't directly call the bootstrap modal to pop up by using controller. There for you will not able to bind form with Spring. But you can Achieve it using Ajax. You have to use form like normal Html form without using spring tags.
function searchAjax() {
var data = {}
data["query"] = $("#query").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "${home}search/api/getSearchResult",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
This is an example ajax for you to get an idea. You have to HttpServletRequest to retrieve data from controller side. Above example is taken from http://www.mkyong.com/spring-mvc/spring-4-mvc-ajax-hello-world-example/
1) create new function just for validation
2) create js function using prefer to use jquery and send ajax request to function in step one.
3) depend on validation status will handle errors or send form completely.
please read this article it's fully answered your question
javacodegeeks.com
I am making an ajax call to my Spring controller to get data from a blob object. I convert the blob to String, and try to return it. If I don't use #ResponseBody annotation, I get a 404 error, but using the annotation solves this.I tried specifying different datatypes in the ajax code, but it has no effect.
Can somebody please explain this behaviour to me. Also any suggestions regarding passing blob data back, in a better way ?
#RequestMapping(value = "/BlobData", method = RequestMethod.GET)
public #ResponseBody String genBlobData(int Id) throws SQLException {
Blob blob = daoImpl.getBlob(Id);
byte[] content = blob.getBytes(1, (int) blob.length());
String temp = new String(content);
return temp;
}
And the ajax :
$.ajax({
type: 'GET',
dataType: "text",
url: 'BlobData',
data: {Id:Id},
success: function(data)
{
var newWindow = window.open();newWindow.document.write(data);
/* alert(data); */
}
});
Thanks
Without #ResponseBody, the returned string is expected to be a relative path to your view (e.g. JSP file), hence the 404.
See http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-viewresolver-resolver.
I have an api controller action that takes a JObject as a
public class ThemeController : ApiController
{
[HttpGet]
public String Get(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/api/Theme/Get',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
When I look at HttpContext.Current.Request.Params["lessVariables"] it gives the correct string of json, but lessVariables is an empty JObject. Is there something else I have to do to setup Json.Net for this?
I've also tried it on a regular controller action
I have a controller action that takes a JObject as a
public class ThemeController : Controller
{
[HttpPost]
public String Post(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/Theme/Post',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
same result
The problem is that lessVariables is now a String. The whole structure probably looks like:
{
"lessVariables": "{'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}",
"siteName": "UnivOfUtah"
}
This is why you can see the correct string in the Params, but the framework is not able to convert it to JObject without knowing it is Json. When you Stringify the root object of a request, WebApi is smart enough to take it as Json as a whole, but you stringified a value inside so it has no idea it should be handled as json.
To fix it, you can either do custom binding with a model binder or custom action, or simply change your method to:
[HttpGet]
public String Get(String siteName, String lessVariables)
{
JObject jo = JObject.Parse(lessVariables);
Update:
To make the issue clearer, this is parsed fine by WebApi, but lessVariables is still a string:
[HttpGet]
public String Get(JObject rootObject)
{
// you now have rootObject which has a "siteName" and "lessVariables" parameter
var siteName = rootObject.GetValue("siteName");
var lessVariables = rootObject.GetValue("lessVariables");
// lessVariables.Type would return the JTokenType String