spring 4 not validate - spring

#RequestMapping(value="/app/home/refernece",method=RequestMethod.POST)
public String processReference(HttpServletRequest request, #ModelAttribute("refernceForm") #Validated #Valid ReferenceForm referenceForm, BindingResult bindingResult, Model model){
if(!bindingResult.hasErrors()){
boolean emailExists = customerservice.customerWithEmailExists(referenceForm.getRefernceMail());
if (!emailExists) {
bindingResult.rejectValue("refernceMail", "registrationform.valid.email.exists");
}
}
System.out.print(referenceForm.getRefernceName());
if (bindingResult.hasErrors()) {
//logger.log(Level.DEBUG, "Form Errors.");
//model.addAttribute("BindingResult",bindingResult);
//model.addAttribute("refernceForm", new ReferenceForm());
return "view/app/refernce";
}
return "redirect:/home/systemschein";
}
This my handler method.
I add 2 validator to this controller but its not validating?

Your ModelAttribute name may have a typo - it says 'refernceForm' when maybe it should say 'referenceForm'. If you post the code for the ReferenceForm class we can also check what it should be validating.

Related

Is it possible to pass Flash parameters from GET method to POST method in the same controller?

I have two controllers. The first send some data using flash parameters to another one
#PostMapping
public String processOrder(Model model, NewOrder order, RedirectAttributes attributes) {
model.addAttribute(order);
attributes.addFlashAttribute("order", order);
return ("redirect:/sendorder");
}
And it's received by:
#GetMapping
public String showSendOrderForm(Model model, #ModelAttribute("order") NewOrder order) {
OrderDetails details = new OrderDetails();
details.setOrder(order);
model.addAttribute("details", details );
model.addAttribute("companies", companyProxy.getCompanies());
return "orderDetails";
}
Can I use value send in Flash attributes in POST method somehow? Or maybe could I use something else instead of Flash attributes?
POST method:
#PostMapping
public String processTaco(Model model, OrderDetails details, SessionStatus sessionStatus) {
detailsProxy.addOrderDetails(details);
sessionStatus.setComplete();
return "redirect:/";
}

Spring 4 MVC: passing multiple #modelattributes trough controllers

I'm looking for a solution to pass 2 #ModelAttributes from my GET controller to my POST controller without using Session. I'm using Spring Boot and Thymeleaf.
My view is bound only to one of those but the second controller need to use them both. The problem is that the second controller reinitialize the #ModelAttribute not used in view.
The controller:
//in this controller I've initialized the first #modelAttribute
#RequestMapping(value="/simulations", method=RequestMethod.POST)
public String checkSimulationsManagerForm(#Valid #ModelAttribute("sim_manager") Simulations_manager sim_manager, BindingResult bindingResult, final RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "set_simulations-manager_form";
}
redirectAttributes.addFlashAttribute("sim_manager", sim_manager);
return "redirect:/simulations2";
}
//GET
#RequestMapping(value="/simulations2", method=RequestMethod.GET)
public String showSimulationsClassForm(#ModelAttribute("sim_class") Simulations_class sim_class, #ModelAttribute("sim_manager") Simulations_manager sim_manager){
//Do some stuff
return "set_simulations-class_form";
}
//POST that reinitilize the firse #ModelAttribute
#RequestMapping(value="/simulations2", method=RequestMethod.POST)
public String checkSimulationsClassForm( #Valid #ModelAttribute("sim_class") Simulations_class sim_class, BindingResult bindingResult,#ModelAttribute("sim_manager") Simulations_manager manager,final RedirectAttributes redirectAttributes) {
//ERROR IS HERE, manager attributes are all null, even if they were not.
}
The view:
<form action="simulations2" th:action="#{/simulations2}" th:object="${sim_class}" method="post">
…
</form>

Spring MVC command object and redirect attributes

I have a simple scenario:
User submits form, if there are binding errors I redisplay it, otherwise I set a flash attribute and redirect to the home page. I can't get the command object and RedirectAttributes to play together though, I can either validate the command object or use redirect attributes but not both. This gives me a 400 Bad Request
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPassword(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
RedirectAttributes redirectAttributes,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return SET_PASSWORD_VIEW_PATH;
...
redirectAttributes.addFlashAttribute("flashMessage", "Password changed");
return "redirect:/";
}
This works but without the flash attrbute:
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPasswordPost(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return SET_PASSWORD_VIEW_PATH;
...
return "redirect:/";
}
What is the recommended pattern for handling this sort of thing?
Your method signature is wrong, as explained here the BindingResult must directly follow the model attribute.
org.springframework.validation.Errors / org.springframework.validation.BindingResult validation results for a preceding command or form object (the immediately preceding method argument).
So moving the RedirectAttributes after the BindingResult will make it work.
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPassword(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
BindingResult bindingResult,
RedirectAttributes redirectAttributes) { ... }

spring: hook between data binding and validation

I have a Roo generated application and use validation, spring security with a custom PermissionEvaluator and the generated web controllers. My entity has a field like this:
#NotNull
private Date creationDate;
This field is set automatically inside the controller's create method when saving the entity and is not included in the form (render="false").
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
#PreAuthorize("hasPermission(#myEntity, 'create')")
public String create(#Valid MyEntity myEntity,
BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest) {
// ... check binding result
myEntity.setCreationDate(new Date());
myEntity.persist();
// ...
}
The problem is, that validation always fails because it runs before the field is set. The PermissionEvaluator (called by #PreAuthorize) is also missing the value. How can I place my code somewhere between data binding and validation so that the entity is complete right from the beginning?
To solve the problem of #PreAutorize move the persistence logic to a #Service bean and call it from the controller. This way security check will be after validation. Roo can help you on it with service command.
Second, you can use validation groups to make different validation on for the same entity. This and this are two howto post.
An example:
#RequestMapping("/myEntity")
public MyEntityController {
#Autowired
MyEntityService myEntityService;
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(#Validated({Account.ValidationStepOne.class}) MyEntity myEntity,
BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest) {
// ... check binding result
myEntityService.save(myEntity);
//...
}
}
#Service
public MyEntityService {
#PreAuthorize("hasPermission(#myEntity, 'create')")
public save(MyEntity myEntity) {
//...
myEntity.setCreationDate(new Date());
myEntity.persist();
}
}
Good luck!

Spring Framework 3 and session attributes

I have form object that I set to request in GET request handler in my Spring controller. First time user enters to page, a new form object should be made and set to request. If user sends form, then form object is populated from request and now form object has all user givern attributes. Then form is validated and if validation is ok, then form is saved to database. If form is not validated, I want to save form object to session and then redirect to GET request handling page. When request is redirected to GET handler, then it should check if session contains form object.
I have figured out that there is #SessionAttributes("form") annotation in Spring, but for some reason following doesnt work, because at first time, session attribute form is null and it gives error:
org.springframework.web.HttpSessionRequiredException: Session attribute 'form' required - not found in session
Here is my controller:
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
FormUtils.populate(form, request);
if(form.validate())
{
formDao.save();
}
else
{
return viewForm(form);
}
return null;
}
It throws Exception if controller called first time even though added #SessionAttributes({"form"}) to class. So add following populateForm method will fix this.
#SessionAttributes({"form"})
#Controller
public class MyController {
#ModelAttribute("form")
public Form populateForm() {
return new Form(); // populates form for the first time if its null
}
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
The job of #SessionAttribute is to bind an existing model object to the session. If it doesn't yet exist, you need to define it. It's unnecessarily confusing, in my opinion, but try something like this:
#SessionAttributes({"form"})
#Controller
public class MyController {
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm(#ModelAttribute("form") Form form) {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
Note that the #SessionAttributes is declared on the class, rather than the method. You can put wherever you like, really, but I think it makes more sense on the class.
The documentation on this could be much clearer, in my opinion.
if there is no defined session object so I think it's gonna be like this:
#SessionAttributes({"form"})
#Controller
public class MyController {
#RequestMapping(value="form", method=RequestMethod.GET)
public ModelAndView viewForm() {
ModelAndView mav = new ModelAndView("form");
if(form == null) form = new Form();
mav.addObject("form", form);
return mav;
}
#RequestMapping(value="form", method=RequestMethod.POST)
#Transactional(readOnly = true)
public ModelAndView saveForm(#ModelAttribute("form") Form form) {
// ..etc etc
}
}
#Controller
#SessionAttributes("goal")
public class GoalController {
#RequestMapping(value = "/addGoal", method = RequestMethod.GET)
public String addGoal(Model model) {
model.addAttribute("goal", new Goal(11));
return "addGoal";
}
#RequestMapping(value = "/addGoal", method = RequestMethod.POST)
public String addGoalMinutes(#ModelAttribute("goal") Goal goal) {
System.out.println("goal minutes " + goal.getMinutes());
return "addMinutes";
}
}
On page addGoal.jsp user enters any amount and submits page. Posted amount is stored in HTTP Session because of
#ModelAttribute("goal") Goal goal
and
#SessionAttributes("goal")
Without #ModelAttribute("goal") amount entered by user on addGoal page would be lost
I'm struggling with this as well. I read this post and it made some things clearer:
Set session variable spring mvc 3
As far as I understood it this basically says:
that Spring puts the objects specified by #SessionAttributes into the session only for the duration between the first GET request and the POST request that comes after it. After that the object is removed from the session. I tried it in a small application and it approved the statement.
So if you want to have objects that last longer throughout multiple GET and POST requests you will have to add them manually to the HttpSession, as usual.

Resources