You can use container managed authentication using deployment descriptors. This requires no extra code in your side expect of a simple login form with an input and password field which submits to the URL j_security_check
. Here's a basic example:
<form action="j_security_check" method="post">
<input type="text" name="j_username">
<input type="password" name="j_password">
<input type="submit">
</form>
Assuming that you've private pages in a folder named /private
and the above login page is located in /private/login.jsp
, then add the following entries to the webapp's web.xml
:
<security-constraint>
<web-resource-collection>
<web-resource-name>Private</web-resource-name>
<url-pattern>/private/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>friends</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Private</realm-name>
<form-login-config>
<form-login-page>/private/login.jsp</form-login-page>
<form-error-page>/private/error.jsp</form-error-page>
</form-login-config>
</login-config>
Then, in the servletcontainer which you're using you need to configure a so-called Realm for Private
. Since it's unclear which servletcontainer you're using, here's a Tomcat 6.0 targeted document: Realm Configuration HOW-TO. You can configure it to verify the username/password combo against a XML file or a database or even a custom location.
A completely different alternative is to homegrow a login mechanism with help of a Filter
which checks the presence of the logged-in user in the session scope. See this answer how to achieve this.