Multiple form submition in spring mvc 3.0 - spring

i want to show entered data of user in a registration form (like preview page) to confirm correctness of entered data and if they accept, then that data should go into the database.
here is my controller code:
#RequestMapping( value="/catalogue/FormPreview.action", method=RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,CatalogueBase catalogueBase) throws Exception {
if(catalogueBase.getTitleNumber()!= null)
{
request.setAttribute("titleNo", catalogueBase.getTitleNumber());
request.setAttribute("title", catalogueBase.getTitle());
request.setAttribute("name", catalogueBase.getName());
request.setAttribute("address", catalogueBase.getAddress());
request.setAttribute("email", catalogueBase.getEmail());
.....
return new ModelAndView("catalogue/catalogueFormPreview","catalogueBase",catalogueBase);
}
else
{
return create(catalogueBase);
}
}
#RequestMapping( value="/catalogue/create.action", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute CatalogueBase catalogueForm) throws Exception {
ModelAndView mvc = null;
try{
List<CatalogueBase> catalogueBases = new ArrayList<CatalogueBase>(); //getCatalogueBase(request);
catalogueBases.add(catalogueForm);
List<CatalogueBase> catalogueBaseList = catalogueService.create(catalogueBases);
mvc = new ModelAndView("catalogue/catalogueList");
} catch (Exception e) {
e.printStackTrace();
}
return mvc;
}
and I show the preview page as jsp using EL like:
Title NO : ${titleNo}
Title : ${title}
......
......
<a onclick="doAjaxPost();">Confirm Data<span class="icon icon44"></a>
and in the head section of the jsp I am calling ajax like:
<script>
function doAjaxPost() {
var name = $('#name').val();
var education = $('#education').val();
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "../catalogue/create.action",
data: str,
success: function(response){
alert("Record Added Successfully");
},
error: function(e){
alert('Error: ' + e);
}
});
};
it is showing data on preview page, but after clicking on confirm data, (hyperlink in preview page)
it sends null values to the create method(Second method) please can anyone tell why it's sending nulls and how I can solve this
thanks.

In Preview Page, you are only displaying the text, you need to get your data there as well in preview page either as hidden(or by any other means, like saving in session if much entries are there then etc). so that when you submit after confirmation, you can read all parameters.

Related

Spring boot, Thymeleaf, Ajax, get null object from ajax

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/

Ajax POST call to Spring MVC

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

How to map Bootstrap Modal to Spring MVC controller

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

handle the exception while ajax call and redirect to error page

I have a JSP page with textbox,drop down list and submit button. on-change of first dropdown list, items belonging to second drop down list should be populated dynamically in the dro down list.Using ajax call i'm calling spring controller where i have written logic to populate the list of items in second dropdown list. Requirement is i need to handle the exception in the spring controller and if any exception occurs redirect the entire page to error page which is other jsp page.
javascript function to get dynamic records to populate 2nd dropdown list records on change of 1st dropdownlist.
function showSID(Id)
{
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
var url = contextPath+"/getAllSID.htm?Id="+Id;
xmlHttp.onreadystatechange = function() {
handleServerResponse(xmlHttp);
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
function handleServerResponse(xmlHttp)
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
if (xmlHttp.responseText != "null")
{
//handled the response..
}
}
}
}
spring controller to populate records in 2nd dropdown list on change of first dropdown list:
#RequestMapping(value = "/getAllSID", method = RequestMethod.GET)
public void getAllSIDs(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute SIDDTO dto, BindingResult beException,
#RequestParam("SelectedList") String selList)
throws IOException {
try {
SIDDTO dynamicData = myService.getSIDDynamicData();//Database call
//logic..
response.setContentType("text");
response.resetBuffer();
response.getWriter().print(SID);
}
catch (Exception e)
{
LOGGER.error("Exception occured", e);
}
}
In the above controller, myService.getSIDDynamicData() retrieves data from database, sometimes database may be down or for any other reasons i may get some exceptions.So when some exception occurs i have to redirect to myErrorPage.jsp.
I have tried using response.sendRedirect("/myErrorPage.jsp"); but could not able to redirect to errorpage, may be the reason is my page is already loaded and only when i change the dropdown control hits the above controller and as page is already loaded it could not able to redirect to error page. Please suggest how to handle the exceptions in this scenario and redirect to JSP page(error page) whenever error occurs.Thanks.
Consider adding an exception-handler method to your Spring controller. This is a method that has an #ExceptionHandler annotation. In the exception handler you can set the HTTP status to something suitable. For example:
#ExceptionHandler(value = DataAccessException.class)
public final void handleException(final DataAccessException exception,
final HttpServletResponse response) {
if (exception instanceof RecoverableDataAccessException
|| exception instanceof TransientDataAccessException) {
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
response.setIntHeader("Retry-After", 60);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}

Getting different data in ajax response froms second time

I am encountering a problem which I am not able to find out why.
I am using spring mvc and I am sending ajax request to one of my controller.
$.get("<c:url value="/createcomment" />", {id: pageid , newcomment : newcomment})
.done(function(data){
$("#newcomment"+data.pageId).val('');
var html = '<tr><td>'+
'<div class="pull-left">'+
'<img class="img-rounded" src="resources/profile-pics/male/small.jpg" alt="">'+
'</div><div class="span4"><ul class="nav nav-stacked">'+
'<li><font size="2"><i class="icon-user"></i>'+data.account.firstName+' '+data.account.lastName+'</font></li>'+
'<li><font size="2">'+data.text+'</font></li><li><font size="1">'+data.postingDate+
'</font></li></ul></div></td></tr>';
$(html).inserAfter($("#tr"+data.pageId));
}
When i refresh the page and send the request i get the following desired object.
and when I send it second time again i get Some Document Object.
I don't understand what is happening wrong.
#RequestMapping(value="/createcomment",method=RequestMethod.GET)
public #ResponseBody Comment createComment(#RequestParam(value="id")final String pageId,#RequestParam(value="newcomment")final String text,
final HttpServletRequest request ,final WebRequest req){
final Comment comment = new Comment();
comment.setId(GenerateUID.generate());
comment.setText(text);
comment.setPostingDate(new Date());
comment.setPageId(Long.valueOf(pageId));
try {
return comment;
} catch (NumberFormatException e) {
return null;
} catch (SignInNotFoundException e) {
return null;
}
}
Just for additonal information i am using jQuery JavaScript Library v1.7.1
You might want to check if your method throws a NumberFormatException or SignInNotFoundException, in which case it returns null. Your network log shows that 0 bytes of data have been transferred.

Resources