Multiple Actions in Struts2 using Annotations
Today, I learned how to use multiple actions in struts2 in class. Surely, the way the teacher taught was using XML. I tried to search for some documentation and tutorials, but they were very scattered. Here I try to write a tutorial about 2 ways to do multiple actions in one class.
References
Documentations
- Convention Plugin
- Action Configuration
- Constant Configuration
- default.properties
- Wildcard Mappings
- Wildcard Method Selection
Questions
- How do I use the Struts2.5 annotation @AllowedMethods (
test
) to implement a dynamic invocation method? - Struts2 - Annotation for having multiple action methods
- Where to put a properties file in Struts 2?
Example Project Download
This is my 5th lab assignment project. It uses git and has 2 branches. Each branch represents a different way to implement multiple actions.
Download Java-Ent-Lab5 project
Multiple Action Methods
The easiest way is using @Action
annotation for functions but not for entire class, so that these methods will be mapped to corresponding URIs.
|
|
Dynamic Method Invocation
Dynamic Method Invocation (DMI) is a feature of struts2 which can let you dynamically call methods in the Action class. It provides similar URI like GET parameters. ?
is replaced by !
. The example below will have pages /calc!add
, /calc!sub
and so on.
Enable DMI
This feature is disabled by default because of some security reason. If you really want to use it, you must do some configuration. Fortunately, I find a way so that I can still not to use struts.xml
. We can add a configuration file named struts.properties
, put it under src
directory and add the following line:
|
|
More configurations can be found in default.properties in above links.
Write the Code
Add @AllowedMethods
annotation for methods you want to be called. In struts 2.5, the DMI is in some strict mode, so it will be more secure. In older version, the @AllowedMethods
annotation below is not required and you can call any method in the Action class. But in newer version, it must be added so only these methods can be dynamically called. You can configure it to make it not need to do this.
|
|
Wildcard Method
Forget about this. Through my hours search, I can bet there is no way to use wildcard method only with annotations. I give up. Struts convention plugin sucks. The documentation is so incomplete. I miss my Red language.