0

Its spring MVC app with Hibernate.

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public boolean save(User user) {

        return userDao.save(user);
    }

    @Override
    public void update(User user) {

        userDao.update(user);

        // return this.userDao.update(user);
    }

    @Override
    @Transactional
    public User findById(int id) {

        return this.userDao.findById(id);
    }

    @Override
    @Transactional
    public List<User> listPersons() {

        return this.userDao.listPersons();
    }

    @Override
    @Transactional
    public User deleteUser(int id) {

        return userDao.deleteUser(id);
    }

    public boolean validateUser(int id) {

        List<User> list= (List<User>) findById(id); 


        return false;   


    }

    public User validateUser(User user) {   

        Session session = this.sessionFactory.getCurrentSession();

        String query = "select u.name, u.password from User as u where u.name='"+ user.getName() + "' and u.password='"
                + user.getPassword() + "'";

        session.createQuery(query);       

        ResultSet rs = (ResultSet) session.createQuery (query);

            try {
                if (rs.next()){

                    return user;
                } else
                    return user;
            } catch (SQLException e) {

                e.printStackTrace();
            }
            return user;

        }
}
My UserServiceImpl class has a method to validate the user input[ password and userID];

User logs in to a login.jsp page filling out this form:

<body>

    Welcome back!

    <br> Only Registered user can log in...
    <br>
    <br>
    <form:form action="admin" modelAttribute="user" method="POST">
        <table border="1">

            <tr>
                <td><form:label path="userId">Your Id:- </form:label></td>
                <td><form:input path="userId" /></td>
            </tr>
            <tr>
                <td><form:label path="password">Password:- </form:label></td>
                <td><form:input path="password" /></td>
            </tr>

            <tr>
                <td><form:label path="role">Select Log in role as a:- </form:label></td>
                <td><form:select path="role">
                        <form:option value="NONE" lable="---SELECT---">Please Select</form:option>
                        <form:options items="${roles}" />
                    </form:select></td>
                <td><input type="submit" value="Login" /></td>
            </tr>
        </table>
    </form:form>
</body>

The form goes to contrroller:

@RequestMapping(value = "/admin", method = RequestMethod.POST)
    public String LoggedUser(@ModelAttribute("user") User user, BindingResult result, Model model) {

        // get the role, id and pw value from jsp
        String role = user.getRole();
        String loadedPW = user.getPassword();
        String loadedUId = user.getUserId();
        // want to check password and userId here again Db
        //loadedPW.

      //directing to admin page and gen page
    if (role.equalsIgnoreCase("Admin") || role.equalsIgnoreCase("Principal")) {
            return "adminPage";         
        } else
            return "genPage";
    }

My User object is

@Entity
@Table(name = "USER")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(name = "NAME")
    private String name;
    @Column(name = "USER_ID")
    private String userId;
    @Column(name = "PASSWORD")/*    
    @NotNull(message="Please select a password")
    @Length(min=5, max=10, message="Password should be between 5 - 10 charactes")*/ 
    private String password;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "ROLE")
    private String role;

    @Column(name = "DEPARTMENT")
    private String department;
    @Column(name = "RID")
    private int rid;    
    public int getRid() {
        return rid;
    }
    public void setRid(int rid) {
        this.rid = rid;
    }   
    @ManyToOne
    @JoinTable(name = "user_roles", joinColumns = {
            @JoinColumn(name = "user_id", referencedColumnName = "id") }, inverseJoinColumns = {
                    @JoinColumn(name = "roles_id", referencedColumnName = "id") })

    /*@ManyToOne(cascade=CascadeType.ALL)*/
    public Roles roles;

    public Roles getRoles() {
        return roles;
    }
    public void setRoles(Roles roles) {
        this.roles = roles;
    }
    // no arg constructor
    public User() {
//getters and setters ........
    }

How can I validate the password and userID inputs on login.jsp against my User table? Do I have to use JDBC Resultset or there is some other better way to do validate the user inputs? I am using Hibernate 4.3x with Spring MVC 4.x .

1 Answer 1

1

How can I validate the password and userID inputs on login.jsp against my User table?

You can use spring-security module, which is very powerful for authenticating & authorizing the user requests (like in your web application) and you can find an example here

spring-security module provides various methods to configure the user details like inmemory, database, LDAP, etc.., but for your case you need to go for JDBC authentication using (AuthenticationManagerBuilder.jdbcAuthentication()).

The approach is you need to provide a configuration class by overriding methods configAuthentication() and configure() methods of WebSecurityConfigurerAdapter

Do I have to use JDBC Resultset or there is some other better way to do validate the user inputs?

No, you don't need to handle JDBC Resultset directly, rather in spring-security, you just need to provide the datasource (database access details) and sql query like select username,password from users where username=?.

You can refer here for configuring JDBC authentication.

Sign up to request clarification or add additional context in comments.

2 Comments

Spring security will not go to remote database for password validation rather stored username/password combination in configuration file itself. But i want it to act like more real time applications, where some user service fetching data from remote database.
No, you need to configure the remote database hostname, port, dbname, userid, pwd as part of datasource properties, that's it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.