Java - Checking if a value is assigned by If Else statements - java

Trying to write some code which checks if something has been entered in a form in the JSP, and if it hasn't, assigns it the value from the session.
Once this has been done an object is made from all of the parameters.
Written all the code but the
User user = new User(username, firstname, surname, password); comes up with a cannot **find symbol error**
I realise that this is because it isn't in any of the ifs. Will anyone show me how I can change the code so that it can use these values?
The code:
try {
User sessionuser =(User)session.getAttribute("User");
String username = sessionuser.getUsername();
if (request.getParameter("firstname").equals (null)){
String firstname = sessionuser.getFirstname();
}
else{String firstname = request.getParameter("firstname");
}
if (request.getParameter("surname").equals (null)){
String surname = sessionuser.getSurname();
}
else{String surname = request.getParameter("surname");
}
String password = request.getParameter("password");
User user = new User(username, firstname, surname, password);
//this.updateUser(user);
this.updateUser(username, firstname, surname, password);
//user.updateUser();
session.setAttribute("User", user);
request.setAttribute("u", user);
request.getRequestDispatcher("UpdateUser.jsp").forward(request, response);

A quick hint
if (request.getParameter("firstname").equals (null)){
...
if (request.getParameter("surname").equals (null)){
...
This can never be true, it can be false or throw NullPointerException. Use == instead of equals()

Lets take a snippet of your code and tell you why you are getting the error
if (request.getParameter("firstname").equals (null)){
String firstname = sessionuser.getFirstname();
}
In here, you are instantiating the string firstname in the if statement, when the condition is true, the string is created but is only accessible inside the if statement.
What you should do is
String firstname = sessionuser.getFirstname();
if (request.getParameter("firstname") != null){
firstname = request.getParameter("firstname");
}

You are defining the variables firstname and surname in the if/else construct, which is prevented by the compiler. In this case, yes, it will be defined, but in other cases it might not, and the compiler doesn't spend too much time on static code analysis, it will prevent such behaviour without further investigating.
Instead of defining the variable in if/else, use a default, in this case you can use:
String surname = sessionuser.getSurname();
if (request.getParameter("surname") != null){
surname = request.getParameter("surname");
}
Note that I switched the conditions a bit.
Also, your if will never be true, it will either be false or throw NullPointerException. Use request.getParameter("surname") == null instead.

You need to declare your variables outside the blocks in the if/else chains.
Use something like:
String surname = request.getParameter("surname");
if (surname == null) {
surname = sessionuser.getSurname();
}
Repeat for the other items.
Local variables are only available in the block in which you define them (and its sub-blocks). The way you're doing it, your creating variables inside the if and else blocks that are discarded (cannot be referred to) at all outside those blocks.
If you need to test if these parameters are either null or empty strings, do the if checks like this:
if ((surname == null) || ("".equals(surname))) { ... }
Don't use == to compare strings, that's not reliable - it compares references, not the string contents.

Alternatively, you can save yourself bit of typing and get rid of IF-ELSE blocks. You can use method like StringUtils.defaultString.
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#defaultString(java.lang.String,%20java.lang.String)
One line for one field will do:
String firstName = StringUtils.defaultString(request.getParameter("firstname"), sessionuser.getFirstname())
Do the same for other fields.
This function basically replaces your IF-ELSE block. As a bonus, you won't make a mistake declaring variable inside IF-ELSE block :)

You could use string variables and then check to see if it is NULL or not.
String test = request.getParameter("test");
if (username.equals(""))
{
//todo
}

Should be like this I think
try {
User sessionuser =(User)session.getAttribute("User");
String username = sessionuser.getUsername(),firstname="",surname="",password="";
if (request.getParameter("firstname") == ""){
firstname = sessionuser.getFirstname();
}
else{firstname = request.getParameter("firstname");
}
if (request.getParameter("surname") == ""){
surname = sessionuser.getSurname();
}
else{surname = request.getParameter("surname");
}
password = request.getParameter("password");
User user = new User(username, firstname, surname, password);
//this.updateUser(user);
this.updateUser(username, firstname, surname, password);
//user.updateUser();
session.setAttribute("User", user);
request.setAttribute("u", user);
request.getRequestDispatcher("UpdateUser.jsp").forward(request, response);
You can also use null instead of ""

Related

equals method doesn't work

I'm practicing a simple Java GUI by making a login system without a database, but my if statement using .equals doesn't work because it always says incorrect password.
contains() work but I think it's not that secure
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if(user.equals("username") && pass.equals("password") ){
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}
As #MadProgrammer pointed out that equals() is a case sensitive method.
"password1" is NOT EQUAL to "PASSWORD1" //The strings should match with case.
Also to avoid NullPointerException a better way is
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if ("username".equals(user) && "password".equals(pass)) {
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}

sign-up form validations in java

i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.

Java - Storing Names in ArrayList and Using it to Login

I have a task to do which involves asking the user to input their last name and giving the user an account number to login to the program. I have listed the steps below which might make more sense.
1) User creates an account
2) User enters their last name (Stores into the arraylist)
3) User is given an account number (Stores into the arraylist)
4) User can then login using their last name and account number (checks arraylist for lastname and accountnumber, if it matches then login message, if it doesnt then error message)
A user enters their last name and they are given an account number which they then use to login to deposit, withdraw and check balance.
How do i create a programe to do this without the use of database?
Account Class
private static int number = 500;
Account(){
accountNumber = number++;
}
Create Account
public void createAccount(){
String firstName;
System.out.print("Please Enter Last Name: ");
lastName = scanner.nextLine();
System.out.println("This is your Account Number to log into: " + _______ );
}
public void logIn(){
System.out.println("Please enter your last name: ");
System.out.println("Please enter your account number: ");
}
I would like to suggest another method using xml to store credentials follow the steps below
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username;
string pwd;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = Login1.UserName;
pwd = Login1.Password;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load(Server.MapPath("Register.xml"));
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "Name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "Password")
{
if (xmln.InnerText == pwd)
{
CurrentPwd = pwd;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("welcome.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
in your xml file
<user>
<Name>smashcode</Name>
<Password>smashcode</Password>
</user>
I guess this would be better approach than a arraylist approach
if you want to try in using arraylist follow steps
step1:username_list{uesr1,user2,user3}
password_List{pass1,pass2,pass3}
step:check all entries with entered userid and password in a loop as follows
int flag = 0;
while(username_list.get(i)!=null)
{
if((username_list.get(i).equals(enteredusername))&&((password_list.get(i).equals(enteredpassword)))
{
flag = 1;
}
}
if(flag==1)
{
System.out.println("login successful ");
Response.Redirect("welcome.aspx");
}
I had written second code implementation in cut short
Hope my work will be helpful.Keep coding
Not a full answer here but a few suggestions....
You could create a "bank" class... It might hold the arraylist of accounts, also holding
createAccount()
delAccount()
findAccount()...
So on and so forth
Having posted this I now see it is an answer, my bad guys
I assume you need to be able to keep this information after the execution is complete, which means you need to store the information somewhere besides the running program.
Of the top of my head, you can use a file to store this store of information, where each line of the file would equal a match of last name - account. When opening the program, you read the file. Try reading:
http://www.tutorialspoint.com/java/java_files_io.htm or
https://docs.oracle.com/javase/tutorial/essential/io/file.html
The solution is similar to using a database, so I don't know if it will do or not. Hope it does.

How do I fix a java.lang.NumberFormatException: for String " " in my servlet?

I keep running into the same error after trying to parse a String parameter I pulled from a corresponding jsp and make them into an integer and a float. In my web application I have java classes where the values I'm trying to parse are an integer and a float, but I can't seem to find a way to parse them and have my servlet work the way I'd like it to. Here's the code I used in my servlet:
//get Parameter from newStudentPage.jsp
String id = request.getParameter("stuId");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String street = request.getParameter("street");
String city = request.getParameter("city");
String state = request.getParameter("state");
String zip = request.getParameter("zip");
String email = request.getParameter("email");
String gpa = request.getParameter("gpa");
int Zip = Integer.valueOf(zip);
float GPA = Float.parseFloat(gpa);
//Use RequestDispatcher to forward to jsp's
RequestDispatcher rd = request.getRequestDispatcher("newStudentLoginPage.jsp");
RequestDispatcher rd2 = request.getRequestDispatcher("newStudentSectionAddDrop.jsp");
//Create Student object and fill with paramater data
Student s2 = new Student();
s2.setstuId(id);
s2.setfName(fName);
s2.setlName(lName);
s2.setstreet(street);
s2.setcity(city);
s2.setstate(state);
s2.setzip(Zip);
s2.setemail(email);
s2.setgpa(GPA);
//Put Student object into Session
HttpSession ses2 = request.getSession();
ses2.setAttribute("s2", s2);
if(id.equals("")||fName.equals("")||lName.equals("")||street.equals("")||city.equals("")||state.equals("")||zip.equals("")||email.equals("")||gpa.equals("")){
rd.forward(request, response);
}else{
rd2.forward(request, response);
}
Can anyone please offer my some insight to what I'm doing wrong?
One or all of these lines can cause the exception:
int Zip = Integer.valueOf(zip);
float GPA = Float.parseFloat(gpa);
You need to check if String zip or gpa can always be converted into a number. What if the user enters nothing, i.e "", " "or a non-number like seven777 ? Those conditions will cause a NumberFormatException.
You should catch the exception and do something, i.e. provide a default value, ask the user to enter a valid value, etc...
Float floatGpa = null;
try {
floatGpa = Float.parseFloat(gpa);
} catch (NumberFormatException e) {
//do something
}

Why doesn't this .equals() work?

I'm working in Eclipse (Android). In the following blocks, EmployeeInt and RestaurantInt are data types and query() opens a connection to the database and parses the results. When I print the query results, I get identical strings, but the boolean is still false. I've tried trimming the strings, but that didn't help.
public boolean verifyEmployee(String email, String password) {
ArrayList<EmployeeInt> employeeEmailID = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
ArrayList<EmployeeInt> employeePasswordID = query("SELECT employeeID FROM employees WHERE password = \'"+password+"\'");
String stringEmployeeEmailID = employeeEmailID.toString();
String stringEmployeePasswordID = employeePasswordID.toString();
if(stringEmployeeEmailID.equals(stringEmployeePasswordID)) {
return true;
} else {
return false;
}
}
Executing the above gives me false, while executing the following block (virtually identical) gives me true.
public boolean verifyRestaurant(String email, String password) {
ArrayList<RestaurantInt> restaurantEmailID = query("SELECT restaurantID FROM restaurants WHERE emailAddress = \'"+email+"\'");
ArrayList<RestaurantInt> restaurantPasswordID = query("SELECT restaurantID FROM restaurants WHERE password = \'"+password+"\'");
String stringRestaurantEmailID = restaurantEmailID.toString();
String stringRestaurantPasswordID = restaurantPasswordID.toString();
if(stringRestaurantEmailID.equals(stringRestaurantPasswordID)) {
return true;
} else {
return false;
}
}
Can anyone point out my mistake?
EDIT
I changed it to this and it worked:
public boolean verifyEmployee(String email, String password) {
ArrayList<EmployeeInt> employeeEmailID = query("SELECT * FROM employees WHERE emailAddress = \'"+email+"\'");
ArrayList<EmployeeInt> employeePasswordID = query("SELECT * FROM employees WHERE password = \'"+password+"\'");
int intEmployeeEmailID = employeeEmailID.get(0).getID();
int intEmployeePasswordID = employeePasswordID.get(0).getID();
if(intEmployeeEmailID==intEmployeePasswordID) {
return true;
} else {
return false;
}
}
I know I could also use return (condition), but I would like to add some messages if the login fails, something like:
System.err.println("email address and password do not correspond");
I'm not making an app to publish, it's merely for an assignment. Thanks for the help!
You are calling toString() on an ArrayList. Two different ArrayList objects will return two different toString() strings. You probably meant to get the first element of the ArrayList, and convert THAT to a string.
Example
EmployeeInt is your custom object. In my example, I assume it has some int field that can be retreived with getID().
ArrayList<EmployeeInt> idList = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
int ID = idList.get(0).getID();
stringEmployeeEmailID = String.valueOf(ID);
This may be easier to read than code:
query() returns an ArrayList
We extract the first element of the ArrayList - this is the part you left out
We get the ID of that element
We convert it to a String

Categories

Resources