Last Updated on 31 July 2019   |   Print Email
In this Struts tutorial, I will share with you how to read values of parameters configured in the Struts configuration file from within a Struts action class.In Struts, the staticParams interceptor enables us configuring parameters for an action class in struts.xml configuration file, for example:
As we can see, each <param> element specifies key and value for a parameter - very straightforward. In the action class, there are two ways for reading these parameters: using JavaBean-style methods and using a Map object named params.
1. Reading parameters using JavaBean-style methods:
In this method, we have to declare properties whose names equal to key names of the parameters in struts.xml file. Suppose we specify parameters for an action as follows:
package net.codejava.struts;
import com.opensymphony.xwork2.ActionSupport;
public class MethodParamAction extends ActionSupport {
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String execute() {
System.out.println("location = " + location);
return SUCCESS;
}
}
And here is the result JSP page:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result</title>
</head>
<body>
<center>
<h3>Upload location: ${location}</h3>
</center>
</body>
</html>
Output when running: http://localhost:8080/Struts2Parameters/testMethodParam
This method is suitable when we have just a few parameters for the action.
2. Reading parameters using a Map object
In this method, we have to do the following:
Declare a property named params of type Map<String, String> - this map will hold all the parameters passed to the action class from the struts.xml file.
Make the action class implementing the com.opensymphony.xwork2.config.entities.Parameterizable interface and implement its methods: setParams(), getParams() and addParam().
Let’s see an example. Suppose we have an action declared in struts.xml file as follows:
Output when running: http://localhost:8080/Struts2Parameters/testMapParamThis method looks a bit more complex then the JavaBean-style one, however it would be useful in case we have many parameters, as reading parameters from a map is easier than having many getter and setter methods.NOTE: The staticParams interceptor is already included in the Strut’s default stack, so if our package extends from the struts-default package, there is no need to include this interceptor explicitly.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments