How to do validation in struts2 when calling action from jquery ajax? - struts2

i am calling struts2 action from jquery ajax on success it returns string and on error it should be dispatched to same page and should display errors. i have used following code check it..
$(document).ready(function(){
$('#getActionRs').click(function(){
alert("call action");
$.ajax({
type:"POST",
url: "returnToAjax",
data: "firstinput=" +$('#firstinput').val()+"&secondinput=" +$('#secondinput').val(),
success: function(msg){
alert("success:"+msg);
}
});
});
});
i have used above code to call my struts action. onclick of button this thing get called
i have specified my action element in config file as follows
<action name="returnToAjax" class="example.returnToAjax">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
<result name="input" type="dispatcher">/Login.jsp</result>
</action>
when it returns success it return string correctly, i have done some validation of this action by validation xml but when it returns error it just shows me Login.jsp file code it does not dispatches it to Login.jsp

you are doing things fundamentally wrong.Ajax is something which means doing a backed process without refreshing page and letting user stay on the same page.
Your approach is something what not in the right scope of Ajax principal.So even when you have validation failure in you action class control is coming back to same handler in your Jquery code and since you have specified the Login.jsp as the view template the steam result is picking the whole jsp and returning back its content.
If you want to go with same approach, just return action name from the Action if validation failed and den redirect user to input page using JavaScript form submit function.

You can follow this procedure :
Form submit
Validation error (checked through validation.xml)
pass error.jsp as input result where error.jsp contains a word, suppose say ERRORPAGE
you'll get error.jsp via the ajax response.
check out the response content if it starts from ERRORPAGE, do a javascript redirect to login.jsp
Here's a code snippet of the example which does struts2 jquery grid validation through ajax.
afterSubmit:function(response,postdata){
return isError(response.responseText);
}
<script type="text/javascript">
function isError(text){
if(text.indexOf('ERRORPAGE')>=0){
return [false,text]; //do redirection here something like
//window.location="/login.action";
}
return [true,''];
}
</script>

Related

struts2 jquery plugin wraps html to returned id

I am using struts2-jquery plugin in my project. I am trying to submit a form using <sj:submit> tag like this:
<sj:submit id="caseSubmit"
targets="result"
formIds="mainForm"
onCompleteTopics="caseSubmitted"
button="true"/>
The struts.xml mapping for this action is as follows:
<action name="submitAddCase" class="com.xxx.action.AddCaseAction">
<result type="json">
<param name="root">caseId</param>
</result>
</action>
The onComPleteTopics code
$.subscribe('caseSubmitted', function(event,data) {
var indexPre = event.originalEvent.request.responseText.indexOf("<pre>")+5;
var indexPreEnd = event.originalEvent.request.responseText.indexOf("</pre>");
var id = event.originalEvent.request.responseText.substring(indexPre,indexPreEnd);
$("#case_id").val(id);
});
What I want is to use the caseId returned to load some other stuff on the same page. But,
event.originalEvent.request.responseText returns caseId wrapped in pre tag like this
<pre>154000</pre>
This is how it is returned in firefox. In chrome it is returned in another form. How can I get th caseId's original value without wrapped html.
Right now I am using javascript's substring method to get the value it is not working in chrome because of a different returned format
Replace
$("#case_id").val(id);
with
$("#case_id").val($(id).html());

Unable to display Struts2 fieldError

I have created the index.jsp which send action request
<meta http-equiv="REFRESH" content="0;url=./radioButton.action">
After completing this the request is forwarded to radio.jsp. In this one i am showing country, state list etc.. (so i am redirecting for this from index.jsp).
Now i am imposing validations to this form. i have created the .xml correctly for validation.When the validation fail it will be redirected to ./radioButton.action
<result name="input" type="redirectAction">radioButton</result>
I have created one interceptor which extends MethodFilterInterceptor, for this to keep the action errors in session scope which having the follow logic in after() method.
if (fieldErrors != null && fieldErrors.size() > 0)
{
Iterator it = fieldErrors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue().toString());
}
session.put(FIELD_ERRORS_KEY, fieldErrors);
}
public static final String FIELD_ERRORS_KEY = "RedirectMessageInterceptor_FieldErrors";
i have configured the interceptor in my .xml as below
<interceptors>
<interceptor name="redirectMessage" class="com.daya.message.RedirectMessageInterceptor" />
<interceptor-stack name="sessionStack">
<interceptor-ref name="redirectMessage" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptor-stack>
</interceptors>
I am getting the error message on my console befor putting into session scope. The output printed in console is
userName = [User Name is required to login]
password = [Password is required to login]
I am using the below tag to display the field error
<s:fielderror></s:fielderror>
But in the jsp after redirect (when validation failed) messages are not getting display.
Client side validation is working well. I disabled javascript for checking server side validation
As Struts providing a way handle this using MessageStoreInterceptor but i don't know why you are doing it manually.

Struts2 token interceptor always fails

Im trying to make it so that once i submit this form i cannot hit the back button, but with the current configuration I cannot even get the page/form to load. I can't seem to figure out why "invalid.token" is always being triggered thus redirecting me to index.jsp no matter what I have the token tag in my form like im supposed to. If i use the "excludeMethods" filter and exclude View then my page loads but I can hit the back button freely so it still does not work properly. I have tried moving the interceptor-ref above and below my noLoginStack but it dosen't make a difference. Based on my debugging my actual java class isn't even being hit, so its failing before then. What am I doing wrong?
My action declaration:
<action name="viewAppointmentLetter" class="edu.ucr.c3.rsummer.controller.instructor.ManageAppointmentLetters">
<interceptor-ref name="noLoginStack"/>
<interceptor-ref name="token" />
<result name="invalid.token">/index.jsp</result>
<result name="error" type="redirectAction">index.do</result>
<result name="input">/instructor/assigned_appts.jsp</result>
<result name="view">/instructor/assigned_appts.jsp</result>
<result type="redirectAction">index.do</result>
</action>
My assigned_appts.jsp:
<s:form action="saveAppointmentLetter" onsubmit="return verifySubmit();">
<s:token name="token" />
.....
</s:form>
If its any clue I always get this in my console
WARN org.apache.struts2.util.TokenHelper - Could not find token name in params.
In struts2 the order of interceptor is very important. you should follow this order.
<interceptor-ref name="token"/>
<interceptor-ref name="noLoginStack"/>
USe TokenSession interceptor.Had to handle result by result name="invalid.token" in struts.xml in specific action.
The page from which your action is generated at that page you have to write <s:token> tag in the header

struts2 submit form and show result in a new window

struts.xml
<action name="run" class="editTrackerAction" method="run">
<result name="input">/jsp/editTracker.jsp</result>
</action>
editTracker.jsp
<s:form method="post" name="saveTracker" id="saveTracker">
<input type="submit" name="executeEntityButtonName"
id="executeEntityOnTableSubmit" value="Run Entity" onclick="executeEntityOnTable();">
*.js has function
function executeEntityOnTable() {
document.saveTracker.action="run";
document.saveTracker.onsubmit=window.open('jsp/thankyou.jsp', 'executeEntityOnTable', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes');
document.saveTracker.submit();
}
In Page editTracker.jsp, I need to click submit button to show result variable defined in action in Page jsp/thankyou.jsp in a new window, editTracker.jsp page still stay there after submit form as struts.xml configured, but I can't get result in jsp/thankyou.jsp because it is pop up before saveTracker form submit.
You would likely be better off submitting the form via ajax then opening the new window.
If you submit a form with a normal request, the page will update; that's just the way it works. If you mean the form submission reloads the same page again, that's fine, but you still need to interact with the server before the new window opens.
try to use your Form something like below and use the following javascript function as well.
<form name="myForm" action="myaction.do" method="post"
onsubmit="return createTarget(this.target)" target="formtarget">
javascript function....
function createTarget(t){
var left = (screen.width/2)-(700/2);
var top = (screen.height/2)-(550/2);
window.open("", t,"status = 1,height = 550,width = 700,resizable = 1,left="+left+",top="+top);
return true;
}
I've done some formatting for the new window as well.
Regards.

Token Session Using tokens to prevent duplicate form submits?

I use Token Session to prevent duplicate form submits, but the first time I make a request to server, I always get error page
<action name="show" class="ClientAction">
<interceptor-ref name="tokenSession" />
<interceptor-ref name="basicStack" />
<result name="invalid.token">/WEB-INF/error.jsp</result>
result type="tiles" name="success">page.view</result>
</action>
"<s:token />" was added to may success page between <s:form> and </s:form>, but it doesn't run correctly.
plz help me to solve them, is there another way prevent duplicate form submits. I wait for suggestion, thank u very much. : )
It seems that you are not using proper interceptor name. If you want to use the session token, it is token-session.
try using token-session instead of tokenSession.
Hope that helps.
tag <s:token /> must be inserted into form which is double-submitted, not into success form. If token tag is missing, interceptor resolve the submitted request as invalid even if it's the first attempt.

Resources