Struts 2 “bean” tag is used to instantiate a class in the JSP page. In this tutorials, you will use the “bean” tag to instantiate a class named “HelloBean“, set its property via “param” element and print out the value.

1. Simple Bean

A simple class, later use bean tag to instantiate it.

HelloBean.java

package com.mkyong.common.action;
 
public class HelloBean{
 
	private String msg;
 
	public String getMsg() {
		return msg;
	}
 
	public void setMsg(String msg) {
		this.msg = msg;
	}
 
}

2. Action

An Action class to forward the request.

BeanTagAction.java

package com.mkyong.common.action;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class BeanTagAction extends ActionSupport{
 
	public String execute() {
		return SUCCESS;
	}
 
}

2. Bean tag example

A JSP page to show the use of “bean” tag to instantiate the “HelloBean“.

In “bean” tag, you can assign a name to the bean via a “var” attribute, later you can access the bean via #var_bean_name , or its property value via #var_bean_name.property.

bean.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>
 
<body>
<h1>Struts 2 Bean tag example</h1>
 
<s:bean name="com.mkyong.common.action.HelloBean" var="hello">
  <s:param name="msg">Hello Bean Tag</s:param>
</s:bean>
 
The HelloBean's msg property value : <s:property value="#hello.msg"/>
 
</body>
</html>

3. struts.xml

Link it ~

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
 
	<action name="beanTagAction" 
	    class="com.mkyong.common.action.BeanTagAction" >
	    <result name="success">pages/bean.jsp</result>
	</action>
 
    </package>
</struts>

4. Demo

http://localhost:8080/Struts2Example/beanTagAction.action

Output

Struts 2 bean tag example

Reference

  1. Struts 2 Bean tag documentation
Note : You can find more similar articles at - Struts 2.x Tutorials