Saturday, 10 October 2015

Module 1.. User Login Validation

In our last blog (http://productdesignsagain.blogspot.com/2015/09/module-1adding-email-notification-on.html) we created a module to save User Master data. In this module we are going to create "login" module, in which, if the user credentials are valid, user is redirected to "login successful page" else back to index page with error message. I will show this as a solo module and then in the later blogs, i will be clubbing all the options in a menu page. Jars are same as shown in the project structure in this link( http://lillbitofeverythingagain.blogspot.in/2015/07/simple-spring-login.html ).

Project Structure:


web.xml
--------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>sdnext</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>sdnext</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
</web-app>

sdnext-servlet.xml
--------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">

 <context:property-placeholder location="classpath:resources/database.properties" />
 <context:component-scan base-package="com.users" />
 <mvc:annotation-driven/>

<mvc:resources mapping="/js/**" location="/js" />

 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>

  <mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="prefixJson" value="true"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${database.driver}" />
  <property name="url" value="${database.url}" />
  <property name="username" value="${database.user}" />
  <property name="password" value="${database.password}" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.users.model.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
   </props>
  </property>

 </bean>

 <bean id="hibernateTransactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
  </property>
  <property name="messageConverters">
    <list>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </list>
  </property>
</bean>

</beans>


UserController.java
--------------------------------------------

package com.users.controller;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.users.bean.UserBean;
import com.users.model.User;
import com.users.service.UserService;


@Controller
public class UserController {

 @Autowired
 private UserService userService;
 

 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public ModelAndView saveUser( @ModelAttribute("user") UserBean u1, BindingResult result) {
  User u = prepareModel(u1);
System.out.println("1");
  userService.addUser(u);

 // mail m = new mail(u1.getEmail_id());
  System.out.println("2");
  return new ModelAndView("save");
 }


 @RequestMapping(value = "/login2", method = RequestMethod.POST)
 public ModelAndView login( @ModelAttribute("user") UserBean u1, BindingResult result) {

System.out.println("In controller");
Map<String, Object> model = new HashMap<String, Object>();
try
{
System.out.println("a");
User u = userService.validateUser(u1.getEmail_id(), u1.getPassword());
if(u.getEmail_id().equalsIgnoreCase("null"))
return new ModelAndView("notsave");


}
catch(Exception e)
{

}


return new ModelAndView("save");

 }


 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public ModelAndView welcome(@ModelAttribute("user") UserBean u1, BindingResult result) {


  return new ModelAndView("login");
 }





 private User prepareModel(UserBean uBean){
  User u1 = new User();
  u1.setPassword(uBean.getPassword());
  u1.setEmail_id(uBean.getEmail_id());
  u1.setUser_id(uBean.getUser_id());
  uBean.setUser_id(null);
  return u1;
 }


}

login.jsp
--------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>

<h2>New User Master Data</h2>
  
  <form:form method="POST" action="login2.html" modelAttribute="user" id="form">
  
<table>
    <tr><td>  <form:input path="user_id" placeholder="User ID:" value="" disabled="true"/></td></tr>
    
        <tr><td><form:input path="email_id" placeholder="Email ID:" value="" /></td></tr>
    <tr> <td> <form:password path="password" placeholder="Password" value="" /> </td></tr>
    
    
    </table> 
 <input type="submit" value="Log-in"/>
  </form:form>
</body>  

</html>

UserBean.java
--------------------------------

package com.users.bean;
import java.util.Date;

import com.ibm.icu.util.Calendar;

public class UserBean {
 private Integer user_id;
 private String email_id;
 private String password;
 public Integer getUser_id() {
  return user_id;
 }
 public void setUser_id(Integer user_id) {
  this.user_id = user_id;
 }
 public String getEmail_id() {
  return email_id;
 }
 public void setEmail_id(String email_id) {
  this.email_id = email_id;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }

}


User.java
------------------------

package com.users.model;

import java.io.Serializable;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="users")
public class User implements Serializable{

 private static final long serialVersionUID = -723583058586873479L;
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 @Column(name = "user_id")
 private Integer user_id;

 public static long getSerialversionuid() {
  return serialVersionUID;
 }

 @Column(name = "email_id")
 private String email_id;
 @Column(name="password")
 private String password;

 public Integer getUser_id() {
  return user_id;
 }

 public void setUser_id(Integer user_id) {
  this.user_id = user_id;
 }

 public String getEmail_id() {
  return email_id;
 }

 public void setEmail_id(String email_id) {
  this.email_id = email_id;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }





}


UserService.java
-----------------------------------

package com.users.service;

import java.util.List;

import com.users.model.User;


public interface UserService {
 public void addUser(User user);
 public User validateUser(String uid, String password);
}


UserServiceImpl.java
---------------------------------------

package com.users.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.users.dao.UserDao;
import com.users.model.User;

@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao uDao;
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
 public void addUser(User user) {
System.out.println("3");
  uDao.addUser(user);
 }

@Override
public User validateUser(String uid, String password) {
System.out.println("b");
return uDao.validateUser(uid, password);
}


}

UserDao.java
---------------------------------

package com.users.dao;

import java.util.List;

import com.users.model.User;
import com.users.model.User;
public interface UserDao {
 public void addUser(User user);
 public User validateUser(String uid, String password);
}

UserDaoImpl.java
---------------------------------

package com.users.dao;

import java.sql.Array;
import java.util.List;
import java.util.Map;

import javax.jms.Session;
import javax.management.Query;
import javax.resource.cci.ResultSet;

import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.users.bean.UserBean;
import com.users.model.User;


@Repository("uDao")
public class UserDaoImpl implements UserDao {

 @Autowired
 private SessionFactory sessionFactory;
 int k;
 public void addUser(User user) {
System.out.println("4");
  sessionFactory.getCurrentSession().save(user);
 }
@SuppressWarnings("finally")
public User validateUser(String email_id, String password)
{
System.out.println("cccc");
User l1 = new User();
try
{


System.out.println("cc1111");
String sql = "SELECT  user_id FROM USERS WHERE email_id = :email_id and password = :password";
SQLQuery query =  sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setParameter("password",password);  
query.setParameter("email_id",email_id); 

int u1 = (Integer) query.uniqueResult();
k = u1;
System.out.println(u1);



System.out.println("d");

}
catch(Exception e)
{
if(k==0)
{
l1.setEmail_id("null");
l1.setPassword("null");
}
}
finally
{
System.out.println(l1.getEmail_id());
return l1;
}
}

}
database.properties
-------------------------------

database.driver=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/PMS
database.user=postgres
database.password=12345
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create


save.jsp
-------------------
/* (to go with the real meaning, you can rename it to success.jsp, here i am just modifying code from last blog so i have let the name save.jsp remain, but we are not saving any data here. If you change it to "success.jsp" here, you must accordingly change controller class)..*/

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<body>
<% out.print("Logged in."); %>
</body>
</html>

notsave.jsp
----------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>

<h2 style="color:red">Incorrect Credentials, please try again</h2>
  
  <form:form method="POST" action="login2.html" modelAttribute="user" id="form">
  
<table>
    <tr><td>  <form:input path="user_id" placeholder="User ID:" value="" disabled="true"/></td></tr>
    
        <tr><td><form:input path="email_id" placeholder="Email ID:" value="" /></td></tr>
    <tr> <td> <form:password path="password" placeholder="Password" value="" /> </td></tr>
    
    
    </table> 
 <input type="submit" value="Log-in"/>
  </form:form>
</body>  

</html>


Login page
-----------------

(Typing in existing uid and password)


Login successful..


Login page with wrong uid and password
-------------------------------------------------------------

Redirect to login unsuccessful page




No comments:

Post a Comment