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", "...").
Related
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");
}
I have gone through url mapping topics but I couldn't find a way to solve my problem despite I'm sure more than one has had this kind of setback. Maybe it is quite simple.
I have a login process, when the login form is submited (user and password)
localhost:8080/library/login the controller leads to the main page of the user, All I would like to do is to set the username in the URL like localhost:8080/library/{username}/mainPage
It seems it has nothing to do with PathVariable or RequestParam as I tried many ways to go through this however 400 error is all I got.
#RequestMapping(value="/mainPage", method = RequestMethod.POST)
public ModelAndView showMainPage(#Valid #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, ModelAndView modelAndView, BindingResult result, final RedirectAttributes attributes){
logger.info("Showing login page.");
modelAndView.addObject(loginUserForm);
attributes.addFlashAttribute("loginUserForm", loginUserForm);
if(result.hasErrors()){
modelAndView.setViewName("login");
return modelAndView;
}
modelAndView.setViewName("mainPage");
return new ModelAndView("redirect:/mainPage");
}
And this leads to another controller class
#RequestMapping(value = "/{userName}/mainPage", method = RequestMethod.GET)
public #ResponseBody ModelAndView showMyArea(ModelAndView model, #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, #PathVariable("email")String email){
logger.debug("Showing mainPage");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("mainPage");
return modelAndView;
}
What should I change or what do I miss? I guess the value, but I do not why
I came up with this wrongly:
#RequestMapping(value="/{userName}/mainPage", method = RequestMethod.POST)
public ModelAndView showMainPage(#Valid #ModelAttribute("loginUserForm") LoginUserForm loginUserForm, ModelAndView modelAndView, BindingResult result, #PathVariable("userName") String userName){
Thanks a ton!
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.
I'm new to Spring. I'm trying to learn it by doing instead of reading. So I found some stuff which is confusing. But it works. I want to know why and how?
#Controller
#RequestMapping("/ok")
public class MyController {
#RequestMapping(value = "/ok", method = RequestMethod.GET)
public ModelAndView findAllAccounts() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", "Listing all accounts!");
return mav;
}
#RequestMapping(value="/ok/{accountId}", method = RequestMethod.GET)
public ModelAndView findAccount(#PathVariable int accountId, Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", String.format("Showing account %d", accountId));
return mav;
}
}
For above code I found that.
working Get request url : http://localhost:8080/ok/
working Get request url : http://localhost:8080/ok/ok/888
But I was expecting url : http://localhost:8080/ok/ok/ should also work. But it doesn't work. Why? If http://localhost:8080/ok/ok/888 works why http://localhost:8080/ok/ok/ doesn't work?
Also when I deploy it in tomcat. It only works if named ROOT.war. If I change to XYZ.war, it doesn't work. Why?
The http://localhost:8080/ok/ok/ does not work as it treats your last ok as your accountId and it fails conversion to an integer. The best documenation is the javadoc
Your question about tomcat - I believe it should be fine with another name, only then you would have to access it as http://localhost:8008/XYZ/
I'm new in Spring and also in JSP. I'm working in the project and I needed to create a page where application will be redirected in case of specific exceptions.
I have service's method which throws one of exceptions. This method is called in one of our page controller with #RequestMapping annotation. So to redirect to specific error page, I created two methods with #ExceptionHanlder which handle this exceptions in this controller. How it looks:
#ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
ModelAndView modelAndView = new ModelAndView("redirect:/error");
modelAndView.addObject("exceptionMsg", ex.getMessage());
return modelAndView;
}
But there wasn't enough. I also need to create ErrorPageController:
#Controller
#RequestMapping("/error")
public class ErrorPageController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView displayErrorPage() {
return new ModelAndView("error");
}
}
And now works displaying error page. But my problem is, that I can't display error message in JSP...
I have:
<h3>Error page: "${exceptionMsg}"</h3>
But I don't see a message ;/ Instead of it, I see message in URL:
localhost/error?exceptionMsg=Cannot+change+participation+status+if+the+event+is+cancelled+or+it+has+ended.
And it's wrong because in URL I want to have only an "localhost/error" and nothing more. This message I want to display in JSP.
To fix both of your issues (show the message, and have the proper url) you should in original code change you exception handler method to e.g.
#ExceptionHandler(IllegalStateException.class)
public RedirectView handleIllegalStateException(IllegalStateException ex, HttpServletRequest request) {
RedirectView rw = new RedirectView("/error");
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null) {
outputFlashMap.put("exceptionMsg", ex.getMessage());
}
return rw;
}
Why? If you want your attributes to persist through redirect, you need to add them to flash scope. The code above uses the FlashMap, from the docs
A FlashMap is saved before the redirect (typically in the session) and
is made available after the redirect and removed immediately.
If it were to be a normal controller method, you could have simply added RedirectAttributes as an argument, but on #ExceptionHandler methods, the arguments of RedirectAttributes are not resolved, so you need to add the HttpServletRequest and use the RedirectView.
You have to change ModelAndView to:
#ExceptionHandler(IllegalStateException.class)
public ModelAndView handleIllegalStateException (IllegalStateException ex) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exceptionMsg", ex.getMessage());
return modelAndView;
}
And have this part in error.jsp:
<h3>Error page: "${exceptionMsg}"</h3>