Struts 2 OGNL - Comparing two string values in validation.xml - java

I am new to Struts2 and OGNL and am making a simple web application with a registration page. There are two fields, password and repassword (to re-enter the password) and using the validation framework i would like to validate that the two passwords match (I know that I can do it easily with JavaScript). Here is what I've got so far. All of the field-validators are working fine. This is my first non-field validator and I just cant get it to work.
<validator type="expression">
<param name="expression">${password}!=${repassword}</param>
<message>Passwords must match.</message>
</validator>
I tried both with
${password}!=${repassword}
and without
password!=repassword
the OGNL tags.

The expression validator is a Non-Field Level validator. Use fieldexpression validator which is a Field Level validator and validates using OGNL expression. And it must be equals (==) check.
<field name="password">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[password == repassword]]></param>
<message>Passwords must match.</message>
</field-validator>
</field>
The expression validator adds action errors. The fieldexpression validator adds field errors.

try
%{password == repassword}
The validator checks to boolean OGNL expression that both are equal.

Related

How to restrict a user to enter numerics in a Integer field with help of annotations?

I need to restrain a user to enter numeric values in a jsp field.On failure it should give relevant message.This is my current declaration:
#NotNull
#Column(value="userId")
private Long userId;
I need to know what more annotations do i need to add, to get my desired result without changing data type of the field.
Hibernate
#Range - Check if the value is between min and max
Example
#Range(min=1, max=1000)
#Pattern - Check if the property match the regular expression given a match flag
#Pattern(regex="regexp", flag=) or #Patterns( {#Pattern(...)} )
Example
#Pattern(regex = "[0-9]+")
Spring
#RegExp - Check if the property match the regular expression given a match flag
Example
#RegExp("[0-9]+")
This isn't something that would be done on the validation level.
When you enter something in a form and you submit that form, the browser will send an HTTP request with your <input> fields serialized and sent as request parameters. Spring then, based on the data type of your bean's field, tries to convert from a String request parameter value to a Long type. If it can't do that because the String is not a Long, it will throw exceptions (NumberFormatException) and respond with a 400 error code.
You can validate this on the (HTML5) client side with
<input name="userId" type="number">
Or use
<input type="text" pattern="\d*" />
if you don't want decimal numbers.

Websphere Commerce: Sorting results of <wcf:getData ...>

Is there a way to get the IBM Websphere Commerce Foundation framework (WCF) sort data?
E.g. this snippet from a Websphere Commerce JSP file:
<wcf:getData type="com.ibm.commerce.store.facade.datatypes.GeoNodeType[]"
var="geoNodes" varException="geoNodeException" expressionBuilder="findChildGeoNodesByGeoNodeUniqueID">
<wcf:param name="accessProfile" value="IBM_Store_All" />
<wcf:param name="parentUniqueId" value="${provinceId}" />
</wcf:getData>
How would I get this to sort the data by a given data field in GeoNodeType? Can I add something like <wcf:param name="sortBy" value="Description" /> ?
ExpressionBuilder "findChildGeoNodesByGeoNodeUniqueID" from your example is declared in /Stores/WebContent/WEB_INF/config/com.ibm.commerce.store/get-data-config.xml as follows:
<expression-builder>
<name>findChildGeoNodesByGeoNodeUniqueID</name>
<data-type-name>GeoNode</data-type-name>
<expression-template>{_wcf.ap=$accessProfile$}/GeoNode[ParentGeoNodeIdentifier[UniqueID='$parentUniqueId$']]</expression-template>
<param>
<name>accessProfile</name>
<value>IBM_Store_All</value>
</param>
<param>
<name>parentUniqueId</name>
<value></value>
</param>
</expression-builder>
According to expression-builder tag docs, if expression-language is not specified inside expression-builder tag - XPath language is used by default. Unfortunately XPath does not support ordering.
I imagine that you can still implement your own ExpressionBuilder class (I haven't done that), implement any kind of sorting inside this new class, and then specify it in get-data-config.xml

How Struts2 validation framework works

I am using struts2 for my project.
Now i have a business information fill-up form for getting business details.
In form i have some basic items such as email, username , password , confirm password & Facebook twitter links(FB & tweeter links are optional but if user enters i want to check whether they are real)
for basic items i am using xml file validation as:
<validators>
<field name="companyname">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Company name is required.</message>
</field-validator>
</field>
<field name="fblink">
<field-validator type="url">
<message>Please enter a valid url</message>
</field-validator>
</field>
<field name="tweetlink">
<field-validator type="url">
<message>Please enter a valid url</message>
</field-validator>
</field>
</validators>
& if user enters values for Facebook or twitter url i am writing validation in Action class's Validate() method to check whether these are real(means HTTP_STATUS_CODE=200)
as :
public void validate()
{
if(getFblink()!=null && !getFblink().isEmpty())
{
if(URLValidation.validate(getFblink())== false)
{
addFieldError("fblink", getText("Enter valid facebook page link"));
}
}
if(getTweetlink()!=null && !getTweetlink().isEmpty())
{
if(URLValidation.validate(getTweetlink())== false)
{
addFieldError("tweetlink", getText("Enter valid tweeter link"));
}
}
}
Here URLValidation is my class & it contains static method validate which takes URL & using Httpclient libraries i am hitting & checking its status code.
Depending on its return value i.e boolean value i am setting error message.
Its working. But i want to know is my approach is correct?
Also i want to use shor-circcuit validation so how can i communicate in xml & validate() validation code??
You want to validate links and want to use your code (from validation xml). This will be possible by writing custom validators. Write a custom validator and use it through XML file for your fields.
For example you can see this tutorial for an idea.

small program on struts2 and jsp

i have done some learning on struts based on one project that i got.Now i have to build 2 to 3 struts jsp pages.
I have following scenario..
<action name="BackAction" class="ClassnamePath">
<result name="user_validated" type="redirectAction">
<param name="actionName">welcome</param>
</result>
<result name="user_profile_found_in_database">/resources/userprofile.jsp</result>
what does param will tell..what is the significance of param(i do not know about this)
my scenario is like this In the class(ClassnamePath) i have done one java program which bring the data from the database and put the values in the userprofile.java(for example the userprofile has variable members like name,email,phone,pin)
that values are come from database and stored in the object of the class userprofile.
i have a task that whenever the result "user_profile_found_in_database" has been done those values should be presented in the jsp as result of the "user_profile_found_in_database"
Is the result "user_profile_found_in_database" that i mentioned in the action tag correct?
the jsp page should be having userprofile with labels as the fields of the userprofile and values should be in the text boxes.
i do not know anything about jsp pages...even web programming..but i am learning on my own..(i am having one doubt how jsp pages are different from struts jsp pages)
with the above tasks i can learn lot in struts and jsp..
Please give some knowledge on this to build further.
JSP pages are not way different than simple JSP pages and in short Struts2 will provides a set of tags which will help we as an end developer to build application fast as these tags provides a easy to access functionality about various features S2 providing, few of them are
Accessing Value Stack using OGNL
Data conversion from server to client and other way around
Features to access other things like request/response/session in most easy and flexible way.
In end when you browser will render the jsp page it will be simple HTML and S2 tags one using in there application will be converted to the HTML as browser will understand HTML.
regarding second part accessing user profile in your jsp do the following gin your Action class
Create an instance of UserProfile in you action class
Create getter and setter for the UserProfile instance
Fill the value in the user-profile (you will fetch that from your DB call)
when your action will send back the response, S2 will place the user-profile instance on top of Value stack and we can access its properties using S2 tags like
<s:textfield name="user_name" value="%{name}"/>
<s:textfield name="user_age" value="%{age}"/>
here name and age are the properties of your user-profile.param in your redirectAction configuration is being used to provide parameters to the result, for more information about what parameters do please read official document.
redirect-action-result
.
Ya i got your question like this,
what is the exact meaning of param tag?
param tag means:
Struts 2 “param” tag is used to parametrize other tags. However, when you declared the “param” tag, the “parameter value” can be define in two ways :
“value” attribute
Text between the start and end of “param” tag.
For Example:
<param name="fruit">Banana</param>
<param name="fruit" value="Banana"/>
In Your example the 1st case i think
Here see this web site it is present complete structure...
http://www.mkyong.com/struts2/struts-2-param-tag-example/

how to validate dynamic map elements

i have a map and i want to validate in struts 2 validation framework by using expression validation how can i access the elements of the map dynamically?
if Map myMap; how can i validate the map with dynamic key? if mymap has static key like "Salary", i could validate like
<field
name="myMap['Salary']">
<field-validator
type="regex">
<param
name="expression">[0-9]+[.][0-9]+</param>
<message>${getText("errors.validation.number")}</message>
</field-validator>
</field>
thanks,
Helen
There are two ways you can use the myApp in declarative validation.
By using myMap.salary
By using myMap['salary']
You will need to use one of the above notations which is based on how you have your input form fields defined.
For example, if your input form looks something like below then you need to use the . operator as you are using the . operator while defining the name of input field.
<s:form action="sayHello">
<s:textfield name="myMap.salary" label="Salary">
<s:submit/>
</s:form>
If you use [] opertaor for defining the name of input field then use the [] operator to access the property in validator.
So, your validation code above is correct, you just need to define your input field at input form correctly with [] operator.
Hope this helps
Hibernate Validator Framework has a recursive validation feature.
And there is a plugin for Struts2 that uses this:
Full Hibernate Plugin: http://cwiki.apache.org/S2PLUGINS/full-hibernate-plugin.html
I don't think you can do this in the declarative validation. I'd suggest dropping down to the validation method for this, or doing the validation in javascript if you're using the javascript validation that is generated by the framework.

Categories

Resources