Struts 2 bean tag example
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“.
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








[...] tag.action tag example Struts 2 action tag is used to call action class directly from a JSP page.bean tag example Struts 2 bean tag is used to instantiate a class in the JSP page.date tag example Struts 2 date tag [...]