2

Here I want if the user is trying to register with the code that already exists in my table then it should provide an error that

This code is already taken please try with different one.

Using Struts2 I want to do this. Below is my action class.

What I have done is: first I have fired a query for selecting code using resultset and stored all the results in a String variable temp_user and in validate() method I have just compared it using equals(temp_user) method, but it doesn't work.

RegisterAction.java

package org.entity;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.wsdl.Message;

import org.apache.struts2.interceptor.SessionAware;

import nl.captcha.Captcha;

import com.opensymphony.xwork2.ActionSupport;

public class RegistrationAction extends ActionSupport implements SessionAware {
    BloodBank register;
    private Map<String, Object> session;
    private String temp_user;

    public BloodBank getRegister() {
        return register;
    }

    public void setRegister(BloodBank register) {
        this.register = register;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public String getTemp_user() {
        return temp_user;
    }

    public void setTemp_user(String temp_user) {
        this.temp_user = temp_user;
    }

    @Override
    public String execute() throws Exception {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/foryou", "root", "siddheshkk");
            System.out.println("Driver Loaded");
            Statement st12 = con.createStatement();
            PreparedStatement st = con
                    .prepareStatement("insert into bbinfo(code,name,address,city,district,contactno,stdcode,password,aname,email) "
                            + "values(?,?,?,?,?,?,?,?,?,?)");
            st.setString(1, register.getCode());
            st.setString(2, register.getBbname());
            st.setString(3, register.getAddress());
            st.setString(4, register.getCity());
            st.setString(5, register.getDistrict());
            st.setString(6, register.getNumber());
            st.setString(7, register.getStd());
            st.setString(8, register.getPassword());
            st.setString(9, register.getAname());
            st.setString(10, register.getEmail());
            st.executeUpdate();
            st.close();

            PreparedStatement st1 = con
                    .prepareStatement("insert into stockinfo(name,city,address,contact,email,code,stdcode,apositive,anegative,bpositive,bnegative,abpositive,abnegative,opositive,onegative)"
                            + "values(?,?,?,?,?,?,?,'0','0','0','0','0','0','0','0')");
            st1.setString(1, register.getBbname());
            st1.setString(2, register.getCity());
            st1.setString(3, register.getAddress());
            st1.setString(4, register.getNumber());
            st1.setString(5, register.getEmail());
            st1.setString(6, register.getCode());
            st1.setString(7, register.getStd());
            st1.executeUpdate();
            st1.close();
            System.out.println("done");
            ResultSet rs12 = st12.executeQuery("select code from bbinfo");
            while (rs12.next()) {
                temp_user = rs12.getString("code");
            }

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    @Override
    public void validate() {
        super.validate();
        if (register.getCode().length() < 1 | register.getCode().equals("")) {
            addFieldError("register.code", "Mandatory Field.");
        }
        if(register.getCode().equals(getTemp_user()))
        {
            addFieldError("register.code", "This Code is already taken. Please try different one.");
        }
        if (register.getBbname().equals("") | register.getBbname().length() < 1) {
            addFieldError("register.bbname", "Invalid Name");
        }
        if (register.getAddress().equals("")) {

            addFieldError("register.address", "Invalid Address");
        }
        if (register.getCity().equals("")) {
            addFieldError("register.city", "Invalid City");

        }
        if (register.getDistrict().equals("")) {
            addFieldError("register.district", "Invalid District");

        }
        if (register.getPassword().length() > 8
                | register.getPassword().equals("")) {
            addFieldError("register.password", "Please Enter a valid Password");
        }
        if (!(register.getConfirm().equals(register.getPassword()))) {
            addFieldError("register.confirm", "Password doesnt match");
        }
        if (register.getConfirm().isEmpty()) {
            addFieldError("register.confirm", "Please enter confirmed password");
        }
        if (register.getAname().equals("")) {
            addFieldError("register.aname", "Please enter your name");
            ;
        }
        if (register.getEmail().equals("")) {
            addFieldError("register.email", "Invalid Email Id");
        } else {
            String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
            CharSequence inputStr = register.getEmail();
            Pattern pattern = Pattern.compile(expression,
                    Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputStr);
            if (!matcher.matches())
                addFieldError("register.email", "Invalid email address");
        }
        Captcha captcha = (Captcha) session.get(Captcha.NAME);
        if (!(captcha.isCorrect(register.getCaptchaAnswer()))) {
            addFieldError("register.captchaAnswer", "incorrect captcha");
        }

    }
}
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • How would the user know the code you selected from the table? – Roman C Jul 01 '15 at 15:45
  • yes i have got errors in the validate method where that equals condition for code begins . –  Jul 01 '15 at 16:27
  • i didnt get you roman sir . i have fetched all the records using resultset in string variable and later on i am comparing it in validation method –  Jul 01 '15 at 16:28
  • Actually i am not getting any error .user gets registered with the duplicate name too . it doesnt give any error at the required field :( –  Jul 01 '15 at 16:41
  • Please anyone help me with the solution :( –  Jul 01 '15 at 16:57

2 Answers2

2

Thanks to @Andrea Sir for Suggestion and it really helped me. :) I wrote following code in Validate() method and my code was executed Successfully. Thanks alot again sir :) and the link posted by you also cleared my concept of how interceptors should be called between and JSP and Action. :) Below is my code.

String temp_user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/foryou", "root", "siddheshkk");
            System.out.println("Step 1");
            Statement st12 = con.createStatement();
            ResultSet rs12 = st12.executeQuery("select code from bbinfo");
            while (rs12.next()) {

                temp_user = rs12.getString("code");
                System.out.println("step2");
                if (register.getCode().equals(temp_user)) {
                    addFieldError("register.code",
                            "This username is already taken .Try Different one !");
                    System.out.println("sid");
                }

            }
            st12.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
0

Your problem is that the validate() method, run by the Validation Interceptor,
is executed before reaching the action, and hence before the execute() method.

This means that temp_user is always null when read in the validate() method.

You need to learn how Struts2 works, especially when and how the Interceptors are called between the JSP and the Action.

Solution: load the temp_user variable inside the validate() method.

Also read Should I retrieve database record in Struts2 view layer? for a discussion on how to make your code cleaner and more decoupled, because all that JDBC stuff in the action is really ugly.

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Okay thanks alot sir :) but what do you mean by loading a variable in validate method ? . String temp_user; ResultSet rs12 = st12.executeQuery("select code from bbinfo"); while (rs12.next()) { temp_user = rs12.getString("code"); } Should i write this code in validate method and then compare ? –  Jul 02 '15 at 14:21
  • Exactly. In `validate()` you have the one coming from the page, but not the other that will be loaded in `execute()`. Load it in `validate()` instead that in `execute()`, if your goal is only to compare them. – Andrea Ligios Jul 02 '15 at 14:24
  • 1
    Yes Sir i will just try that and will let u know and if i succeed i will mark the answer which helped me :) –  Jul 02 '15 at 14:28