Total Pageviews

Wednesday, May 29, 2013

Spring MVC 3 login Example With Database MySql using Session


This is the Example of Spring MVC 3 Login and Log Out Example With Database MySql using Session (Take Help from many Websites.) The Log OUT works only in Mozilla Firefox.. This project is build in Netbeans IDE 7.2.1







dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- declare mvc to be annotation driven -->
<!--<mvc:annotation-driven/>-->
<context:annotation-config />
<!-- provide Your Base package to scan annotations for components -->
<context:component-scan base-package="com.lalit" />

<!-- Configuration for View page resolver.here we are using jsp pages -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- DataSource configuration of database -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/lalit" />
<property name="username" value="root" />
<property name="password" value="12345" />
</bean>
</beans>


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" id="WebApp_ID" version="2.5">
  <display-name>Spring-Mvc-Login-Demo</display-name>
  <welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  <!-- make sure servlet-name is same as in <servlet> configuration -->
    <servlet-name>dispatcher</servlet-name>
    <!-- only url's with extension mentioned in url-pattern 
    will be directed to spring controller -->
    <url-pattern>*.obj</url-pattern>
  </servlet-mapping>
</web-app>


UserBean.java

package com.lalit.bean;

import java.io.Serializable;

import org.hibernate.validator.constraints.NotEmpty;

public class UserBean implements Serializable{
private static final long serialVersionUID = 4657462015039726030L;
//spring validation 
@NotEmpty(message="UserId cannot be empty")
private String userId;
@NotEmpty(message="Password cannot be empty")
private String password;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

CombatController.java

package com.lalit.controller;


import javax.validation.Valid;

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

import com.lalit.bean.UserBean;
import com.lalit.service.ICombatService;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("Sess_Var")

public class CombatController {

@Autowired
private ICombatService combatService;

public void setCombatService(ICombatService combatService) {
this.combatService = combatService;
}

public ICombatService getCombatService() {
return combatService;
}

                @RequestMapping("/index")
public String index(Model model){
//make sure to add model of UserBean in which login 
//userName and password will be stored from the login-form 
model.addAttribute("userBean", new UserBean());
//"login" will be resolved to login.jsp
//where login-form is presented to user
return "index";
}

                        
        @RequestMapping("/Next")
public String Next1(Model model){
//make sure to add model of UserBean in which login 
//userName and password will be stored from the login-form 
model.addAttribute("userBean", new UserBean());
//"login" will be resolved to login.jsp
//where login-form is presented to user
return "Next";
}
                
                        
                 @RequestMapping("/Log")
public String Log(Model model,HttpSession session){

              model.addAttribute("userBean", new UserBean());
              session.invalidate();
              
//"login" will be resolved to login.jsp
//where login-form is presented to user
//                 sessionStatus.setComplete();  
//              sessionStatus.setComplete();  
return "LogOut";
}

        
@RequestMapping("/toLogin")
public String toLogin(Model model,HttpSession session){
//make sure to add model of UserBean in which login 
//userName and password will be stored from the login-form 
model.addAttribute("userBean", new UserBean());
                session.invalidate();
//"login" will be resolved to login.jsp
//where login-form is presented to user
return "login";
}

@RequestMapping("/doLogin")
public ModelAndView doLogin(@ModelAttribute @Valid UserBean userBean,BindingResult result,HttpSession session){
ModelAndView view = new ModelAndView("login");
//             String var=  userBean.getUserId();
                
//if input bean does not have validation error then proceed
if(!result.hasFieldErrors()){
//if not a valid user then add error
//else proceed to user welcome page
if(!combatService.authenticateUser(userBean)){
result.addError(new ObjectError("err", "Invalid Credentials"));
}
else{
                            session.setAttribute("Sess_Var", userBean.getUserId());
//                            view.addObject("Sess_Var", var);
                      view.setViewName("welcome");
}
}
return view;
}
}


CombatDAO.java

package com.lalit.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;

import com.lalit.bean.UserBean;

@Component
public class CombatDAO implements ICombatDAO {

private SimpleJdbcTemplate simpleJdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource){
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
public boolean authenticateUser(UserBean userBean){
boolean userExists = false;
/* Provide table name and column name carefully in the sql query below.
* here i have a table "userbean" with two column's
* "userId" and "password" both of varchar2 type.
*/
int rowcount = simpleJdbcTemplate.queryForInt("select count(*) from userbean " +
" where userId = ? and password = ?",
userBean.getUserId(),userBean.getPassword());
if(rowcount==1){
userExists = true;
}
return userExists;
}

}

ICombatDAO.java

package com.lalit.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import com.lalit.bean.UserBean;

public interface ICombatDAO {

@Autowired
public abstract void setDataSource(DataSource dataSource);

public abstract boolean authenticateUser(UserBean userBean);

}


CombatService.java

package com.lalit.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lalit.bean.UserBean;
import com.lalit.dao.ICombatDAO;

@Component
public class CombatService implements ICombatService {

@Autowired
private ICombatDAO combatDAO;
public void setCombatDAO(ICombatDAO combatDAO) {
this.combatDAO = combatDAO;
}
public ICombatDAO getCombatDAO() {
return combatDAO;
}
public boolean authenticateUser(UserBean userBean){
return combatDAO.authenticateUser(userBean);
}
}

ICombatService.java

package com.lalit.service;

import com.lalit.bean.UserBean;

public interface ICombatService {

public abstract boolean authenticateUser(UserBean userBean);

}

redirect.jsp

<%--
Views should be stored under the WEB-INF folder so that
they are not accessible except through controller process.

This JSP is here to provide a redirect to the dispatcher
servlet but should be the only JSP outside of WEB-INF.
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("index.obj"); %>



index.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Mvc Login Demo</title>
<!--<link href="style.css" rel="stylesheet" type="text/css" />-->
</head>
<body>
    <%        
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setDateHeader("Expires",0);
%>
<div class="content">
<fieldset>
<legend>Navigation menu</legend>

<!-- here the href's value will be used to decide the method from
  controller to be executed on click of this link-->
<a href="toLogin.obj" style="margin:50;">Login</a>
</fieldset>
</div>
</body>
</html>

login.jsp

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <%        
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setDateHeader("Expires",0);
%>

<div class="content">
<fieldset>
<legend>Navigation menu</legend>
<a href="index.jsp">Home</a>
<!-- here the action's value will be used to map the corresponding 
method in controller needs to be executed on form submit.
modelAttribute value should be camelCase name of bean 
added earlier as model in spring controller
 -->
<sf:form action="doLogin.obj" modelAttribute="userBean">
<!-- to display error message from action method if any -->
<sf:errors /><br />
<sf:label path="userId">UserName:</sf:label>
<sf:input path="userId" /><br />
<!-- to display validation error message if any -->
<sf:errors path="userId" /><br />
<sf:label path="password">Password:</sf:label>
<sf:password path="password" /><br />
<sf:errors path="password" /><br />
<input type="submit" value="Login" /><br />"
</sf:form>
</fieldset>
</div>
</body>
</html>

Welcome.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Home Page</title>
<!--<link href="style.css" rel="stylesheet" type="text/css" />-->
</head>
<body>
  <%        
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setDateHeader("Expires",0);
%>
<c:if test="${empty Sess_Var}">
 <%
   response.sendRedirect("toLogin.obj");
  %>  
 </c:if> 

<div class="content">
<fieldset>
<legend>First Welcome Page</legend>
<a href="index.jsp">Home</a>
<br /><br />
<h2>User page</h2>
<br/>
<!-- display the userId just logged in -->


go to next page
<a href="Next.obj">Next 2 page</a>
Hello  user here  
${Sess_Var}
</fieldset>
</div>
</body>
</html>

Next.jsp

<%-- 
    Document   : Next
    Created on : May 29, 2013, 7:50:54 AM
    Author     : Love
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@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>
 <%        
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setDateHeader("Expires",0);
%>
<c:if test="${empty Sess_Var}">
 <%
   response.sendRedirect("toLogin.obj");
  %>  
 </c:if>

  <h1>In Second Welcome Page</h1>
        <a href="Log.obj">LOG OUT  </a>
       ${Sess_Var}
    </body>
</html>

LogOut.jsp

<%-- 
    Document   : LogOut
    Created on : May 29, 2013, 8:00:09 AM
    Author     : Love
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@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>
      <%        
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setDateHeader("Expires",0);
%>
<c:if test="${empty Sess_Var}">
    <%
   response.sendRedirect("toLogin.obj");
  %> 
</c:if>
           <h1>Hello World!</h1>
        ${Sess_Var}
    </body>
</html>

log4j.properties

# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=basicspring.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n


style.css

label,span,input{margin:5px;padding:5px;}
span{color:red;}
.content{width:400px;margin:auto;text-align:center;
margin-top:200px;box-shadow:0.4em 0.4em 0.6em #611;}
.fieldset{border-radius:10px;}

Will Try to Provide Download Link Also



2 comments:

  1. hibernate configuration file missing

    ReplyDelete
  2. Hey its better if you show the demo and also source code in github or something

    ReplyDelete