How to put an attribute in the URL - java

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!

Related

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.

How Spring maps URL and where to read more about it

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/

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", "...").

Redirecting to an external URL in view file

I have the following string in a Spring MVC Controller action. I wanted the controller action to render a view page that takes this following string and then does the redirection.
String redirectUrl = "http://www.yahoo.com"
My controller action looks like the following:
#RequestMapping(method = RequestMethod.GET)
public String showForm(HttpServletRequest request, ModelMap model)
{
String redirectUrl = "http://www.yahoo.com";
model.addAttribute("redirectUrl", redirectUrl);
return "loginSuccess"; //this is my view JSP file
}
Is there a way in JSP view to do this redirect without using JSTL? I want a clean redirect and not send any query string parameters.
Thanks,
Maybe I misunderstood but if you want a redirect, you'll have to use a RedirectView.
String redirectUrl = "http://www.yahoo.com";
return "redirect:" + redirectUrl;
Or use a RedirectView instance
#RequestMapping(method = RequestMethod.GET)
public View showForm(HttpServletRequest request, ModelMap model)
{
String redirectUrl = "http://www.yahoo.com";
RedirectView view = new RedirectView(redirectUrl );
return view;
}

Java Spring Controller mapped properly, but server returns 302 instead of 200

I have following controller
#Controller
#RequestMapping("/adwords")
public class AdwordsController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(#ModelAttribute(Const.ADWORDS_COMMAND) AdwordsCommand adwordsCommand, BindingResult result)
throws HttpSessionRequiredException
{
this.checkSessionExpired();
ModelAndView mav = new ModelAndView("adwords/adwordsRequest");
if(adwordsCommand == null)
adwordsCommand = new AdwordsCommand();
User user = this.getUser();
adwordsCommand.setEmail(user.getEmail());
mav.addObject(Const.ADWORDS_COMMAND, adwordsCommand);
return mav;
}
}
That is mapped properly:
13:17:49,276 INFO RequestMappingHandlerMapping:185 - Mapped "{[/adwords],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView pl.ifirma.domeny.controller.adwords.AdwordsController.showForm(java.lang.String,org.springframework.validation.BindingResult) throws org.springframework.web.HttpSessionRequiredException
But when I type URL in browser I get 302 code and server redirects immediately to main page of application. Can anyone help? Why server does not return 200 or at least 404?
Adam
#Comments:
Such code acts exactly the same.
#Controller
#RequestMapping("/adwords")
public class AdwordsController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(#ModelAttribute(Const.ADWORDS_COMMAND) AdwordsCommand adwordsCommand, BindingResult result)
{
ModelAndView mav = new ModelAndView("adwords/adwordsRequest");
if(adwordsCommand == null)
adwordsCommand = new AdwordsCommand();
User user = this.getUser();
adwordsCommand.setEmail(user.getEmail());
mav.addObject(Const.ADWORDS_COMMAND, adwordsCommand);
return mav;
}
}
I wonder if this weird redirection could be caused by some spring configuration, but where to check it? And it is only place in project where problem occurs.
Solved. There was a hidden redirect in a view...

Categories

Resources