NOTE: This information applies to an older version of Tapestry. For current information on Tapestry's Spring support, see http://tapestry.apache.org//integrating-with-spring-framework.html. |
- AcegiSpringJava5 - First part of the tutorial
Now that I know how to protect my Tapestry pages I would like to print the name of a registered user. That is not difficult...
To avoid duplicated code I created a base class for Home.java
and Secured.java
:
src/main/java/de/zedlitz/tapestry/acegi/UserPage.java
package de.zedlitz.tapestry.acegi; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContextHolder; public abstract class UserPage extends org.apache.tapestry.html.BasePage { public String getUserName() { // getContext() will never return null so we do not have to check that. Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if( auth != null ) { return auth.getName(); } return ""; } }
The two existing pages extend this base class:
src/main/java/de/zedlitz/tapestry/acegi/Home.java
package de.zedlitz.tapestry.acegi; public abstract class Home extends UserPage { }
src/main/java/de/zedlitz/tapestry/acegi/Secured.java
package de.zedlitz.tapestry.acegi; @org.acegisecurity.annotation.Secured("ROLE_USER") public abstract class Secured extends UserPage {}
The last step is to display the username on the html pages:
src/main/webapp/Home.html
<html> <head> <title>tapestry-acegi: normal page</title> </head> <body> <h1>tapestry-acegi: normal page</h1> <p>You are logged in as <em><span jwcid="@Insert" value="ognl:userName">Timmi Tester</span></em>.</p> <p><a href="Secured.html" jwcid="@PageLink" page="Secured">secured page</a></p> </body> </html>
src/main/webapp/Home.html
<html> <head> <title>tapestry-acegi: secured page</title> </head> <body> <h1>tapestry-acegi: secured page</h1> <p>You are logged in as <em><span jwcid="@Insert" value="ognl:userName">Timmi Tester</span></em>.</p> <p><a href="Home.html" jwcid="@PageLink" page="Home">back to homepage</a></p> </body> </html>