Struts 2 Annotation Example

SHARE & COMMENT :

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

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.

Struts 2 Annotation Example

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better