Saturday, December 28, 2013

Spring MVC Annotations Login Example

Steps in NetBeans:
--------------------

1)File->NewProject->Java Web->Web Application->Provide Webapplication Name
   I have given name as jlwebdec

2)Right click on jlwebdec project ->Libraries->Add Library->Spring Framework 3.2.3.release
   ->Add Library

3)Also add ojdbc.jar,commons-dbcp-1.4.jar.

4)Spring libraries image



5)Project Structure




6)Copy following content in to required places....as show in the above picture
login.jsp
---------
<%--
    Document   : login
    Created on : Dec 28, 2013, 4:52:03 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="jquery-1.8.0.min.js">
           
        </script>
        <script>
$(document).ready(function(){
  $("#login").click(function(){
  
        var uname =$("#uname").val();
        var pwd = $("#pwd").val();
      
        if(uname == null || pwd == ''){
            alert("Please enter user name ");
            $("#uname").focus();
           
        }else if(pwd == null || pwd ==''){
            alert("please enter password ");     
            $("#pwd").focus();
        }
       
  });
});
</script>
       
    </head>
    <body>
       
        <form action="login.spring">
           
            <table >
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="uname" id="uname" /></td>
                   
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="text" name="pwd" id="pwd" /></td>
                   
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Login" id="login"></input></td>
                   
                </tr>
               

               
            </table>
           
           
           
        </form>
       
       
    </body>
</html>


b)userHome.jsp

<%--
    Document   : userHome
    Created on : Dec 28, 2013, 11:34:34 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Success Login Page</h1>
    </body>
</html>


c)applicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd

" >

   
   
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="oracle.jdbc.driver.OracleDriver"
        p:url="jdbc:oracle:thin:@localhost:1521:XE"
        p:username="hr" p:password="hr" /> 
   
    <bean id="jdbcTemplate" c:_0-ref="dataSource"
      class="org.springframework.jdbc.core.JdbcTemplate"/>
   
      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
   
    <context:component-scan base-package="org.jl"/>
         
          
  </beans>

d)web.xml

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









e)LoginController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.controllers;

import org.jl.dao.UserDAOI;
import org.jl.vo.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Rishitha
 */
@Controller
public class LoginController {
   
   @Autowired
   UserDAOI userDAO;
  
   
  @RequestMapping("/login.spring")
  public String handle(UserDetails command ) throws Exception{
      System.out.println("HAI HELLO ");
      boolean flag = userDAO.validate(command);
      System.out.println(flag);
      if(!flag){
          return "/login.jsp";
      }else{
          return "/userHome.jsp";
      }
     
     
  }
   
   
 
}


f)UserDAOI.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.dao;

import org.jl.vo.UserDetails;

/**
 *
 * @author Rishitha
 */
public interface UserDAOI {
   
    public  boolean validate(UserDetails user );
   
   
}

g)UserDAO.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.jl.vo.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Rishitha
 */
@Repository
public class UserDAO  implements UserDAOI{
    @Autowired
    private JdbcTemplate jdbcTemplate;
   
    public boolean validate(final UserDetails user) {
        System.out.println(" "+user.getUname() + " "+user.getPwd());
        ResultSetExtractor<Boolean> rse =  new ResultSetExtractor<Boolean>(){
          
            @Override
            public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException {
                if(rs.next()){
                    System.out.println("login success ");
                    return true;
                   
                }
               
                return false;
            }
          } ;
           
        return jdbcTemplate.query("SELECT 1 FROM javalearners WHERE jlfname=? AND jllname=? ",
                new Object[]{user.getUname(),user.getPwd()},rse);
       
       
       
    }

   
   
}

h)UserDetails.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.vo;

/**
 *
 * @author Rishitha
 */
public class UserDetails {
    private String uname;
    private String pwd;
   
    public UserDetails(){
       
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
   
   
}


You have to add the jquery javascript file...

DBSection
------------
create table javalearners(jlid number,jlfname varchar2(100),jllname varchar2(100),
jldob date );
Sample Insert Script
----------------------------

insert into javalearners values(1,'Anil','Kumar',null);





That is all for now......Hope you enjoyed my first example on Spring MVC with annotations
Please comment for any suggestions or doubts.. hope I can help you :)