Spring MVC - can I "bind" ModelMap to view? - java

I have this piece of code:
#RequestMapping(value="login/authUser", method=RequestMethod.POST)
public String authUser(#RequestParam("login") String login,
#RequestParam("password") String password, ModelMap model){
(...)
if (password.equals(user.getPassword())){
ModelMap modelMap = new ModelMap();
modelMap.put("loggedUser", user.getName() + " " + user.getSurname());
return "home";
}
else{
model.put("info", "Bad data!");
return "index";
}
For bad password, everything is correct - it returns a with information "bad data", but if password is correct I can't get an info about logged user (but it redirects correctly). Because ModelMap model is ,,bind" to index.jsp it works when it redirects to index jsp, but is there a way to "bind" new ModelMap to view called home.jsp with simply way or I have to use ModelAndView?
Thank you in advance.
#SOLVED: It was my stupidity, I simple do not initialize name and surname in variable user, and because of it there were a "" instead name and surname which I want to see in home.jsp. Now, with user with name and surname set it works great :)

Related

Model Attribute After posting DTO Object on Spring Boot

In my Spring boot project, Passed a DTO object to my view which is then posted after submission. eg. How do I access the "randomKey" after the form is posted?
#GetMapping("/{userId}/edit/feature/")
public String showEditFeature(#PathVariable("userId") Long userId, UserDto userDto,
Model model)
{
User user = userService.get(userId);
model.addAttribute("user", user);
model.addAttribute("randomKEy", "AnyObject");
return "user/edit/profile";
}
Then My post function.
#PostMapping("profile_update")
public String watchFeatureUpdate(#Valid UserProfileDto UserProfileDto,
BindingResult result,
RedirectAttributes redirectAttributes, Model model)
{
Long userId = userService.updateUserProfile(userProfileDto);
redirectAttributes.addFlashAttribute("message", "Profile features updated
successfully!");
redirectAttributes.addFlashAttribute("alertClass", "alert-success");
return "redirect:/user/view/" + userId + "/profile";
}
You need to include in your HTML page "user/edit/profile" as a hidden input every object property value so they are sent back when the form is submitted.
<input type="hidden" name="randomKEy" value="${randomKEy}">
Note that HTML content is still manipulable by the user even not being visible in the rendered web page.

Transfer variable value to html using ModelMap

this method opens a page when clicking on a link in which I want the value of the message attribute, I did not add the servlet and jsp, how can I display it? my html is empty
#GetMapping("/activate/{code}")
public String activate(ModelMap model, #PathVariable String code) {
boolean isActivated = userService.activateUser(code);
if (isActivated) {
model.addAttribute("message", "User Successfully activated");
System.out.println("Successfully");
} else System.out.println("Activation code not found");
model.addAttribute("message", "Activation code not found");
return "verificationPage";
}
try to use RedirectAttributes
#GetMapping("/activate/{code}")
public String activate(ModelMap model, #PathVariable String code, RedirectAttributes redirAttrs) {
redirAttrs.addFlashAttribute("message", "Here is your message");
}

How to save the passed parameter in the URL for use in different controller in Spring?

In one page I have an DataTable.
when clicked upon a user, the user Id gets passed as url value
usersInfo?getid=1
I have a controller like this :
#RequestMapping(value = "users/userInfo", method = RequestMethod.GET, params = {"getId"})
#ResponseBody
public ModelAndView getClientStat(#RequestParam(value="getId", required = true) String getId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
long clientId=0;
clientId=Long.parseLong(getId);
Client client=clientService.getClientById(clientId);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userName", user.getName() + " " + user.getLastName());
modelAndView.addObject("userId", user.getId());
modelAndView.addObject("id", client.getName()+ " " + client.getLastName());
modelAndView.setViewName("users/userInfo");
return modelAndView;
}
And then I use the passed object id which has the name and last name to show the user name.
Then on the opened users/userInfo page I have a button which sends to another page to fill out a form.
The question is : How do I save the fields of these form to the database, but for the client whose id I have in the controller.
How do I pass this value on ?
Or is there a better more logical way to do this ?
I am fairly new at using Spring , so I apologize in advance if something is unclear but I would really appreciate some guidance.
Thank you
You can use #PathVariable with addAttribute
#RequestMapping(value = "users/edit/{userId}", method = RequestMethod.GET)
public ModelAndView getClientStat(#PathVariable(value="userId", required = true) String userId) {
//Use the userId to find user information and pass
modelAndView.addAttribute("id", userId)
modelAndView.setViewName("users/edit");
return modelAndView;
}
In your view, you can add the userId as hidden field
<input type="hidden" name="userId" value={userId} />, depend on the view you're using thymeleaf OR jsp

POST method returns wrong URL when BindingResult has errors

I have this POST method which only validates a form and returns a confirmation view if the form is validated and I want to send back to the register screen if any field is wrong. In this case if the BindingResult object has errors, the system send the user back to the form screen but the URL shown is "/registerConfirmation" which should only be in case the form has no errors.
#RequestMapping(value="/registerConfirmation", method = RequestMethod.POST)
public ModelAndView confirmRegister(#Valid #ModelAttribute("form") RegistrationForm form, BindingResult result){
logger.info("Sending registration data");
ModelAndView modelAndView = new ModelAndView();
if(result.hasErrors()){
modelAndView.setViewName("register");
modelAndView.addObject("form", form);
return modelAndView;
}
//more code here
return modelAndView;
}
I dont know what I'm missing as I have seen methods like this in many other posts. Any help??
Many thanks!!!
One way to solve your issue is to use redirect:
#RequestMapping(value="/registerConfirmation", method = RequestMethod.POST)
public String confirmRegister(#Valid #ModelAttribute("form") RegistrationForm form, BindingResult result, RedirectAttributes attr){
logger.info("Sending registration data");
if(result.hasErrors()){
attr.addFlashAttribute("org.springframework.validation.BindingResult.form", result);
attr.addFlashAttribute("form", form);
return "redirect:/register";
}
//more code here
return "redirect:/registerConfirmation";
}
and in your register GET method you should check:
#RequestMapping(value="/register", method = RequestMethod.GET)
public String showRegister(Model model) {
....
if (!model.containsAttribute("form")) {
model.addAttribute("form", new RegistrationForm());
}
.....
}
you can read more in this article
Also don't forget to create GET method with registerConfirmation value.

Spring Flash Attributes not working

I have the following controller code redirecting to a page:
#RequestMapping(value="/site_form", method = RequestMethod.POST)
public String welcomeForm(ModelMap model, #Valid #ModelAttribute Site s,
BindingResult br, RedirectAttributes ra) {
if (br.hasErrors()) {
model.addAttribute("errors", br.getAllErrors());
return "hello";
}
model.addAttribute("message", "Entry Log");
model.addAttribute("site", s);
ra.addAttribute("flash", "Site saved successfully");
return "redirect:/app/admin/site_form";
I'm trying to access ${flash} in the controller, but cannot.
Also, I though this was supposed to go in the session, but my URL after the redirect URL hit as a get attribute.
I'm stuck.
It has to be ra.addFlashAttribute("flash", "...").

Categories

Resources