Here I’m demonstrating a Login flow consisting of the following:
1. showing a Login form to the user
2. submitting the form to the server via Angular and Ajax
3. validating it on the server and returning a JSON response
4. redirecting to a welcome page on successful submission

This is a flow I encountered recently using Spring MVC and, while not a single-page application was effective at displaying whether the login was successful without a page refresh.

Note the following:
• data-ng-app will make Angular aware of this form and data-ng-controller will link to a specific class we are providing. We called it LoginController and it will be in login.js referenced at the end of the template.
• role=”form” is to tell Bootstrap about our form so that it can style it correctly.
• data-ng-submit=”…” tells Angular about our form and it will handle its submission.
• form-group, form-control, alert, alert-danger – all of the classes used are ones used by Bootstrap.
• data-ng-show means that AngularJS will show / hide an element based on the expression provided, in this case it is ‘does a non-empty feedback field exist?’ The feedback field belongs to the $scope variable as documented here: https://docs.angularjs.org/guide/scope

We need to update our conf/routes file, adding /login for the processing action and a /welcome to show to authenticated users:

And our JavaScript file, public/javascripts/login.js which contains the postLoginForm function we bind to our form with data-ng-submit. This function performs the HTTP POST and redirects on successful submission or shows an error message.

It does a lot. I’ll explain each action:
• index() – shows the login form using the index.scala.html template and empties out the user’s session if it exists (so we can demonstrate handling users not logged in)
• login() – handles the form submission. Turns the JSON input into a LoginRequest object using a Reader (see the Play documentation) and checks the simple authenticate() method. It returns a JSON object with the key ‘valid’ and the value returned by authenticate(). If a valid user it stores the username in the session, to be used by the welcome action.
• welcome() – if the username is present in the session it shows a welcome page, otherwise it redirects back to the login screen.

Let’s run it:

If we type in values other than those hard-coded to work ( root/god and sysadmin/password1) and submit it (pressing Enter or clicking Login) then we should see our error message:

But if we provide a valid login we get a welcome page:

What happens if we go back to the login page and refresh it? We show the page again but removing our session. If we now try to get to /welcome we are sent back to the login page.