on action error message not showing on same page - validation

I have insert and view on same page. but problem is error message not showing
<action name="ViewAllCostings" class="volo.tms.costings.Costings" method="ViewAllCostings">
<result name="success">/costings/costings.jsp</result>
</action>
<action name="addcosting" class="volo.tms.costings.Costings">
<result name="input">/costings/costings.jsp</result>
<result name="success" type="chain">ViewAllCostings</result>
<result name="error" >/costings/costings.jsp</result>
</action>
and costings.jsp
<s:actionerror/>
<s:form action="addcosting" method="post">
<s:textfield label="Costing Type" name="costtype" required="true"/>
<s:textfield label="Cost(rs.)" name="costrs" required="true"/>
<s:submit value="ADD" name="addcostbutton"/>
</s:form>
<div class="Wrapper">
<display:table id="txt" name="costinglist" pagesize="10" cellpadding="2px;" cellspacing="5px;" requestURI="">
<display:column property="costtype" title="Cost Type" sortable="true"></display:column>
<display:column property="costrs" title="Cost(rs.)" sortable="true"></display:column>
</display:table></div>
and action class
public String execute(){//used this method for insert data
ArrayList costList = new ArrayList();
costList.add(costtype);
costList.add(costrs);
costList.add(costid);
if (AddCostDao.insertEditCostDetails(costList)) {
return SUCCESS;
} else {
addActionError("Employee name already exists !");
return ERROR;
}}
public String ViewAllCostings(){
//used for view data using list
return SUCCESS
}
did not getting error message. I tried but not getting solution

You might have validation errors which results INPUT, but the action is not executed and message isn't set. If you want to prevent the action from validation you can configure the action to exclude the method from validation interceptor. As far as validation interceptor implements a method filter interceptor you can do it in struts.xml. Or just add #SkipValidation annotation on the method.
#SkipValidation
public String execute(){//used this method for insert data

Related

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

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>

My form is not repopulated when validation fails

I have a simple page with a firstName field and a lastName field both of which are required. When I only enter one field I get the correct error message but I lose the value I have entered. I do have getters and setters for the fields and the page uses the values correctly if I enter them. Everything seems set up in the same way I had it on my previous project and I did not lose data on those pages. I know this question has been asked before but I can't find anything wrong with my code based on those answers so I am hoping someone can see what I am doing wrong.
My jsp code is:
<s:form action = "sign" validate="true" method="post" id="sign" >
<s:hidden name="dateSigned"></s:hidden>
<div class="row">
<div class = "col-md-7 col-xs-12">
<div class="col-md-3 col-sm-3 col-xs-12"><label for="firstName" class="pull-right"><span class="required">*</span><s:text name="firstName"></s:text>:</label></div>
<div class="col-md-3 col-sm-3 col-xs-12"><s:textfield name = "firstName" id = "firstName" value="" maxlength="50" class="form-control" onchange="dirtyFlag();" tabindex="4"/></div>
<div class="col-md-3 col-sm-3 col-xs-12"><label for="lastName" class="pull-right"><span class="required">*</span><s:text name="lastName"></s:text>:</label></div>
<div class="col-md-3 col-sm-3 col-xs-12"><s:textfield name = "lastName" id = "lastName" value="" maxlength="50" class="form-control" onchange="dirtyFlag();" tabindex="5"/></div>
</div>
</div>
<div class="row">
<s:submit method="save" key="button.save" cssClass="submit" onclick="clearDirtyFlag();" tabindex="1"/>
</div>
My struts action is:
<action name="sign" class="gov.mo.dnr.egims.controller.request.RequestorSignatureAction">
<result name="success" type="tiles">reqSign</result>
<result name="input" type="tiles">reqSign</result>
<result name="error" type="tiles">error</result>
<result name="ownerSignature" type="redirectAction">
<param name="actionName">owner</param>
<param name="namespace">/req</param>
<param name="requestId">${requestId}</param>
</result>
</action>
My tiles code is:
<definition name="reqSign" extends="baseLayout">
<put-attribute name="navbar"
value="/WEB-INF/pages/request/nav_secondary.jsp" />
<put-attribute name="content"
value="/WEB-INF/pages/request/RequestorSignature.jsp" />
</definition>
My struts2 result-types and interceptor code is:
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors>
<interceptor name="validUser" class="gov.mo.dnr.egims.controller.interceptors.ValidUser" />
<interceptor-stack name="validUserStack">
<interceptor-ref name="validUser" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
<interceptor name="userInRole" class="gov.mo.dnr.egims.controller.interceptors.UserInRole">
<param name="rolesList">Administrator,Geologist,Requestor,Reviewer, User</param>
</interceptor>
<interceptor-stack name="userInRoleStack">
<interceptor-ref name="userInRole" />
</interceptor-stack>
</interceptors>
My validation xml is:
<validators>
<field name="firstName">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="errors.required" />
</field-validator>
<field-validator type="regex">
<param name="regex">^[ a-zA-Z0-9'\-,.!:##/]*$</param>
<message key="errors.invalidCharacter"/>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">50</param>
<message key="errors.maxlength"></message>
</field-validator>
</field>
<field name="lastName">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="errors.required" />
</field-validator>
<field-validator type="regex">
<param name="regex">^[ a-zA-Z0-9'\-,.!:##/]*$</param>
<message key="errors.invalidCharacter"/>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">50</param>
<message key="errors.maxlength"></message>
</field-validator>
</field>
Any help would be appreciated, thanks!
Here is the requested dirtyFlag() code (and related code):
//needToConfirm used by confirm exit
var needToConfirm = false;
//default string message to display before leaving a page when data on the page has changed
//these changes were made to allow the message displayed before exiting to be customized
var defaultWarningMessage = "There is unsaved data on this screen. Do you want to exit anyway?";
var dirtyWarningMessage = defaultWarningMessage;
//this line intercepts attempts to leave the page via clicking the X button.
window.onbeforeunload = function ()
{
if (needToConfirm)
{
var outMessage = dirtyWarningMessage;
setDirtyWarningMessage(defaultWarningMessage);
return outMessage;
}
// no changes - return nothing
}
//function to set the string message to display before leaving a page when data on the page has changed
function setDirtyWarningMessage(inMessage)
{
dirtyWarningMessage = inMessage;
}
//function to set dirty flag
function dirtyFlag()
{
//alert ("Dirty flag set");
needToConfirm = true;
}
//function to clear dirty flag
function clearDirtyFlag()
{
//alert ("Dirty flag cleared");
needToConfirm = false;
}
//function to confirm close
function confirmClose()
{
if (needToConfirm)
{
var agree=confirm("Some data on the page is modified. Do you wish to leave the page without saving changes?");
if (agree == true)
{
needToConfirm = false;
window.close();
}
else
{
return false;
}
}
else
{
window.close();
}
}
Guess what ?
<s:textfield name = "firstName"
id = "firstName"
value = ""
maxlength = "50"
class = "form-control"
onchange = "dirtyFlag();"
tabindex = "4"/>
value="" forces the value to always be empty.
Use value="%{firstName}", or
remove it and let name="firstName" do the job (recommended).

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

Validating a form on a button click in struts 1.2

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

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

Resources