I am trying to use struts 2 custom validation framework for validations, however that does not seem to be working. I am working on a very big project and the module I'm working on, I'm trying to implement this.
The problem struts 2 is not detecting my validation.xml. I tried creating a sample project and and used this validation.xml and it is working, but the same is not working in the project.
I am using model driven , I hope that should not be the problem.
The basic validations provided by action support are working fine but not my validations.
<interceptors>
<interceptor name="multiselect" class="org.apache.struts2.interceptor.MultiselectInterceptor" />
<interceptor name="browserCachingInterceptor" class="com.comviva.im.ui.interceptor.BrowserCachingInterceptor" />
<interceptor name="sessionHijackInterceptor" class="com.comviva.im.ui.interceptor.SessionHijackInterceptor" />
<interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />
<interceptor-stack name="defaultSecurityStack">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">DEBUG</param>
</interceptor-ref>
<interceptor-ref name="tokenSession">
<param name="excludeMethods">*</param>
</interceptor-ref>
<interceptor-ref name="sessionHijackInterceptor" />
<interceptor-ref name="browserCachingInterceptor" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="defaultSecurityStack"></default-interceptor-ref>
The interceptor declaration is also fine.
I tried for days but still cant figure out the problem. the only option remaining is debug.
Can anybody suggest me where should I be looking for. Where is the validation.xml file is loaded in ActionInvocation so that I can check if validation file was loaded properly or not.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="nodeId">
<field-validator type="required">
<message key="errors.required"/>
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">10000</param>
<message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
</field-validator>
</field>
<field name="selfISDNNumber">
<field-validator type="required">
<message key="errors.required"/>
</field-validator>
</field>
</validators>
This is extract from my action class:
public class NodeAction extends BaseAction implements ModelDriven<NodeConfigurationForm>, ParameterAware ,Preparable {
NodeConfigurationForm nodeConfigForm = new NodeConfigurationForm();
private static final Logger logger = Logger.getLogger(NodeAction.class);
private NodeConfigurationService configurationService;
private List<NodeConfiguration> nodeListTable = null;
Map<String , String[]> requestParams;
private int isFallBackChannelEnable;
private int smsSupportEnable;
private ServletContext servletContext;
MY NodeAction class extends BaseAction which extends ActionSupport which by default is validation aware.So NodeAction should work with custom validations also.
This is extract from my struts.xml regarding actions:
<action name="createGWNode" method="create" class="com.comviva.im.ui.ussdGateway.action.NodeAction">
<result name="success" type="tiles">createGWNode</result>
</action>
<action name="addGWNode" method="add" class="com.comviva.im.ui.ussdGateway.action.NodeAction">
<result name="success" type="chain">listGWNodes</result>
<result name="input" type="tiles">createGWNode</result>
<result name="error" type="tiles">createGWNode</result>
</action>
<action name="editGWNode" method="edit" class="com.comviva.im.ui.ussdGateway.action.NodeAction">
<result name="success" type="tiles">createGWNode</result>
</action>
<action name="updateGWNode" method="update" class="com.comviva.im.ui.ussdGateway.action.NodeAction">
<result name="success" type="redirect">listGWNodes</result>
<result name="input" type="tiles">createGWNode</result>
<result name="error" type="tiles">createGWNode</result>
</action>
And this is my jsp
<s:textfield name="nodeId" required="true" theme="simple" />reado
<s:radio name="status" list="#{'1':'Enable','0':'Disable'}" theme="simple"></s:radio>
<s:textfield name="gwInstanceName" theme="simple" />
<s:textarea name="description" cols="30" rows="2" theme="simple"/>
<s:textfield name="serverIp" theme="simple"/>
<s:textfield name="serverIp" theme="simple" readonly=< s:textfield name="loginUserId" theme="simple"/>
<s:password name="loginPassword" showPassword="true" theme="simple"/>
<s:textfield name=" selfISDNNumber " theme="simple "/>
<s:select name="logLevel " list="logLevelList " theme="simple "/>
Note: Please remove _ Underscore from selfISDN_num
Check proper jar files.
Xwork: Core 2.3.16.2 API
And check getter , setters
Note: Please check package name in struts.xml, does it extend struts-default?
<package name="Registration" namespace="/" extends="struts-default">
...
</package>
Finally found what was going wrong.
The DTD specified in validaiton.xml was wrong. The specifed DTD is for 2.3 onwards. I was using struts with a lower version.
I am now using
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
Related
This question already has an answer here:
Struts 2 Validation and Input fields repopulation
(1 answer)
Closed 6 years ago.
I was recently working with a login page with Struts2 framework and for validating the fields i used XML Validation feature provided by Struts2. And the fields are validated but the problem is that, if any of the field is not empty after validation the those field values are not repopulated in the corresponding field.The Example code is given.The version of the framework is 2.5.x.
Login.jsp
<s:form method="post" action="authenticate">
<div class="form-group">
<span class="input-icon">
<s:textfield name="strUserName" id="strUserName" cssClass="form-control" placeholder="Username or Email"></s:textfield>
<i class="fa fa-user"></i>
</span>
<span>
<s:fielderror fieldName="strUserName"/>
</span>
</div>
<div class="form-group">
<span class="input-icon">
<s:password name="strPassword" id="strPassword" cssClass="form-control" placeholder="Password"></s:password> <i class="fa fa-lock"></i>
</span>
<span>
<s:fielderror fieldName="strPassword"/>
</span>
</div>
</s:form>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.action.extension" value=",json"/>
<!-- Set to false before deploying the application -->
<constant name="struts.devMode" value="true" />
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.configuration.xml.reload" value="false" />
<!-- constant to define global resource bundle -->
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<constant name="struts.ui.theme" value="simple" />
<package name="<package_name>" namespace="/" extends="struts-default">
<action name="authenticate" class="<Action_class_name>" method="<method_name>">
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result type="redirectAction">Successpage</result>
<result name="input" type="redirectAction">login</result>
</action>
<action name="login">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<result>login.jsp</result>
</action>
</package>
</struts>
Action_name-validation.xml
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<validator type="requiredstring">
<param name="fieldname">strUserName</param>
<param name="trim">true</param>
<message key="errors.required"></message>
</validator>
<validator type="requiredstring">
<param name="fieldname">strPassword</param>
<param name="trim">true</param>
<message key="errors.required"></message>
</validator>
</validators>
Action_name.java
public class Action_name extends ActionSupport implements ModelDriven<UserModel> {
private UserModel user;
public String method_name() {
if(success){
return SUCCESS;
}else{
return INPUT;
}
}
#Override
public UserModel getModel() {
user = new UserModel();
return user;
}
}
Applicatin - intial run
Application - After Validation
value "xyz" is not repopulated after the validation.
There are two problems:
your login action
<action name="login">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<result>login.jsp</result>
</action>
has only a single interceptor, the MessageStore one.
It should have instead at least the ModelDriven and the Parameters Interceptors to work correctly. For example
<action name="login">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result>login.jsp</result>
</action>
But note that this would lead to infinite recursion due to the MessageStore Interceptor always adding errors and the Workflow Interceptor always returning "input"; to avoid it you should define a secondary defaultStack in your struts.xml with all the intercpetors except the Workflow one, otherwise the MessageStore with RETRIEVE will make it loop or, if you haven't defined an input result for your login action, complaining about a missing input result.
The second error is that you are redirecting, and hence losing the parameters. You're using the MessageStore Interceptor to preserve Action Messages, Action Errors and Field Errors across the redirection, but every other parameter is lost. If you want to preserve a parameter across a redirectAction you must explicitly send it, or store it in session in the source action and retrieving it in the destination action. In your case, it would be better to simply return the JSP in case of input result, instead of redirecting:
<action name="authenticate" class="<Action_class_name>" method="<method_name>">
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result type="redirectAction">Successpage</result>
<result name="input" >login.jsp</result>
</action>
<action name="login">
<interceptor-ref name="defaultStack" />
<result>login.jsp</result>
</action>
I am trying to validate user credentials details during application log in.I have changed my struts config and validation xml but the validation gets invoked on the page load itself.
I want that this validation should be invoked only during the click of a button(submit button).
My struts config is as under:
<action-mappings>
<action attribute="loginForm" input="jsp/LoginPage.jsp" name="loginForm"
parameter="method" path="/loginAction" scope="request"
type="com.pcs.bpems.portal.struts.action.LoginAction" validate="false">
<forward name="schoolloginpage" path="/jsp/SchoolLoginPage.jsp" />
</action>
<action attribute="loginForm" input="/jsp/SchoolLoginPage.jsp" name="loginForm"
parameter="method" path="/loginAction" scope="request"
type="com.pcs.bpems.portal.struts.action.LoginAction" validate="true">
<forward name="schoolloginpage" path="/jsp/SchoolLoginPage.jsp" />
<forward name="schoolhomepage" path="/ownerHome.do?method=showHome" />
</action>
My validation xml is as under
<form name="loginForm">
<field property="userId" depends="required,minlength">
<arg0 key="label.userName"/>
<var>
<var-name>minlength</var-name>
<var-value>6</var-value>
</var>
<arg1 key="${var:minlength}" resource="false" />
</field>
<field property="password" depends="required,minlength">
<arg0 key="label.password"/>
<var>
<var-name>minlength</var-name>
<var-value>6</var-value>
</var>
<arg1 key="${var:minlength}" resource="false" />
</field>
</form>
#Anish Try this code instead of your first LoginAction attribute,
<action path="/loginAction" parameter="method"
type="com.pcs.bpems.portal.struts.action.LoginAction" validate="false">
<forward name="schoolloginpage" path="/jsp/SchoolLoginPage.jsp" />
</action>
My thought is form name is not necessary for load the form, though you are made validate attribute to false. Let me know if this helps.
If you do not pass through the input, Struts performs the validation. There are several ways to solve it.
Request directly to the JSP
Make a request to the JSP file directly and not through the org.apache.struts.action.ActionServlet.
http://localhost:8080/MyContext/jsp/SchoolLoginPage.jsp
With a forward
<action path="/login" forward="/jsp/SchoolLoginPage.jsp" />
Use:
http://localhost:8080/MyContext/login.do
I'm using struts2 and my struts.xml looks like this:
<action name="actionA" class="actionAClass">
<result name="success" type="redirectAction">actionD</result>
<result name="error" type="redirectAction">actionB</result>
</action>
<action name="actionB" class="actionBClass">
<result name="success" type="redirectAction">actionC</result>
<result name="error" type="redirectAction">actionC</result>
</action>
<action name="actionC" class="actionAClass">
<result name="success">homepage.jsp</result>
<result name="error">homepage.jsp</result>
</action>
As you can see, actionA error result redirect to actionB and actionB error result redirect to actionC. At the end, I want to display the error message at the homepage.jsp but homepage is loaded only when actionC is called.
However using actions like this, when homepage is loaded, all the action error messages are lost.
I've also tried using interceptors in struts.xml between actions like below but still I'm not able to retrieve the error messages:
<action name="actionA" class="actionAClass">
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success" type="redirectAction">actionD</result>
<result name="error" type="redirectAction">actionB</result>
</action>
<action name="actionB" class="actionBClass">
<result name="success" type="redirectAction">actionC</result>
<result name="error" type="redirectAction">actionC</result>
</action>
<action name="actionC" class="actionAClass">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success">homepage.jsp</result>
<result name="error">homepage.jsp</result>
</action>
Please help how do I retrieve action error messages using multiple redirect actions.
I have this form:
<s:form
action="conexion" validate="true" theme="css_xhtml">
<s:textfield name="username" key="profile.rut" labelposition="left" />
<s:password name="password" key="profile.password" labelposition="left" />
<s:submit id="boton_ingreso" align="left" cssClass="send" value="Entrar" />
</s:form>
This validators:
<validators>
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>*</message>
</field-validator>
<field-validator type="rutValidator">
<param name="trim">true</param>
<message>*</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>*</message>
</field-validator>
</field>
</validators>
And this definition:
<action name="conexion" class="agenda.SecurityAction">
<interceptor-ref name="profiling">
<param name="profilingKey">profilingKey</param>
</interceptor-ref>
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="success" type="tiles">/profile.tiles</result>
<result name="error" type="redirectAction">
<param name="actionName">cliente</param>
</result>
<result name="input" type="redirectAction">
<param name="actionName">cliente</param>
</result>
</action>
This works perfectly client side. But when I remove validate="true" from the form in order to test server side, valdation occus and the form loads again, but no error message appears.
Other question regarding the same: I am not using JSON validation, but the normal client side validation. Why it does not work when I remove the definition?
I guess it is because maybe jsonValidationWorkflowStack inherits from other validation interceptor. If it is, perhaps it is convenient to define the other one, instead of jsonValidationWorkflowStack.
Your input result is a redirect and during redirect all request attributes (also messages) are gone, you must use MessageStoreInterceptor to persist them between requests.
See also Struts 2 Validation using Message Store Interceptor
http://struts.apache.org/development/2.x/docs/message-store-interceptor.html
I trying to use struts2 validation framework. I have a ActionName-validation.xml in place. Entry in the struts.xml is as follows
<action name="registerCandidateStep1" class="candidateAction"
method="registerCandidateStep1">
<result name="success" type="tiles">registerCandidate</result>
<result name="input" type="chain">
<param name="actionName">loadCandidateRegistrationForm</param>
<param name="namespace">/.secureActions</param>
</result>
</action>
<action name="loadCandidateRegistrationForm" class="loadCandidateFromAction"
method="loadCandidateRegistrationForm">
<result name="success" type="tiles">registerCandidate</result>
</action>
on error condition request do get forwarded to "loadCandidateRegistrationForm" but i dont see error on the page. I have included tag in the jsp
StrutsConfig.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.objectFactory" value="spring" />
<constant name="struts.devMode" value="false" />
<constant name="struts.action.extension" value="action" />
<constant name="struts.custom.i18n.resources" value="global" />
<package name="org" namespace="/"
extends="struts-default,json-default">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<global-results>
<result name="welcome" type="tiles">welcome</result>
</global-results>
</package>
<package name="org.unsecureActions" extends="org">
<!--
This package contains such a actions which doesn't need user logged
in.
-->
<action name="welcome" method="forwardAction" class="baseAction">
<result name="success" type="tiles">welcome</result>
</action>
<action name="logout" method="logoutCandidate" class="logoutAction">
<result name="success" type="tiles">welcome</result>
</action>
<action name="loadAdvanceSearchForm" method="loadAdvanceSearch"
class="advanceSearchAction">
<result name="success" type="tiles">advanceSearch</result>
</action>
<!--Candidate workflow actions -->
<action name="registerCandidateStep1" class="candidateAction"
method="registerCandidateStep1">
<interceptor-ref name="store">
<param name="operationMode">STORE</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success" type="tiles">registerCandidate</result>
<result name="input" type="redirect">loadCandidateRegistrationForm.action</result>
</action>
<action name="registerCandidateStep2" class="candidateAction"
method="registerCandidateStep2">
<result name="success" type="tiles">registerCandidate</result>
<result name="input" type="tiles">loadCandidateRegistrationForm</result>
</action>
<action name="registerCandidateStep3" class="candidateAction"
method="registerCandidateStep3">
<result type="chain">
<param name="actionName">loginCandidate</param>
<param name="namespace">/org.unsecureActions</param>
</result>
<result name="input" type="tiles">registerCandidate</result>
</action>
<action name="loadCandidateRegistrationForm" class="loadCandidateFromAction"
method="loadCandidateRegistrationForm">
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<result name="success" type="tiles">registerCandidate</result>
</action>
<!--Candidate workflow actions -->
<action name="loginCandidate" class="loginAction" method="loginCandidate">
<result name="success" type="tiles">home</result>
<result name="input" type="tiles">welcome</result>
</action>
</package>
<package name="org.secureActions" extends="org">
<!--
This package contains such a actions which needs user must logged in
before executing these.
-->
<interceptors>
<!--
Following interceptor checks for is user logged in before executing
the action.
-->
<interceptor name="contextSecurityInterceptor"
class="org.kovid.matrimony.interceptor.ContextSecurityInterceptor">
</interceptor>
<!--
This stack is as like default stack provided ny Struts Only
difference is at the bottom of folowing stack where we included our
"contextSecurityInterceptor" interceptor.
-->
<interceptor-stack name="applicationStack">
<interceptor-ref name="exception" />
<interceptor-ref name="alias" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="prepare" />
<interceptor-ref name="i18n" />
<interceptor-ref name="chain" />
<interceptor-ref name="debugging" />
<interceptor-ref name="profiling" />
<interceptor-ref name="scopedModelDriven" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="checkbox" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="actionMappingParams" />
<interceptor-ref name="params" />
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation" />
<interceptor-ref name="workflow" />
<interceptor-ref name="contextSecurityInterceptor" />
</interceptor-stack>
</interceptors>
<!--
Setting default stack for interceptor taking care of this packageS.
-->
<default-interceptor-ref name="applicationStack" />
<action name="home" method="forwardAction" class="baseAction">
<result name="success" type="tiles">home</result>
</action>
<action name="loadAdvanceSearchForm" method="loadAdvanceSearch"
class="advanceSearchAction">
<result name="success" type="tiles">advanceSearch</result>
</action>
<action name="simpleSearch" method="simpleSearch" class="simpleSearchAction">
<result name="success" type="tiles">search</result>
<result name="input" type="tiles">home</result>
</action>
<action name="advanceSearch" method="advanceSearch" class="advanceSearchAction">
<result name="success" type="tiles">search</result>
</action>
<action name="loadImage" method="loadImage" class="imageAction">
<result name="imageData" type="stream">
<param name="contentType">${imageContentType}</param>
<param name="inputName">imageStream</param>
<param name="contentDisposition">filename="candidate.jpeg"</param>
<param name="bufferSize">${myBufferSize}</param>
</result>
</action>
</package>
</struts>
Action chaining is actively discouraged, and interactions with the validation interceptor is one reason why. You might be able to sneak around it by explicitly mapping some values (like the validation messages) from one action to the next, but... don't chain actions--there's almost never a reason to do so.
Like Dave said, Action Chaining is discouraged.
Action Chaining :
Don't Try This at Home
As a rule, Action Chaining is not recommended.
First explore other options, such as the Redirect After Post
technique.
And if you have good reason to use Redirect After Post, use the
Redirect Result + Message Store Interceptor OR
Redirect Action Result + Message Store Interceptor
Life time of Errors lasts for the current Action. If you forward/redirect to another action, then the errors will be lost.
Use session scope instead. Place ArrayList in session and append your errors/messages.
Action/Interceptor:
Map session = ActionContext.getContext().getSession();
List<String> errors = session.get("errorMessages");
if(errors==null)
session.put("errorMessages", errors=new ArrayList<String>() );
errors.add("Invalid Username/Password. Kindly retry");
JSP:
<s:iterator var="msg" value="#session.errorMessages" >
<p> ${msg} </p>
</s:iterator>
<s:set scope="session" var="errorMessages" value="%{null}" /><%--flush errors--%>