Struts 2 Annotation Example

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.

  1. 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.
  2. 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


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;

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;

	public String execute(){
		return "success";

2. JSP File


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
		<s:property value="msg" /><br>

3. Struts 2 Annotation Demo

If you access the application using URL http://localhost:8080/Struts2App/helloannotation, you would see the following output.

Struts 2 Annotation Example

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!