Struts 2 supports annotations out of the box in its latest release without even a single line of configuration changes. You are not needed to create struts.xml file and there is no need to mention the scanning path anywhere like we mention in the spring framework. You have to add one extra JAR file struts2-convention-plugin.jar which has the API to scan the classes and find the annotations.
- Struts 2 by default scan the action classes and convert the action class name to action mapping. For example if your action class name is “HelloAction”, the default action mapping would be “hello”. The first letter of the first word will be small.
- If you add @Action annotation before the execute method, the action mapping will be override the default name.
Lets look at the example code.
1. Action Class
package javabeat.net.struts2; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.ResultPath; @Namespace("/") @ResultPath(value="/") @Result(name="success",location="Annotation.jsp") public class HelloAction{ private String msg = "JavaBeat - Struts 2 Annotation Hello World!!"; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Action(value="/helloannotation") public String execute(){ return "success"; } }
2. JSP File
Annotation.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <body> <h4> <s:property value="msg" /><br> </h4> </body> </html>
3. Struts 2 Annotation Demo
If you access the application using URL http://localhost:8080/Struts2App/helloannotation, you would see the following output.