Pass values from html to Action Class Struts - java

I am completely new to Struts and now I am facing some issues.
Here is my html code :-
<div id = "processingMode">
<div id = "appButton">
<input type="hidden" value="Cancel" name="flagValue" />
Cancel
</div>
</div>
And I want to retrieve hidden field values in the action class (or please let me know how to pass values from html to action class).
Can anyone help me to achieve this.

In order to pass the hidden parameter value using struts
you first need to add the struts library and import the struts tag library
Try this below code
<s:url action="actionclass">
<s:param name="id" value="parametervalue" />
</s:url>

Hi Krupa
To send hidden parameters from view page to action class, you have to use <s:hidden></s:hidden> struts tag. You can pass the parameters through the URL too. But that is not a best practice to do so when it comes to security.
so try to use struts tag to achieve desired task. find the following sample app code to get a better understanding :-
View Page
<s:form action="testAction">
<s:hidden name="EmpName" value="DummyName" />
<s:submit value="Submit" />
</s:form>
Action class
public class Employee extends ActionSupport {
private String EmpName;
// getters and setters
public String execute() {
System.out.println("Employee Name :- "+this.getEmpName());
return "success";
}
}
struts.xml
<action name="testAction" class="Employee">
<result name="success"><path of your view page></result>
</action>

Simply,
Cancel
In Action class, create a parameter q and its set and get methods

Related

Change action attribute of Form for different action methods in Struts2

I have created a from in JSP page name add.jsp to save data like this
<s:form action="AddDomain">
<s:push value="idp">
<s:textfield name="domainName" label="Domain Name" />
<s:textfield name="url" label="Domain URL" />
<s:textfield name="noOfLicense" label="License Purchased" />
<s:textfield name="licenseExpireDate" label="License Expire Date" title="YYYY-MM-DD like 2013-01-21" />
<s:textfield name="userActiveDuration" label="Active User Duration"
title="please mention in days" />
<s:textarea cols="30" rows="5" name="notes" label="Note"></s:textarea>
<s:submit value="Add"></s:submit>
</s:push>
</s:form>
Action Method that show this view is as
public String addDomainPage() {
return ActionSupport.SUCCESS;
}
I have created another page that list the all domains and provide a edit link to edit any domain. When Use click on edit URL this action is called
public String loadDomain() {
HttpServletRequest request = ServletActionContext.getRequest();
String url = request.getParameter("durl");
IDPBroker broker = new IDPBroker();
idp = broker.getDomainByURL(url);
return ActionSupport.SUCCESS;
}
On successful completion of action I show the add.jsp page. Struts populate the data in JSP page.
Now, issue is that I want to change the value of action attribute of form tag. I also want to change the value of submit button to 'Edit'. I have plan to create some private attribute(action,Label) in Action class and when an addDomainPage action is call I will change the value of these attribute with respect to add page. Similar for loadDomain action. Now I don't know how to do this means how to use these private attributes in view. Tell me is I am doing correctly and what to do next?
The same action class could be used to map different methods on submit buttons. Like
<s:submit value="Add" method="addDomainPage" />
<s:submit value="Load" method="loadDomain" />
The form action attribute should map to the action class execute method which will never call if you use submit buttons like that. The DMI which is enabled by default allows to call specified methods.
If you want to dynamically change attributes in the Struts tags you could use OGNL expressions in JSP instead of hardcoded values. For this purpose you should define properties in the action that define dynamic values before result is executed. For example
public String getAction(){
return "AddDomain";
}
<s:form action="%{action}">

Append a query string with action in Struts 2

I am appending the parameters with action but I am getting an exception of on my Struts 2 page.
PWC6212: equal symbol expected
Below is my action with appended parameters code which is to be submitted.
action="MyAction.action?id=<%=request.getParameter("id")%>&name=<%=request.getParameter("name")%>&age=<%=request.getParameter("age")%>&num=<%=request.getParameter("num")%>"
Is the above is the syntax problem? If not then how can we set the parameters as a query string with action?
You should not use Scriptlets (<%= %>)
And, if action is an attribute of a Struts tag (like <s:form>), you can't use scriptlets, you should use OGNL.
Please refer to this question: Struts 2 s:select tag dynamic id for more details
Assumed the action attribute is used with the <form tag. 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 given error message (Exception Name: org.apache.jasper.JasperException: equal symbol expected is occurred when <s:form tag is used. So, you cannot use this url in the action attribute. This attribute should contain the plain action name that would be used to find your action.
"How we set parameters as a querystring?"
Actually we do it with <s:param tag. 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 construction doesn't work with <s:form tag, unless you applying a special syntax as described in this answer and you definitely want to get these parameters if you do in the action
String quesyString = request.getQueryString();
and this string should not be empty.
However, this usecase is rarely applied, If you don't have a reason to get parameters in such way then as alternative you always can use <s:hidden fields to contain the values of the parameters. 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 a parameters and initialize the action attributes after params interceptor worked. You could also get this parameters directly from the request as
Map<String, String[]> params = (Map<String, String[]>)request.getParameterMap();
However, the more convenient way to do this in your action is to implement ParameterAware.
Just like #AndreaLigios mentioned, you should use Struts2 specified EL, check out the Document here.
If you are using <s:url/>, check out Document 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>

Struts2: values from action are not seen in jsp, but they are seen in the javascript code from jsp

In action I have a variable which has getter on it.
private String myActionVariable = "predefined....";
public String getMyActionVariable () {
return myActionVariable;
}
In jsp, I try to use my variable in this way:
<input type="button" class="styledButton"
onclick="javascript: doAjax('myActionName',false);"
value="${myActionVariable}"
But it is not shown. However, if I output this variable from the javascript code included within the same jsp file:
alert (${myActionVariable})
I will get the value of it....
Any idea please ? ...
You can use a Standard <input/> HTML Tag with an <s:property /> Struts2 Tag for the value, like this:
<input type="button" class="styledButton"
onclick="javascript:doAjax('myActionName',false);"
value="<s:property value="%{myActionVariable}"/>"/>
or a Struts2 Tag directly like this:
<s:submit type="button" cssClass="styledButton"
onclick="javascript: doAjax('myActionName',false);"
value="%{myActionVariable}" />
Note that with Struts2 Tag, class attribute becomes cssClass (and style becomes cssStyle), and that %{} is the right OGNL syntax, instead of ${} (that is JSTL syntax)
EDIT: when using Struts2, forget about JSTL, you won't need them anymore.
You should be using struts2 tag.
<input type="button" class="styledButton" onclick="javascript: doAjax('myActionName',false);" value="${myActionVariable}">
Instead of this, use
<s:submit type="button" cssClass="styledButton" onClick="javascript: doAjax('myActionName',false);" value= "myActionVariable" />

Avoiding duplication in parameter name

Inside a POST in a .jsp file, I'd like to do something like this:
<input type="text" name="...">
And inside the servlet I'd like to do:
request.getParameter(...)
Now where should and how should I declare "..." so that I can avoid duplication and reuse the same String.
Should this go in an interface like this:
public interface SO {
String POST_PARAM = "userinput";
}
Or in a property file? Or ...?
In any case, how do I then access this from the .jsp and from the .java file?
You can define constants like final String POST_PARAM = "userinput"; and then use them in markup: <input type="text" name="<%=POST_PARAM%>">.
Moving fields names to properties file does not sound as a beneficial unless you have reasons to do this.
To get parameter value from HTTP request caused by form submit say request.getParameter(POST_PARAM).
I hope this helps.
You might get the ... from a bean using EL. However, it is not usual for me.
You can use standard actions: jsp:useBean, jsp:setProperty and JavaBean technology:
Example:
A.jsp should call HTTP POST to B.jsp. B.jsp should automatically map all fields and redirect to your servlet.
// model.MyBean.java
class MyBean {
private int age;
// getters&setters
}
// A.jsp:
<form method="POST" action="B.jsp">
<input type="text" name="age">
</form>
// B.jsp
<jsp:useBean id="form" class="model.MyBean" scope="request" />
<jsp:setProperty name="form" property="*" />
<jsp:include page="/servletURL" />
Small description:
MyBean class will be created. This bean should has exactly the same
fields name like name in your form: for <input type="text"
name="age"> in bean should exists int age field and getter/setter.
jsp:setProperty with wildcard map all values from form A.jsp into your bean automatically.
if you want to call your servlet you can simple include appropriate url. Then in the servlet you will have access to request attribute "form" which will has MyBean with entered values.

Struts2 parameters between actions

I have to pass some parameter from an action to another action,for example to keep trace of an event.
What is the best way to do that?
I would not use session parameters. Thanks
Assuming you are serverside within one action and wishing to invoke another action with some parameters.
You can use the s:action tag to invoke another action, possibly with additional/other parameters than the original action:
<s:action name="myAction" ignoreContextParams="true" executeResult="true">
<s:param name="foo" value="bar"/>
</s:action>
You can also use a standard struts-xml result type with a parameter:
<result name="success" type="redirect" >
<param name="location">foo.jsp?foo=${bar}</param>
<param name="parse">true</param>
<param name="encode">true</param>
</result>
If you want a client side redirect you have to send an url back to the client with the proper parameters, and maybe use some javascript to go there.
<s:url action="myAction" >
<s:param name="foo" value="bar"/>
</s:url>
Use url tag in the struts core tags, sample is given below:
<s:url var="idurl" action="EditEnterprise">
<s:param name="enterpriseId">
<s:property value="enterpriseId" />
</s:param>
</s:url>
<td>
<s:url id="url" action="Logging">
<s:param name="m_userNameInAction"><s:property value="m_userNameInForm"/></s:param>
</s:url>
<s:a href="%{url}">English</s:a>
</td>
Actually you are going to pass your one action parameter value from one action to another action.
simply include bean variable with same name. which parameter you are going to receive on action(receiver action).
<action name="ForwardAction" class="...">
<result name="success" type="chain">ReceiverAction</result>
</action>
ForwardAction parameter will be forwarded to ReceiverAction. you can use it.
but include same bean name in both actions.
if you are going to receive userid in receiveaction means.,
This should be in both actions.,
private int userid;
public void setUserid(int id){
this.userid = userid;
}
public int getUserid(){
return userid;
}
actually, the scope and servletConfig interceptor can be utilized in struts2, to automatic pop the action context parameters, (request/session, etc)

Categories