Unable to repopulate values after xml validation in Struts2 [duplicate] - validation

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>

Related

Struts 2 validation not working

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">

Server side validation works, but it does not show error message

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

Validation in Struts 2 for 2 methods in the same action

I'm developing with Struts 2 and I would like to validate 2 methods in the same action (which represents a user). The first is the login method which checks the role of the user (admin or normal user) and the second is to edit the user :
public class UserAccountAction extends AppSupport {
public String login() {
if (getUsername().equals("admin") && getPassword().equals("admin")) {
session.put("username", getUsername());
return "adminSuccess";
} else if (getUsername().equals("user") && getPassword().equals("user")) {
session.put("username", getUsername());
return "userSuccess";
} else {
addActionError(getText("login.failedLoginCredential"));
return INPUT;
}
}
public String editProfile {
// ...
}
}
For that, I created 2 xml files : UserAccountAction-login-validation.xml :
<validators>
<field name="login">
<field-validator type="required">
<message key="form.required" />
</field-validator>
</field>
<field name="password">
<field-validator type="required">
<message key="form.required" />
</field-validator>
</field>
</validators>
The UserAccountAction-editProfile-validation.xml is the same with lastname and firstname.
The struts.xml :
<action name="login" method="login" class="com.project.action.UserAccountAction">
<result name="input">/jsp/login.jsp</result>
<result name="userSuccess" type="redirect">home.html</result>
<result name="adminSuccess" type="redirect">admin/home.html</result>
</action>
<action name="edit_account" method="editProfile" class="com.facilityrh.action.UserAccountAction">
<result name="input" type="tiles">userEditProfile</result>
<result name="success" type="redirect">account.html</result>
</action>
And the login.jsp :
<s:if test="hasActionErrors()">
<div class="error"><s:actionerror /></div>
</s:if>
<s:if test="hasActionMessages()">
<div class="message"><s:actionmessage /></div>
</s:if>
<s:form action="login" method="post">
<s:textfield name="login" key="login.login" /><br />
<s:password name="password" key="login.password" /><br />
<s:submit name="submit" key="login.submit" />
</s:form>
For the moment, in the action, the verification is basic but after, I'll use the database to get informations.
The problem is when I submit the form (login or editProfile), the method is not executed because I've no error, I return on the same jsp (without the required messages next to input)
Thank you

struts2 errors lost

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--%>

Wildcard action mapping with dummy data in Struts 2

I'm trying to map my Struts actions using wildcards.
Before, I used UrlRewrite Filter by Tuckey. But this question changed my mind.
So here's my problem: My URL's look like the following:
www.example.com/promoties/category-123
www.example.com/promoties/category-123/subcategory-456
In these examples, the words category and subcategory are dummy data used to make the URL more relevant for search engines.
Now I'd like to ignore this dummy data, as I'm just interested in the (last) ID. In the first case 123 in the last case 456.
I've tried the following without success:
<package name="promoties" namespace="/promoties" extends="struts-default">
<action name="([0-9a-zA-Z\-_]+)-{id:([0-9]+)}$" class="CategoryAction">
<result type="tiles">categorydetail</result>
</action>
</package>
Using following options in my struts.xml:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.patternMatcher" value="regex" />
Has anyone tried this before? How would I go about doing this in Struts2?
One way is to use simple wild card mapping and regulate the validation of the id component to struts2 validation. Here is an example which has been tested, but without validation.
struts.xml you'll see an action defined for category-* and category-*/subcategory-* in the second we'll just keep the second wild card.
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<package namespace="" name="default" extends="struts-default">
<action name="category-*" class="test.TestBean">
<param name="id">{1}</param>
<result>/WEB-INF/content/test/results.jsp</result>
</action>
<action name="category-*/subcategory-*" class="test.TestBean">
<param name="id">{2}</param>
<result>/WEB-INF/content/test/results.jsp</result>
</action>
</package>
</struts>
test.TestBean here I used a String but in your case you'll change this to int or Integer. You'll want to validate that we did get an integer using validation xml or simply implementing com.opensymphony.xwork2.Validateable.
package test;
import com.opensymphony.xwork2.ActionSupport;
public class TestBean extends ActionSupport{
//public to avoid get/set to make example shorter
public String id;
}
/WEB-INF/content/test/results.jsp
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h1>Wild Card Value</h1>
id: <s:property value="id"/>
</body>
</html>
Example 1
The url: example.com/category-helloBart produces...
Wild Card Value
id: helloBart
Example 2
The url: example.com/category-helloBart/subcategory-123 produces...
Wild Card Value
id: 123

Resources