Servlet FORM based login

Servlet API supports FORM login by specification.

Activating it is pretty easy and few lines in your web.xml is enough.

To use a form, just configure a login-config using the provided FORM auth method:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""

You can customize the login and error page. The login page is the form (html) you want to use and the error page is the one you see when you try to log in without being able to get authenticated. Path is relative to the webapp.

The form needs to contain the following parameters (or inputs):

– j_username
– j_password

Their meaning are without any surprise the login and password of the user.

The action of the form is on path `/j_security_check`.

A stupid but working login template can be:

    <form method="post" action="j_security_check">
      Login: <input type="text" name="j_username" />
      Password: <input type="password" name="j_password" />
      <input type="submit" value="Login"/>

The error page is totally up to you.

Once all this is set up, we can add some constraints on our web application. Let say we want a user to have master role to access /protected/* urls.

To do so, we add a standard security constraint and a role:


And that’s it! Easy right?

Side note: in Tomcat it can also be interesting to set the landingPage in the FormAuthenticator.
This will allow you to show a custom page instead of having error responses if a user tries to access to the login page directly.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s