0

My index page contains a visible login form and a hidden registration form (the two toggle visibility). When a user registers and has some validation errors, they return to the index page. However, by default, they will see the login page. How could the controller tell the index page to run some javascript code (just to hide login and display registration)?

@RequestMapping(value="/register", method=RequestMethod.POST)
    public String addNewUser(@Valid @ModelAttribute("registerForm") RegisterForm registerForm,
               BindingResult result, Model model, HttpServletRequest request){

        if(result.hasErrors()){
            model.addAttribute("error", true);
            System.out.println("ERROR");
            return "index";
        }       
        return "index";
    }
3
  • Why do you want to toggle visibility by js? You could simply use your view's templating engine for that. Commented Mar 19, 2015 at 9:22
  • I'm working on a test application for to get a job, this is the first time I am working with any kind of java web development (coming from asp.net) so I don't really know what is going on Commented Mar 19, 2015 at 9:33
  • Ok, in the index page, what kind of view technology are you using (e.g. jsp, velocity, thymeleaf, ...) Commented Mar 19, 2015 at 10:51

2 Answers 2

1

If you simply want to show one part or the other of your template then there is no need to use javascript. You are already passing an appropriate flag over to your view (your error attribute).

In your view you can use an jsp choose statement (sort of an xmlified switch) to select the part to show:

<c:choose>
  <c:when test="${!error}">
    <!-- Login code here (your 'no error' case) -->
  </c:when>   
  <c:otherwise>
    <!-- Registration code here (your 'error' case) -->
  </c:otherwise>
</c:choose>

Or (cleaner in my opinion) you could create two views and select the right one in your controller:

@RequestMapping(value="/register", method=RequestMethod.POST)
public String addNewUser(
        @Valid @ModelAttribute("registerForm") RegisterForm registerForm,
        BindingResult result, 
        Model model){

    if(result.hasErrors()) {
        return "registration";
    }       
    return "index";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use error attribute which you are adding in model. You can check its value in javascript and according to that you can change visibility.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.