Struts 2 Tip: Override Default Theme
Viral Patel on December 21, 2011
Recently I came up with a requirement in Struts 2 to display a particular form with some style and alignment. While creating the form the developer had used Struts 2’s taglib
/struts-tags to paint the user controls like textboxes and select boxes.
Now it turns of that Struts 2 parse these
s: tags and generate HTML tags like and . But Struts 2 not only generate these tags, but also generates enclosing tags to align them in a tabular format.
For example, the above Struts 2 code would generate HTML as following:
Note how Struts2 taglib generated enclosing TR tags around the controls. Lets see why this is so.
Themes in Struts 2
When you use a Struts 2 tag such as
s:select in your web page, the Struts 2 framework generates HTML that styles the appearance and controls the layout of the select control. The style and layout is determined by which Struts 2 theme is set for the tag. Struts 2 comes with three built-in themes:
simple, xhtml, and css_xhtml. If you don’t specify a theme, then Struts 2 will use the xhtml theme by default.
Thus in our case, Struts 2 automatically rendered the controls using default
xhtml theme. Specifying The Theme in Struts 2
The Struts 2 tags have a theme attribute you can use to specify which Struts 2 theme should be used when creating the HTML for that tag. The values for the theme attribute are simple, xhtml, css_xhtml, and ajax.
You can specify the theme on a per Struts 2 tag basis or you can use one of the following methods to specify what theme Struts 2 should use:
The theme attribute on the specific tag
The theme attribute on a tag’s surrounding form tag
The page-scoped attribute named “theme”
The request-scoped attribute named “theme”
The session-scoped attribute named “theme”
The application-scoped attribute named “theme”
property in struts.properties (defaults to xhtml)
Thus, you can specify what theme you want to use at any level. Tag level, enclosed tag lever, form level, page level or at application level.
I preferred specifying theme at the application level. To override the default scheme you can create (or update existing) struts.properties file in your project.
Create struts.properties file and add following line into it:
struts.ui.theme = css_xhtml
So if you want to take full control for your user interface and want to align all controls yourself, I would suggest you to use
css_xhtml theme instead of default xhtml.
The theme for above JSP code when changed into css_xhtml would generate following HTML code.
So all we have to do is to write CSS style for classes like wwgrp, wwlbl, wwctrl etc.
Hope this helps. Please comment if you have some specific requirement or suggestions.
Get our Articles via Email. Enter your email address.