Sending ajax response to another controller using Spring MVC - ajax

I have a view from where I am sending a request to a Controller and as a result getting response back to the view page. Now I want to pass the ajax response in to the next Controller but I do not know what will be the type of response in Controller
This is my ajax code:
$.ajax({
type: "POST",
url: "<c:url value="/menu/menucheckout/${restaurant_menu.name}"/>",
data : {"amount":amount, "orderoption" :orderoption, "date":date , "time":time ,'menuitemsArray': menuitemsArray ,'menuPriceArray': menuPriceArray , 'menuSpiceeArray': menuSpiceeArray , 'ItemQuantityArray': ItemQuantityArray },
success: function(response){
console.log(response);
window.location.href = "/BistroServicesMenuApp/welcome/getordercheckout/"+response.model;
}
});
Here is the Menu Controller
#Controller
#RequestMapping(value = "/menu")
public class MenuController {
#Autowired
private MenuTypeService menutypeService;
#RequestMapping(value="/menucheckout/{restaurantname}" ,method = RequestMethod.POST )
#ResponseBody
public ModelAndView menucheckout(#PathVariable("restaurantname") String restaurantname , HttpSession session, HttpServletRequest request, HttpServletResponse response) throws SQLException, NamingException, IOException
{
ModelAndView model = new ModelAndView("/welcome/getordercheckout");
System.out.println("COMING IN menucheckout CONTROLLER" + restaurantname);
System.out.println("orderoption" + request.getParameter("orderoption"));
String amount = request.getParameter("amount");
String orderoption = request.getParameter("orderoption");
String date = request.getParameter("date");
String time = request.getParameter("time");
String[] menuitemsArray = request.getParameterValues("menuitemsArray[]");
String[] menuPriceArray = request.getParameterValues("menuPriceArray[]");
String[] menuSpiceeArray = request.getParameterValues("menuSpiceeArray[]");
String[] ItemQuantityArray = request.getParameterValues("ItemQuantityArray[]");
model.addObject("restaurantname", restaurantname);
model.addObject("amount", amount);
model.addObject("orderoption", orderoption);
model.addObject("date", date);
model.addObject("time", time);
model.addObject("menuitemsArray", menuitemsArray);
model.addObject("menuPriceArray", menuPriceArray);
model.addObject("menuSpiceeArray", menuSpiceeArray);
model.addObject("ItemQuantityArray", ItemQuantityArray);
return model;
}
}
Now Here is the Second Controller "OrderController":
#Controller
#RequestMapping("/welcome")
public class OrderController {
#Autowired
private OrderService orderService;
#RequestMapping("/getordercheckout/{response}")
public ModelAndView getOrderCheckOut(#PathVariable("response") ModelAndView response)
{
ModelAndView model = new ModelAndView("/getordercheckout");
model.addObject("response" , response);
System.out.println("Response : " +response);
return model;
}
Now here I want to get the response but I am not sure what will be the datatype of reponse.
The System.out.println prints this error:
ModelAndView: reference to view with name '[object Object]'; model is null
Please Help me out as I am new to the Spring MVC.
Thank You in advance.

Related

Request method 'POST' not supported in Springboot MVC

Below are my GET and POST methods..
When I run the application, I get this error: Request method 'POST' not supported.
GET Method:
#RequestMapping(value = "userProfiles/{userId}/setup/Tool", method = RequestMethod.GET)
public String ToolSetup(Model model, #PathVariable int userId, #RequestParam(value = "update", defaultValue = "false") boolean update) {
model.addAttribute("formInput", new Resource());
model.addAttribute("userId", userId);
if (update) {
model.addAttribute("update", "update");
} else model.addAttribute("update", "");
return "Tool";
}
Below is my POST method:
#RequestMapping(value = "/userProfiles/{userId}/setup/Tool", method = RequestMethod.POST)
#ResponseBody
public void makeVideo(#PathVariable Long userId, #ModelAttribute("formInput") Resource formInput,
Authentication authentication,
ModelMap modelMap,
#RequestParam("uploadingFiles") MultipartFile[] uploadingFiles,
#RequestParam("track_value") int trackNumber,
HttpServletResponse response) throws IOException, URISyntaxException, InterruptedException, FrameGrabber.Exception,FrameRecorder.Exception {
UserProfile userProfile = userProfileRepository.findOne(userId);
ArrayList<String> photos = new ArrayList<>();
String audioPath= audioPath1;
for(MultipartFile file : uploadingFiles){
photos.add(file.getName());
}
formInput.setUploadingFiles(photos);
modelMap.put("formInput", formInput);
//some processing with images and the audio
response.sendRedirect("/userProfiles/" + userId + "/Tool/Processing"); //redirect to notif. page, then redirect to logged in home
}
HTML:
<form th:action="#{${#httpServletRequest.requestURI + '?update=true'}}" th:object="${formInput}" method="POST" enctype="multipart/form-data">
I know there are other posts related to this once, and I have tried all the recommended solutions from them but nothing seems to work..
Any help is appreciated!

Spring - Stop redirection on error

I have a page to manage users and I would like to stay on the page if any error occurs when clicking save.
The only cases I found online where to do with validation.
Also my page requires the userId to be posted so I don't think returning the name of the original page in the controller would work. Also I would loose the changes made in the page.
What I am trying to achieve is stay in the same page, showing a message to the user.
Here is my controller:
#RequestMapping(method = RequestMethod.POST)
public String editUser(#RequestParam("userId") String userId, final Map<String, Object> model) {
User user = spiService.getUser(userId);
model.put("user", user);
configureRoles(model, user);
return "edituser";
}
#RequestMapping(path = "/updateUser", method = RequestMethod.POST)
public String updateUser(#RequestParam("userJson") String userRoles, #RequestParam("userId") String userId, final Map<String, Object> model) throws IOException {
User user = spiService.getUser(userId);
try {
addRoles(JsonUtil.getField(userRoles, "addedRoles"), user.getRoles(), userId);
removeRoles(JsonUtil.getField(userRoles, "removedRoles"), user.getRoles(), userId);
} catch (Exception ex) {
// What now?
}
return "users";
}
Instead of redirecting you can use Ajax calls in your controller. For that you have to create one AjaxPojoClass for exampleAjaxResponseBody as your convenience.
For example
$.ajax({
type : "POST",
contentType : "application/json",
url : "/yourUrl",
data : JSON.stringify(data),
dataType : 'json',
success : function(data) {
window.location.replace("/successUrl")
},
error : function(e) {
display(e);
},
});
AjaxController
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/yourUrl")
public AjaxResponseBody getSearchResultViaAjax(#RequestBody SearchCriteria search) {
AjaxResponseBody result = new AjaxResponseBody();
//logic
return result;
}
}
you can use ajax to submit your request.

Change url path in Spring MVC by #RequestMapping

Currently path is showing
http://localhost:8081/UserLogin/login
But i want this as
http://localhost:8081/UserLogin/index
or
http://localhost:8081/UserLogin/
My controller class is
#RequestMapping(value = "/login" ,method = RequestMethod.POST)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
//return "hi this is a test";
String userName = request.getParameter("data[Admin][user_name]");
String userPass=request.getParameter("data[Admin][password]");
int userId=userDAO.getUser(userName, userPass);
if(userId!=0){
String message = "welcome!!!";
return new ModelAndView("result", "message", message);
}
else{
String message = "fail";
return new ModelAndView("index", "message",message);
}
}
Want to change in else condition when not match.
Thanks in advance. :)
I would return a redirect to render the view under the new URL:
request.addAttribute("message",message) // better use a Model
return "redirect:/[SERVLET_MAPPING]/index";
It take some time to understand what you want: - I guess you want to alter the URL that is returned from the Server after login.
But this does not work this way, because the URL is requested from the browser and the server can not change them. Instead the server can respond an "HTTP 303 Redirect" (instead of the view). This cause the Browser to load the URL given with the Redirect.
#RequestMapping(value = "/login" ,method = RequestMethod.POST)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
//return "hi this is a test";
String userName = request.getParameter("data[Admin][user_name]");
String userPass=request.getParameter("data[Admin][password]");
int userId=userDAO.getUser(userName, userPass);
if(userId!=0){
return new ModelAndView(new RedirectView("/result", true)); // "/result" this is/become an URL!
}
else {
return new ModelAndView(new RedirectView("/index", true)); // "/index" this is/become an URL!
}
}
#RequestMapping(value = "/index" ,method = RequestMethod.GET)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
String message = "fail";
return new ModelAndView("index", "message",message); //"index" the the name of an jsp (or other template)!!
}
#RequestMapping(value = "/result" ,method = RequestMethod.GET)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
String message = "welcome!!!";
return new ModelAndView("result", "message", message); //"result" the the name of an jsp (or other template)!!
}
#See http://en.wikipedia.org/wiki/URL_redirection

Sending data from AngularJS factory to a Spring Controller

I have a spring controller which should recieve data in the sessionAttribute from an angularjs factory.
My Spring Controller is :
#Controller
#SessionAttributes("dataObject")
public class ScreenDesignerController extends BaseController {
/**
* Injected screen designer service class.
*/
#Autowired
private ScreenDesigner screendiService;
#RequestMapping(value = "FormBuilder", method = RequestMethod.POST)
public final String knowDetails(
#ModelAttribute("globalUser") User globalUser,
#RequestParam(value = "dataObject") String myJsonStr,
BindingResult result, RedirectAttributes redirectAttributes,
final Model model
) throws Exception {
try {
logger.info("this is json array: " + myJsonStr);
screendiService.addData(myJsonStr);
} catch (Exception e) {
logger.info("inside customiseForm POST catch");
}
return "ScreenDesigner/FormBuilder";
}
Angular factory:
indApp.factory('sendJsonDataService', function ($http, $rootScope, superCache) {
var sendjsondataservice = {
sendJsonData: function () {
//dataObject = JSON.stringify(superCache.get('super-cache'));
alert(JSON.stringify(dataObject));
res = $http.post('FormBuilder', dataObject);
res.success(function(data, status, headers, config) {
alert("Your Screen has been saved successfully into the database!");
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
}
};
return sendjsondataservice;
});
Whenever I am invoking the factory via angularjs controller to recieve "dataObject", it says "bad request 400", Though the "dataObject" has valid json data in it.
I want my spring controller to receive this data.
Please help, stuck for two days now :(
Thanks in advance!!
If you're sending JSON as a POST payload, you should be using #RequestBody instead of #RequestParam.
Thy this i modified your controller :
#Controller
#SessionAttributes("dataObject")
public class ScreenDesignerController extends BaseController {
/**
* Injected screen designer service class.
*/
#Autowired
private ScreenDesigner screendiService;
#RequestMapping(value = "FormBuilder", method = RequestMethod.POST)
public final String knowDetails(#RequestBody String myJsonStr,#ModelAttribute("globalUser") User globalUser,
BindingResult result, RedirectAttributes redirectAttributes,
final Model model
) throws Exception {
try {
logger.info("this is json array: " + myJsonStr);
screendiService.addData(myJsonStr);
} catch (Exception e) {
logger.info("inside customiseForm POST catch");
}
return "ScreenDesigner/FormBuilder";
}
Another this be sure to send json data from AngularJS factory. For instance :
headers: {
'Content-type': 'application/json'
}

How to map both json and form submit requests to the same controller?

If I send data like this :
$.ajax({
url: $fooForm.action,
data: $fooForm.serialize(),
type: 'POST',
success: function(data) { console.log(data); }
});
This can be received by a controller that has the following signature :
public ResponseEntity<Map<String, Object>> checkEligibility( Person person )
At another instance, I am sending the request like this :
$.ajax({
url: $fooForm.action,
data: $fooForm.serialize(),
dataType: 'json',
type: 'POST',
success: function(data) { console.log(data); }
});
This can be received by a controller with the following signature :
public ResponseEntity<Map<String, Object>> checkEligibility(#RequestBody Person person )
I want to write a single method that can accept both the json POST as well as the simple POST, and give me the same Person object
If the x-www-form-urlencoded POST is part of a browser-based HTML forms application, DO NOT DO THIS
You should be using the POST-Redirect-GET pattern with HTML forms. Otherwise, when a user hits refresh in their browser they get that annoying popup.
And this is fundamentally at odds with patterns of a REST API
You can use polymorphism to make this feature work.
So, you need to create a BaseController.
#Controller
public class BaseController
public ResponseEntity<Map<String, Object>> checkEligibility(final Person person) {
Map<String, Object> body = new HashMap<String, Object>();
body.put("person", person);
ResponseEntity<Map<String, Object>> entity = new ResponseEntity<Map<String,Object>>(body, HttpStatus.OK);
// write some logic here ...
return entity;
}
Next, you need to create RestController
#Controller
#RequestMapping(value = "/eligibility")
public class RestController extends BaseController {
#Override
#ResponseBody
#RequestMapping(method = RequestMethod.POST, headers = { "content-type=application/json" })
public ResponseEntity<Map<String, Object>> checkEligibility(final #RequestBody Person person) {
return super.checkEligibility(person);
}
}
After that, create Standart controller
#Controller
#RequestMapping(value = "/eligibility")
public class StandartController extends BaseController {
#Override
#ResponseBody
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> checkEligibility(final #ModelAttribute Person person) {
return super.checkEligibility(person);
}
}
Now this should work.

Resources