For example, I want to execute the “initRegister” method in Controller only after a user click the “Register” button in the page
@Controller
public class UserController
{
@RequestMapping(method=RequestMethod.GET, value="/initPage.do")
public String initPage(Model model)
{
return "home.jsp";
}
@RequestMapping(method=RequestMethod.GET, value="/initRegister.do")
@ResponseBody
public void initRegister(Model model)
{
model.addAttribute("reg", new RegisterForm());
}
}
JQuery AJAX invoked by “Register” button: (show a small popup window for registration)
$.get('initRegister.do', function()
{
$('body').append('<div>'
+'<form:form method="POST" modelAttribute="reg" '
+ 'commandName="reg" action="register.do">'
+ 'name: <form:input path="name"/>'
+ '<input type="submit" value="Submit">'
+ '</form:form>'
+ '</div>');
}
);
However I got the following error in the browser when I access “http://localhost:8080/…/initPage.do”
Neither BindingResult nor plain target object for bean name 'reg' available as request attribute
The page works only if I move “model.addAttribute(“reg”, new RegisterForm());” to “initPage” method. But I don’t need to create a RegisterForm instance until a uesr click “Register” button.
How to solve it?
I’m assuming this code is contained within home.jsp
You just can’t do this. The
form:formtag is processed on the server side when the initPage.do is rendered because it’s a JSP tag and means nothing in javascript or html. I’m amazed you got as meaningful a message as you did.When rendering JSP, it doesn’t care if the tags are in HTML, javascript, wherever. If it sees a JSP tag it’s going to perform appropriate processing. Trying to render the JSP code into the html page in response to an AJAX call just isn’t going to work because the processing of the JSP tags must happen on the server.
Typically you will want to return an object in JSON format (or XML I guess) and use that in the javascript. have a look at the docs for jQuery’s get command. Your function for the success handler has a ‘data’ parameter that will contain the response from your Ajax call. In order for that to work you should change the return type of
initRegisterfromvoidto something else. You can use Jackson to do the conversion from POJO to JSON.