Struts 2 @Action Annotation Example

By Arvind Rai, May 13, 2014
@Action annotation in struts 2 defines URL pattern for an Action class. Each method of an action class can be fetched by a separate URL. This facility provides the power to hide package name in URL. It is also possible that more than one URL pattern can point a single point of execution. In this page we will see different cases how to use @Action annotation in struts 2.

Case 1: @Action at Method Level

@Result(name="success",location="/user/user.jsp")
public class UserAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	@Action("/url/one")	
	public String one() {
	    return SUCCESS;
	}
} 
In this case @Action is used at method level. We have provided a URL pattern. On the accessing of the URL pattern /url/one , method one will be called. For instance URL will look like

http://localhost:8080/Struts2Demo-1/url/one

Case 2 : @Action at Class Level

@Namespace("/user")
@Action("/login")
@ResultPath(value="/")
@Result(name="success",location="login.jsp")
public class LoginAction extends ActionSupport{
	public String execute() {
	    return SUCCESS;
	}
} 
In the second case, @Action is being used at class level with @Namespace annotation. @ResultPath will provide the result path for JSPs. URL pattern will be /user/login and sample URL may as below.

http://localhost:8080/Struts2Demo-1/user/login

Case 3 : @Actions with more than one @Action

@Result(name="success",location="/user/user.jsp")
public class UserAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	@Actions({
	   @Action("/abc/url"),
	   @Action("/xyz/url")
	})
	public String three() {
	    return SUCCESS;
	}
} 
In this case 3, we are using @Actions, that will contain more than one @Action annotation. If we provide two URL pattern for a single method, then that method will be fetched by two URL pattern one is /abc/url and second is /xyz/url . URL may look like as below.

http://localhost:8080/Struts2Demo-1/abc/url
http://localhost:8080/Struts2Demo-1/xyz/url
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us