Struts 2 URL tag example
The Struts 2 url tag can be useful if you need to use a url in many places and don’t want to repeat the code again and again. You need to specify an id attribute for your url and you can also use actions instead of simple links in this tag. Adding parameters to the url can be done by using the param tag.
** UPDATE: Struts 2 Complete tutorial now available here.
Url tag example
Here are some examples to show the use of Struts 2 “url” tag.
1. Create an image url.
<img src="<s:url value="/image/android.jpg"/>" />
Output (assume the root context name is “URLtag”)
<img src="/URLtag/image/android.jpg" />
2. Create a “Yahoo” text and link it to http://www.yahoo.com.
<a href="<s:url value="http://www.yahoo.com"/> >Yahoo</a>
Output
<a href="http://www.yahoo.com">Yahoo</a>
Note :
When you define the URL value with starting of “www” or “http”, Struts 2 will not add extra root context, instead it will display as it is.
3. Adding parameters to the url using param tag
<s:url id="urlValue" action="urlTag.action"> <s:param name="age">25</s:param> </s:url> <s:a href="%{urlValue}">urlTag With Parameter</s:a>
On clicking the above <s:a> tag, the following url is generated in the browser
http://localhost:8089/URLtag/urlTag.action?age=25
Complete jsp page
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>URL Tag</title> </head> <body> <h2>Struts 2 URL tag</h2> <ol> <li><img src="<s:url value="/image/struts.jpg"/>" /></li> <li><a href="<s:url value="http://www.yahoo.com" />">Yahoo</a></li> <li> <s:url id="urlValue" action="urlTag.action"> <s:param name="age">25</s:param> </s:url> <s:a href="%{urlValue}">urlTag With Parameter</s:a> </li> </ol> </body> </html>
Demo
http://localhost:8080/URLtag/urlTag.action
Struts 2 Debug Tag Example
In Struts 2, the “debug” tag is used to output the content of the “Value Stack” and Stack Context details in the web page.
** UPDATE: Struts 2 Complete tutorial now available here.
1. Jsp debug tag example
A JSP page to output the system’s “Value Stack” and “Stack Context” using debug tag.
debug.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>Debug tag</title> </head> <body> <h3>Debug tag</h3> <s:debug /> </body> </html>
2. Action class
A Action class, with a field named actionProperty” property, show in value stack in jsp.
DebugTag.java
package com.simplecode.action; import com.opensymphony.xwork2.Action; public class DebugTag implements Action { public String actionProperty; public String getActionProperty() { return actionProperty; } public void setActionProperty(String actionProperty) { this.actionProperty = actionProperty; } }
3. struts.xml
<?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" extends="struts-default"> <action name="debugTagAction" class="com.simplecode.action.DebugTag"> <result name="success">/debug.jsp</result> </action> </package> </struts>
4. Demo
http://localhost:8089/Debug/debugTagAction.action
Output
|
Read More
There Is No Action Mapped For Namespace / And Action Name “YourActionName”
Problem
Many Struts 2 developers have claimed that they had configured the action class properly but a page not found error occurs when we try to access the action class and will get the following error message in the browser(If the developer mode is enabled).
** UPDATE: Struts 2 Complete tutorial now available here.
Struts has detected an unhandled exception: Messages: There is no Action mapped for namespace / and action name "yourActionName". Stacktraces There is no Action mapped for namespace / and action name "yourActionName". - [unknown location] com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:178) org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) ...
Solution
The above error message is saying that the action class is not available, it means you are did something wrong in your action class configuration, it may be a namespace error, just double check the name.
Here’s a working action class configuration in struts.xml
file, may use for your reference.
<?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="myAction" class="com.Simplecode.action.myAction" > <result name="success">jsp/my.jsp</result> </action> </package> </struts>
Assume the project root context is “Struts2“, so, you can access the above action via this URL –
http://localhost:8089/Struts2/myAction.action
And it will be better if you learn about Struts2 Namespace configuration to avoid this issue
Struts 2 + Spring Integration Example
In this following example we shall see how to integrate Spring and Struts 2 using the struts2-spring-plugin. We integrate Spring with Struts2 to utilize the Spring’s Dependency Injection feature.
First add the org.springframework.web.context.ContextLoaderListener to the web.xml file.
** UPDATE: Spring Complete tutorial now available here.
** UPDATE: Struts 2 Complete tutorial now available here.
File : web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter </filter-class> </filter> <listener> <listener-class>org.springframework.web.context. ContextLoaderListener</listener-class> </listener> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
By default the applicationContext.xml file will be used for doing the Spring bean configuration.
File : applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="helloWorldClass" class="com.simplecode.HelloWorld" > <property name="msg" value="Struts 2 + Spring Integration Example!" /> </bean> </beans>
As you can see we have registered the HelloWorld class and injected the “Hello World!” message to the message attribute using the setter injection method.
All the Struts 2 action configuration goes in the struts.xml file.
File : struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="struts-default"> <action name="helloWorld" class="helloWorldClass"> <result name="SUCCESS">/success.jsp</result> </action> </package> </struts>
The only change here is instead of referring the com.simplecode.HelloWorld class directly, we relate it using the bean name given in the spring bean configuration file.
The HelloWorld class is shown below. In the execute() method we simply return “SUCCESS” and themessage attribute is set using setter injection.
File : HelloWorld.java
package com.simplecode; public class HelloWorld { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String execute() { return "SUCCESS"; } }
In the index.jsp page we forward the request to the helloWorld action.
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=helloWorld.action">
After invoking the execute() method the user will be directed to the success.jsp page. In this page we dispaly the message value.
You need to have the following jar files in the WEB-INF/lib directory.
commons-fileupload-1.2.1 commons-io-1.3.2 commons-logging-1.1 freemarker-2.3.13 junit-3.8.1 ognl-2.6.11 struts2-convention-plugin-2.1.6 struts2-core-2.1.6 xwork-2.1.2 struts2-spring-plugin-2.1.6 antlr-runtime-3.0 org.springframework.asm-3.0.0.M3 org.springframework.beans-3.0.0.M3 org.springframework.context-3.0.0.M3 org.springframework.core-3.0.0.M3 org.springframework.expression-3.0.0.M3 org.springframework.web-3.0.0.M3 org.springframework.web.servlet-3.0.0.M3
Read More
Struts 2 + Log4j integration example
In this tutorial we will learn about integrate Log4j with Struts 2 framework.
|
Log4j Appender
Create a text file named “log4j.properties“, put it at the root of the project classpath. The log4j.properties or appender file is the Log4j configuration file, it defines how the Log4j logging mechanism work.
** UPDATE: Struts 2 Complete tutorial now available here.
In this example, it will log all the logging detail and outputs it to an external file “C:\\loggerfile.txt“.
log4j.properties
# Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=C:\\loggerfile.txt log4j.appender.file.MaxFileSize=10MB log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Root logger option log4j.rootLogger=warn, file, stdout
Action Class
To use Log4j in Struts 2 framework, you can get the Log4j logger via Logger.getLogger() and log it directly.
package com.simplecode.action; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; public class LoggerAction extends ActionSupport { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(LoggerAction.class); public String execute() throws Exception { logger.warn("Warning ......."); logger.error("Error ......."); return SUCCESS; } }
Demo
Now, all the logging details will be logged into the file, named “C:\\loggerfile.txt“. See sample :
23:37:38,166 ERROR LoggerAction:15 – Error …….
|
Reference
Read More
Struts 2 <s:textfield> example
In Struts 2 , you can use the <s:textfield> to create a HTML input textbox. For example, you can declare the s:textfield with a key attribute or label and name attribute.
<s:textfield key="userName" /> //or <s:textfield label="Username" name="userName" />
In Struts 2, the “name” will map to the JavaBean property automatically. In this case, on form submit, the textbox value with name=“username” will call the corresponding Action’s setUsername(String xx) to set the value
** UPDATE: Struts 2 Complete tutorial now available here.
Struts 2 <s:textfield> example
Quick guide to create a textbox input field in Struts 2.
1. Properties file
Two properties files to store the message.
project.properties
project.username = Username project.submit = Submit
LoginAction.properties
username.required = Username Cannot be blank
2. Action
A simple Action class with a validation to make sure the username is not empty, otherwise return an error message.
LoginAction.java
package com.simplecode.action; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private static final long serialVersionUID = 6677091252031583948L; // Need to Initiize a morden driven object private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String execute() { return SUCCESS; } public void validate() { if (userName.equals("")) { addFieldError("userName", getText("username.required")); } } }
3. View page
Result page to use Struts 2 s:textfield to create a HTML textbox input field.
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="/struts-tags" prefix="s"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login</title> </head> <body> <h3>Struts 2 < S:textfield > Textbox Examplee</h3> <s:form action="welcome"> <s:textfield name="userName" key="project.username" /> <s:submit key="project.submit" name="submit" /> </s:form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Welcome Page</title> </head> <body> <h3>Struts 2 < S:textfield > Textbox Example</h3> <h4> Welcome <s:property value="userName" /> </h4> </body> </html>
4. struts.xml
<?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.custom.i18n.resources" value="project" /> <package name="default" extends="struts-default" namespace="/jsp"> <action name="Login"> <result>/jsp/login.jsp</result> </action> <action name="welcome" class="com.simplecode.action.LoginAction"> <result name="success">/jsp/success.jsp</result> <result name="input">/jsp/login.jsp</result> </action> </package> </struts>
5. Demo
http://localhost:8089/Struts2_textfield/
Reference
1. Struts 2 textfield documentation