I'm having an issue with RedirectAttributes not saving (i think). This is my code:
#RequestMapping(path = "/job_offers", method = RequestMethod.POST)
public String createJobOffer(#Valid #ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm,
final BindingResult binding, RedirectAttributes attr) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.jobOfferForm", binding);
attr.addFlashAttribute("jobOfferForm", jobOfferForm);
return "redirect:/job_offers";
}
#RequestMapping(path = "/job_offers", method = RequestMethod.GET)
public ModelAndView jobOffers(#RequestParam(required = false, value = "skill_id") final Long skillId,
#ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm, final BindingResult binding) {
ModelAndView mav = new ModelAndView("job_offers/index");
mav.addAllObjects(getJobOffersMap(skillId));
mav.addObject("jobOfferForm", jobOfferForm);
return mav;
}
If I print my binding in the POST method it has the error in it, but when I call the GET method via the redirect the binding comes empty! and Spring doesnt show the error feedback on forms because of that
Any ideas?
Thanks!
Try this:
In your POST
attr.addFlashAttribute("bindignResultForJobOfferForm", binding);
And in GET
if (model.asMap().containsKey("bindignResultForJobOfferForm"))
{
model.addAttribute("errors",
model.asMap().get("bindignResultForJobOfferForm"));
}
Related
My Controller:
#RequestMapping(value = "/BankEdit", method = RequestMethod.GET) public ModelAndView BankEdit(HttpServletRequest request, HttpServletResponse response,BankBean bankBean)
{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank_edit");
long bName=Long.parseLong(request.getParameter("bName"));
System.out.println("Banme get "+request.getParameter("bName"));
return model;
}
am getting bName value in get method...I need the same value in post method..getting null value
POst Method:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST) public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean) throws Exception
{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name==="+request.getParameter("bName"));
long bName=Long.parseLong(request.getParameter("bName"));
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
In post method you try to retrieve parameter value bName. as like get method.
For GET request value will be send as parameter like
~/BankEdit?name1=value1&name2=value2
so request.getParameter("bName") you get that value.
For POST method value send via message body not send in parameter so you got null request.getParameter("bName")) cause you try to extract from parameter request url.
For received POST value you need declare parameter object on method argument and you got the value from message body.
If bName is part of your BankBean then you retrieve from your BankBean.bName object.
If not then declare in your method argument and get your value.
If bName is object of BankBean:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST)
public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean) throws Exception{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name=== "+bankBean.bName);
long bName=Long.parseLong(bankBean.bName);
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
In other way received string:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST)
public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean, String stringValue) throws Exception{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name=== "+stringValue);
long bName=Long.parseLong(stringValue);
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
I created registration Controller. Everything works fine, user is create in database but then end service program doesnt go to successRegister view. I dont know why. If I return like String successRegister everything is ok.
#RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView registerUserAccount(#RequestBody #Valid User accountDto,
BindingResult result, WebRequest request, Errors errors) {
if (result.hasErrors()) {
return new ModelAndView("successRegister", "User", accountDto);
}
User registered = userService.register(accountDto);
if (registered == null) {
result.rejectValue("email", "message.regError");
}
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent
(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("successRegister", "User", accountDto);
}
return new ModelAndView("successRegister");
}
Problem was with AJAX. I changed location after success and then ModelAndView was not return.
Your problem is with this
produces = MediaType.APPLICATION_JSON_VALUE
You says produces a JSON response but thats not true, you want to return a ModelAndView, so try to remove that attribute
I am using Spring to create and download Excel sheet I want to add some variable in model in requestiong mapping method so that I can use in other request maping method
#RequestMapping("/contentUploadDetails/{content_type}/{date}")
public ModelAndView contentUpload(
#PathVariable(value = "content_type") String content_type,
#PathVariable(value = "date") String date) {
List<CountAndValue> ls = contentCountImp
.getuploadedContentCountDatewise(content_type, date);
model.addObject("CountAndValue", ls);
return model;
}
As you can see in above
model.addObject("CountAndValue", ls);
I want to use this model value in my other requestMapping method
#RequestMapping(value = "/ContentUploadExport", method = RequestMethod.GET)
public ModelAndView getExcel() {
return new ModelAndView("CountAndValueExcel", "CountAndValue", CountAndValue);
}
how can I use CountAndValueExcel model object that is set by first method in second method with using session? Can I send model object(which contains list of class object) back from view to controller?
You can save an object into a session:
#RequestMapping("/contentUploadDetails/{content_type}/{date}")
public ModelAndView contentUpload(HttpServletRequest request,
#PathVariable(value = "content_type") String content_type,
#PathVariable(value = "date") String date) {
List<CountAndValue> ls = contentCountImp
.getuploadedContentCountDatewise(content_type, date);
model.addObject("CountAndValue", ls);
request.getSesion().setAttribute("CountAndValue", ls);
return model;
}
And then you retrieve it like this:
#RequestMapping(value = "/ContentUploadExport", method = RequestMethod.GET)
public ModelAndView getExcel(HttpServletRequest request) {
List<CountAndValue> CountAndValue = (List<CountAndValue>) request.getSession().getAttribute("CountAndValue");
return new ModelAndView("CountAndValueExcel", "CountAndValue", CountAndValue);
}
Wrote it from my head, not tested.
#RequestMapping("/insert")
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
if (emp != null)
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
Please tell me what to write in else part.I was trying for that but i am not getting
Make employeeId as a required param to serve the request by this RequestMapping then you don't need to write else part because Employee model will never be null in that case. It must have at least employeeId.
Note: Make it POST request.
Example:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
In other way you can validate the model and redirect to form page back with validation error messages.
Sample:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult result, ModelMap model) {
if (result.hasErrors()){
model.addAttribute("error", "Your custom error messages");
return "<<back to form page without redirection>>";
}else {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
}
Read more about Spring - Validation, Data Binding, and Type Conversion
Read a post on Spring MVC : How to perform validation ?
I have a working code.
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, ModelMap model
,#RequestBody Map reqbody)
throws Exception{
List result = testService.selectData(reqbody);
model.addAttribute("grid", result);
return "jsonview";
}
Now, I want to change above code to below style.
- adding data to response instead of model.
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, HttpServletResponse response
,#RequestBody Map reqbody)
throws Exception{
List result = testService.selectData(reqbody);
//model.addAttribute("grid", result);
//add result to response here...
return "jsonview";
}
Any suggestion??
Thanks in advance.
If you are working with session you can do the next step.
request.getSession().setAtribute("nameVarible","valor")
PD: Excuse me gramatic but I am trying to learn English
Not sure what is your intention is, but you can not set attribute to response object. You can only set attribute in request object. Since you already have a request parameter, change your code as follows:
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, #RequestBody Map reqbody)throws Exception{
List result = testService.selectData(reqbody);
request.setAttribute("grid", result);
return "jsonview";
}