Add query string with action in Struts 2
I am adding parameters with an action, but I am getting an exception on my Struts 2 page.
PWC6212: equal symbol expected
Below is my action with added parameter code to be sent.
action="MyAction.action?id=<%=request.getParameter("id")%>&name=<%=request.getParameter("name")%>&age=<%=request.getParameter("age")%>&num=<%=request.getParameter("num")%>"
Is the above syntax problem? If not, how can we set the parameters as a query string with an action?
source to share
You shouldn't use Scriptlets ( <%= %>
)
And if action
is a Struts tag attribute (for example <s:form>
), you cannot use scripts, you must use OGNL
.
Please refer to this question: Struts 2 s: select dynamic id tag for more details
source to share
The attribute action
is assumed to be used with a tag <form
. Then the construction
<form name="MyAction.action" action="upload?id=<%=request.getParameter("id")%>&name=<%=request.getParameter("name")%>&age=<%=request.getParameter("age")%>&num=<%=request.getParameter("num")%>" method="POST">
should work with the current context. But in your case, this error message ( Exception Name: org.apache.jasper.JasperException: equal symbol expected
occurs when using a tag <s:form
. So you cannot use this url in an action attribute. This attribute must contain the name of a simple action that will be used to find your action.
"How do we set parameters as a request?"
We actually do this with a tag <s:param
. For example, when using hyperlinks
<s:a action="MyAction">
<s:param name="id" value="%{id}"/>
<s:param name="name" value="%{name}"/>
</s:a>
But this construct doesn't work with a tag <s:form
unless you use the special syntax as described in this , and you definitely want to get those parameters if you do in action
String quesyString = request.getQueryString();
and this line must not be empty.
However, this utility is rarely used unless you have a reason to get parameters this way, then alternatively you can always use fields <s:hidden
to hold parameter values. for example
<s:form action="MyAction" method="POST">
<s:hidden name="id" value="%{id}"/>
<s:hidden name="name" value="%{name}"/>
</s:form>
These values are passed as parameters and the action attributes are initialized after the handler runs params
. You can also get these parameters directly from the request as
Map<String, String[]> params = (Map<String, String[]>)request.getParameterMap();
However, a more convenient way to do this in your action is to implement ParameterAware
.
source to share
Just like @AndreaLigios mentioned you should be using ELSUT Struts2, check out the Document here.
If you are using <s:url/>
, see the doc , please, for more information.
Your code should look something like this:
<s:url value="MyAction.action">
<s:param name="id" value="%{#parameters.id}" />
<s:param name="name" value="%{#parameters.name}" />
<s:param name="age" value="%{#parameters.age}" />
<s:param name="num" value="%{#parameters.num}" />
</s:url>
source to share