- Create a new web application called BestSongsStruts
- Add the required libraries (including the MySQL connector)
- Copy the models from a previous project in an appropriate package
- Add an action called Countries with a getter for a property called countries which returns a List of Country objects (use the DAO)
- Write the view (using Struts tags like s:iterator and s:a)
- Implement the Artists action and its corresponding view.
- Do the same for Songs
Artists is slightly different from Countries as it require a parameter (countryid) to work properly. It therefore needs to implement the ParameterAware interface (and, consequently, implement the setParameters method).
Adding a logging interceptor
In Struts, interceptors are used to modify the workflow of an application.
In all Struts applications, there exist a default stack of interceptors (notice ParametersInterceptor, ActionMappingParametersInteceptor and StaticParametersInterceptor).
Also notice that there is an interceptor called “logger” but it is not part of the default stack.
Let us add the logger before the default stack and let us observe what happens:
<action name="Songs" class="com.knowledge7.strutsbestsongs.actions.Songs"> <interceptor-ref name="logger" /> <interceptor-ref name="defaultStack" /> <result>/Songs.jsp</result> <result name="error">/Error.jsp</result> </action>
The order can also be changed.
Creating a custom logging interceptor
User-made interceptors are straightforward to write and they can then be added to any Action (e.g. Songs). We will now write a custom logging interceptor which will log everything in a table in the database:
- Create a new table with fields: logid (an autonumber), occurence (a timestamp) and reason a varchar(255).
- Create a LogDAO with one static method “void log(String reason)”
- Create a class called DatabaseLoggingInterceptor (which needs to implement the Interceptor interface and the implement method)
- Declare the interceptor in struts.xml as databaseLogger
- And, finally, replace logger (above) by databaseLogger