Detect blank HTML form input values - servlets

When I submit a HTML form with blank data it's still going into else block below:
String n=request.getParameter("uname");
String e=request.getParameter("mail");
String p=request.getParameter("pwd");
if(n==null || e==null || p==null)
{
// ...
} else
{
// ...
}
How can I make sure that it enters the if block?

Blank submitted input values do not arrive as null. Instead, they arrive as empty string. The null only means that the input value was not submitted at all (i.e. the input field was totally absent in the form).
If you're not interested in distinguishing the presence of a specific input field in the form, then add a String#isEmpty() check to the if block.
if (n == null || n.isEmpty() || e == null || e.isEmpty() || p == null || p.isEmpty()) {
// ...
}
You could even bake a custom utility method for this.
public static boolean isEmpty(String string) {
return (string == null || string.isEmpty());
}
if (isEmpty(n) || isEmpty(e) || isEmpty(p)) {
// ...
}
You can even go a refactoring step further with help of varargs.
public static boolean isOneEmpty(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return true;
}
}
return false;
}
if (isOneEmpty(n, e, p)) {
// ...
}
If you would like to cover whitespace as well, then replace string.isEmpty() over all place by string.trim().isEmpty().
See also:
Our Servlets wiki page
How to determine which form has been submited and to validate them in a servlet
Validating numbers with Servlets and JSP

This is because uname,mail,pwd variables are not null instead these parameters contains empty strings.
i.e.
uname="";
mail="";
pwd="";
when you check whether these parameters are null or not , it results into false and your else block executes and persist the record into database.
you can create a method to check empty string(s).
public static boolean checkEmpty(String value){
if(!(value==null))
return value.isEmpty();
return true;
}
replace your if condition with this:
if(checkEmpty(n) || checkEmpty(e) || checkEmpty(p)){
}

String n=request.getParameter("uname");
if (n != null) n = n.trim();
if (n == null) n = "";
String e=request.getParameter("mail");
if(e != null) e = e.trim();
if(e == null) e = "";
String p=request.getParameter("pwd");
if(p != null) p = p.trim();
if(p == null) p = "";
//
// only process if values for all three exist
//
if((n.length() < 1) || (e.length() < 1) || (p.length() < 1))
{
// ...
} else
{
// ...
}

Related

ignore fields while comparing two lists

I have two lists of Person objects.
Person class has the below attributes
String Name,
Integer Age,
String Department,
Date CreatedTime,
String CreatedBy
When I compare my lists for equality, I would like not to compare the CreatedTime and CreatedBy fields.
How can I compare, using Java 8, the two lists for equality and also ignore the CreatedTime, CreatedBy fields for comparison?
You don't even need features from Java-8 to do this, simply override the equals & hashCode like this:
class Person {
String name;
Integer age;
String department;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
if (age != null ? !age.equals(person.age) : person.age != null) return false;
return department != null ? department.equals(person.department) : person.department == null;
}
#Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
result = 31 * result + (department != null ? department.hashCode() : 0);
return result;
}
}
Then you can compare two given lists like so:
boolean result = firstList.equals(secondList);
edit:
following your comment:
I need this form of comparison only for test purposeses . In my
production code I would like to retain equals and hashcode to compare
all fields
you can define a custom equal method like so:
public static boolean areEqual(List<Person> first, List<Person> second) {
Objects.requireNonNull(first, "first list must not be null");
Objects.requireNonNull(second, "second list must not be null");
return first.size() == second.size() &&
IntStream.range(0, first.size()).allMatch(index ->
customCompare(first.get(index), second.get(index)));
}
or if you want to allow null to be passed to the areEqual method then a little change will suffice:
public static boolean areEqual(List<Person> first, List<Person> second){
if (first == null && second == null)
return true;
if(first == null || second == null ||
first.size() != second.size()) return false;
return IntStream.range(0, first.size())
.allMatch(index ->
customCompare(first.get(index), second.get(index)));
}
then along with it the method that will determine if two given person objects are equal:
static boolean customCompare(Person firstPerson, Person secondPerson){
if (firstPerson == secondPerson) return true;
if (firstPerson.getName() != null
? !firstPerson.getName().equals(secondPerson.getName()) : secondPerson.getName() != null)
return false;
return (firstPerson.getAge() != null ? firstPerson.getAge().equals(secondPerson.getAge()) : secondPerson.getAge() == null)
&& (firstPerson.getDepartment() != null
? firstPerson.getDepartment().equals(secondPerson.getDepartment())
: secondPerson.getDepartment() == null);
}
Then call it like so:
boolean result = areEqual(firstList, secondList);
You can use Streams.zip() from Guava for a more functional solution. Ignoring null checks for brevity:
public static boolean comparePersonLists(List<Person> list1, List<Person> list2) {
if (list1.size() != list2.size()) {
return false;
}
return Streams.zip(list1.stream(), list2.stream(), (a, b) ->
a == b || (a.name.equals(b.name) && a.age.equals(b.age) && a.department.equals(b.department))
).allMatch(t -> t);
}

Check Cookies AND Session in Same IF Statement

I have a function that checks for Session and Cookies and redirects user based on those.
private void CheckRecruiterLogin()
{
List<string> list = new List<string>();
if (Session["Candidate"] != null ||
Request.Cookies["Candidate"] != null)
{
list = (List<string>)Session["Candidate"];
string status = list[1].ToString();
if (status.Equals("applicant") ||
Request.Cookies["Candidate"]["Status"].Equals("applicant"))
{
Response.Redirect("ApplicantHome.aspx");
}
if (status.Equals("preboarding") ||
Request.Cookies["Candidate"]["Status"].Equals("preboarding"))
{
Response.Redirect("PreboardingHome.aspx");
}
else if (status.Equals("hiring") ||
Request.Cookies["Candidate"]["Status"].Equals("hiring"))
{
Response.Redirect("HiringHome.aspx");
}
}
else if (Session["HR"] != null || Request.Cookies["HR"] != null)
{
list = (List<string>)Session["HR"];
string type = list[1].ToString();
if (type.Equals("preboarder") ||
Request.Cookies["HR"]["Type"].Equals("preboarder"))
{
Response.Redirect("PreboarderList.aspx");
}
else if (type.Equals("datamanager") ||
Request.Cookies["HR"]["Type"].Equals("datamanager"))
{
Response.Redirect("HiringList.aspx");
}
else if (type.Equals("admin") ||
Request.Cookies["HR"]["Type"].Equals("admin"))
{
Response.Redirect("AdminHome.aspx");
}
}
else if (Session["HR"] == null &&
Request.Cookies["HR"] == null)
{
Response.Redirect("index.aspx");
}
}
But the application throws a runtime exception saying Object reference not set to an instance of an object. I believe this is because there are no cookies present.
My question is: Should I separate the checking of sessions and cookies, or can I do it in one statement?
Thanks!
Your code requires both the cookie, and the session.
If this is intended, you want to change the condition to use && instead of ||.
However, it's more likely you intend the code to use session if available, and cookies if session isn't there. This is quite simply done by storing the value in a variable, and using that later:
if (Session["Candidate"] != null || Request.Cookies["Candidate"] != null)
{
var list = Session["Candidate"] as List<string>;
var status = list == null ? Request.Cookies["Candidate"]["Status"] : list[1];
if (status == "applicant")
{
...
}
...
}
That said, using cookies for security checks like this is a bad idea - they are user visible and user editable.
Also, there's no point in using Equals - just use ==. This isn't Java, .NET actually compares the value, not the reference. Although it's probably a better idea to actually do the comparison using invariant culture, case insensitive equality. There's also no point in creating new List<string> - the value is never used. Just declare the variable at the point where you already have something to fill it with.
You are directly checking that if Request has a cookie named "HR" which will throw exception if there is no cookie with this name. So you first need to check if CookieCollection have any cookie with name "HR". Here is method which checks if CookieCollection have a cookie with a given name.
if(Request.Cookies.Get("cookieNmae") !=null)
So change your if statement like this
if (Session["HR"] != null || Request.Cookies.Get("HR") !=null)

How to get just one value from querystrig

I'm write this function:
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
{
if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
}
return "NAQ";
}
And i want to get just one value from querystring parameter.
for example i send "page" to my function and url is: "sth.com/?page=1&page=2"
and function return to me: "1,2" ; but i want first value: "1", How?
GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.
You could also use the Enumerable.First extension method:
Request.QueryString.GetValues("page").First();
Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
if (values != null) return values.First();
}
return "NAQ";
}
A better approach would be -
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
{
return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
}
return "NAQ";
}

Is it possible to use a Kleene Operator for Flex Formatters?

is it possible to use a Kleene Operator (Kleene Star) for the Formatters?
I want to use a phoneFormatter, which puts a minus after the 5th number and afterwards it should be possible to have a variable number of numbers.
E.g.: 0172-555666999, 0160-44552 etc.
That is how I started, but I don't know which character belongs after the last hash (it is not a star, I already tried it ;-) ):
<fx:Declarations>
<mx:PhoneFormatter id="mPhoneFormat"
formatString="####-#"/>
</fx:Declarations>
The default PhoneFormatter expects the input string to have the same number of characters as the format string. They don't support regular expression patterns (like * to match the element zero or more times).
However, it's pretty easy to make your own formatter. To do this, I extended the PhoneFormatter class and overrode its format() method. I copied and pasted the original format() method and made the following modifications:
comment out the code that compared the length of the source string with the length of the format string
compare the length of the formatted string. If the original string is longer, append the remaining chars from the original string to the formatted string.
This probably won't handle all of your use cases, but it should be pretty straightforward to modify this to your needs.
package
{
import mx.formatters.PhoneFormatter;
import mx.formatters.SwitchSymbolFormatter;
public class CustomPhoneNumberFormatter extends PhoneFormatter
{
public function CustomPhoneNumberFormatter()
{
super();
}
override public function format(value:Object):String
{
// Reset any previous errors.
if (error)
error = null;
// --value--
if (!value || String(value).length == 0 || isNaN(Number(value)))
{
error = defaultInvalidValueError;
return "";
}
// --length--
var fStrLen:int = 0;
var letter:String;
var n:int;
var i:int;
n = formatString.length;
for (i = 0; i < n; i++)
{
letter = formatString.charAt(i);
if (letter == "#")
{
fStrLen++;
}
else if (validPatternChars.indexOf(letter) == -1)
{
error = defaultInvalidFormatError;
return "";
}
}
// if (String(value).length != fStrLen)
// {
// error = defaultInvalidValueError;
// return "";
// }
// --format--
var fStr:String = formatString;
if (fStrLen == 7 && areaCode != -1)
{
var aCodeLen:int = 0;
n = areaCodeFormat.length;
for (i = 0; i < n; i++)
{
if (areaCodeFormat.charAt(i) == "#")
aCodeLen++;
}
if (aCodeLen == 3 && String(areaCode).length == 3)
{
fStr = String(areaCodeFormat).concat(fStr);
value = String(areaCode).concat(value);
}
}
var dataFormatter:SwitchSymbolFormatter = new SwitchSymbolFormatter();
var source:String = String(value);
var returnValue:String = dataFormatter.formatValue(fStr, value);
if (source.length > returnValue.length)
{
returnValue = returnValue + source.substr(returnValue.length-1);
}
return returnValue;
}
}
}

What is the different between stringvariable != NullValue.String and !string.IsNullOrEmpty(stringvariable) in asp.net?

Is there any different between stringvariable != NullValue.String and !string.IsNullOrEmpty(stringvariable) in asp.net ? then which is best ?
The first tests that the string isn't "".
As strings can be null (because they are actually references) this test could fail.
By using IsNullOrEmpty you are wrapping:
if (string != null && string.Length > 0)
in one test.
IsNullOrEmpty is implemented like:
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
So it checks both an empty string, and a null string. (Where is NullValue.String defined, I cannot seem to find a reference to it in any docs, but I assume it's eiter String.Empty or "null", so your first check only checks for one of these conditions.)
.Net4 has a new function called IsNullOrWhiteSpace(string value) which also returns true if the string contains only white space.

Resources