Thursday 17 December 2020

Spring MVC login Example using Spring jdbcTemplate

Project Code Structure
Following screenshot shows the structure of the project we will create.













Create POM.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ramsis</groupId>

  <artifactId>springmvcjdbctemplate</artifactId>

  <packaging>war</packaging>

  <version>0.0.1-SNAPSHOT</version>

  <name>springmvcjdbctemplate Maven Webapp</name>

  <url>http://maven.apache.org</url>

  

   <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <spring.version>5.2.4.RELEASE</spring.version>

    <junit.version>4.12</junit.version>

    <servlet.version>3.1.0</servlet.version>

    <java.version>1.8</java.version>

    <mysql.connector.version>8.0.17</mysql.connector.version>

  </properties>

  

 <dependencies>

    <!-- Junit -->

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>${junit.version}</version>

      <scope>test</scope>

    </dependency>


    <!-- Spring Framework -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-core</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-beans</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-context</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-jdbc</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-test</artifactId>

      <version>${spring.version}</version>

      <scope>test</scope>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-webmvc</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <!-- MySQL database driver -->

    <dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

      <version>${mysql.connector.version}</version>

    </dependency>


    <!-- Servlet API -->

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>javax.servlet-api</artifactId>

      <version>${servlet.version}</version>

    </dependency>

    

    <!-- https://mvnrepository.com/artifact/jstl/jstl -->

<dependency>

    <groupId>jstl</groupId>

    <artifactId>jstl</artifactId>

    <version>1.2</version>

</dependency>

    

  </dependencies>

  <build>

    <finalName>springmvcjdbctemplate</finalName>

  </build>

</project>




------------------------------------------------------------------------------------

user-beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

  xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  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">


  <context:component-scan base-package="com.ramsis.springmvcjdbctemplate" />

  <context:annotation-config />


  <bean id="userService" class="com.ramsis.springmvcjdbctemplate.service.UserServiceImpl" />

  <bean id="userDao" class="com.ramsis.springmvcjdbctemplate.dao.UserDaoImpl" />


  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

    <property name="dataSource" ref="datasource" />

  </bean>


  <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />

    <property name="url" value="jdbc:mysql://qadbserver.cqlzbbt51la6.ap-south-1.rds.amazonaws.com:3306/anjni_testing" />

    <property name="username" value="root" />

    <property name="password" value="admin" />

  </bean>


</beans>


-------------------------------------------------------------------------------------

LoginController.java



package com.ramsis.springmvcjdbctemplate.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;
import com.ramsis.springmvcjdbctemplate.service.UserService;

@Controller
public class LoginController {

  @Autowired
  UserService userService;

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("login");
    mav.addObject("login", new Login());

    return mav;
  }

  @RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
  public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,HttpSession session,
      @ModelAttribute("login") Login login) {
    ModelAndView mav = null;

    User user = userService.validateUser(login);

    if (null != user) {
      mav = new ModelAndView("welcome");
      session.setAttribute("username", user.getFirstname());
      mav.addObject("firstname", user.getFirstname());
    } else {
      mav = new ModelAndView("login");
      mav.addObject("message", "Username or Password is wrong!!");
    }

    return mav;
  }
 
  @RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpSession session) {
 ModelAndView mav = new ModelAndView("login");
 session.removeAttribute("username");
 mav.addObject("login", new Login());
 return mav;
}

}

--------------------------------------------------------------------------------------

RegistrationController.java


package com.ramsis.springmvcjdbctemplate.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ramsis.springmvcjdbctemplate.modal.User;
import com.ramsis.springmvcjdbctemplate.service.UserService;

@Controller
public class RegistrationController {
  @Autowired
  public UserService userService;

  @RequestMapping(value = "/register", method = RequestMethod.GET)
  public ModelAndView showRegister(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("register");
    mav.addObject("user", new User());

    return mav;
  }

  @RequestMapping(value = "/registerProcess", method = RequestMethod.POST)
  public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,
      @ModelAttribute("user") User user) {
    userService.register(user);
    return new ModelAndView("welcome", "firstname", user.getFirstname());
  }
 
 
  @RequestMapping(value = "/dashBoard", method = RequestMethod.GET)
  public ModelAndView dashBoard(HttpServletRequest request, HttpServletResponse response,HttpSession session) {
    ModelAndView mav = null;

     String user = (String) session.getAttribute("username");
     System.out.println("Session User : "+user);
    if (null != user) {
      mav = new ModelAndView("welcome");
      mav.addObject("firstname", user);
    } else {
      mav = new ModelAndView("login");
      mav.addObject("message", "Username or Password is wrong!!");
    }
    return mav;
  }
 
  @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
  public String getAllEmployees(Model model)
  {
      model.addAttribute("user", userService.getAllUsers());
      return "userListDisplay";
  }
 
}



---------------------------------------------------------------------------------------------


UserDao.java


package com.ramsis.springmvcjdbctemplate.dao;

import java.util.List;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public interface UserDao {

  int register(User user);

  User validateUser(Login login);
 
  List<User> getAllUsers();
}


----------------------------------------------------------------------------------------------


UserDaoImpl.java


package com.ramsis.springmvcjdbctemplate.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public class UserDaoImpl implements UserDao {

  @Autowired
  DataSource datasource;

  @Autowired
  JdbcTemplate jdbcTemplate;

  public int register(User user) {
    String sql = "insert into users(username,password,firstname,lastname,email,address,phone) values(?,?,?,?,?,?,?)";

    return jdbcTemplate.update (sql, new Object[] {user.getUsername(), user.getPassword(), user.getFirstname(),
        user.getLastname(), user.getEmail(), user.getAddress(), user.getPhone() });
  }

  public User validateUser(Login login) {
    String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
        + "'";
    List<User> users = jdbcTemplate.query(sql, new UserMapper());

    return users.size() > 0 ? users.get(0) : null;
  }

public List<User> getAllUsers() {

String sql = "select username,password,firstname,lastname,email,address,phone from users";
    List<User> users = jdbcTemplate.query(sql, new UserMapper());

    return users;
}

}

class UserMapper implements RowMapper<User> {

  public User mapRow(ResultSet rs, int arg1) throws SQLException {
    User user = new User();

    user.setUsername(rs.getString("username"));
    user.setPassword(rs.getString("password"));
    user.setFirstname(rs.getString("firstname"));
    user.setLastname(rs.getString("lastname"));
    user.setEmail(rs.getString("email"));
    user.setAddress(rs.getString("address"));
    user.setPhone(rs.getInt("phone"));

    return user;
  }
}



--------------------------------------------------------------------------------------------


Login.java


package com.ramsis.springmvcjdbctemplate.modal;


public class Login {


  private String username;

  private String password;

  

  


  public String getUsername() {

    return username;

  }


  public void setUsername(String username) {

    this.username = username;

  }


  public String getPassword() {

    return password;

  }


  public void setPassword(String password) {

    this.password = password;

  }


}


--------------------------------------------------------------------------------------------


User.java


package com.ramsis.springmvcjdbctemplate.modal;


public class User {

  private Integer id;

  private String username;

  private String password;

  private String firstname;

  private String lastname;

  private String email;

  private String address;

  private Integer phone;

  

  public Integer getId() {

return id;

 }


  public void setId(Integer id) {

this.id = id;

 }


public String getUsername() {

    return username;

  }


  public void setUsername(String username) {

    System.out.println("username: " + username);

    this.username = username;

  }


  public String getPassword() {

    return password;

  }


  public void setPassword(String password) {

    this.password = password;

  }


  public String getFirstname() {

    return firstname;

  }


  public void setFirstname(String firstname) {

    System.out.println("firstname: " + firstname);

    this.firstname = firstname;

  }


  public String getLastname() {

    return lastname;

  }


  public void setLastname(String lastname) {

    System.out.println("lastname: " + lastname);

    this.lastname = lastname;

  }


  public String getEmail() {

    return email;

  }


  public void setEmail(String email) {

    this.email = email;

  }


  public String getAddress() {

    return address;

  }


  public void setAddress(String address) {

    this.address = address;

  }


  public Integer getPhone() {

    return phone;

  }


  public void setPhone(Integer phone) {

    this.phone = phone;

  }

}


--------------------------------------------------------------------------------------------


UserService.java


package com.ramsis.springmvcjdbctemplate.service;

import java.util.List;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public interface UserService {

  int register(User user);

  User validateUser(Login login);
  public List<User> getAllUsers();
}


---------------------------------------------------------------------------------------------


UserServiceImpl.java



package com.ramsis.springmvcjdbctemplate.service;

import java.util.ArrayList;
import java.util.List;

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

import com.ramsis.springmvcjdbctemplate.dao.UserDao;
import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public class UserServiceImpl implements UserService {

  @Autowired
  public UserDao userDao;

  public int register(User user) {
    return userDao.register(user);
  }

  public User validateUser(Login login) {
    return userDao.validateUser(login);
  }


public List<User> getAllUsers() {

List<User> userList = new ArrayList<User>();
User user1;
  for(User user2 : userDao.getAllUsers()) {
    user1 = new User();
  user1.setPhone(user2.getPhone());
  user1.setAddress(user2.getAddress());
  user1.setEmail(user2.getEmail());
  user1.setFirstname(user2.getFirstname());
  user1.setLastname(user2.getLastname());
  user1.setUsername(user2.getUsername());
  userList.add(user1);
  }
 
return (List<User>) userList;
}

}


--------------------------------------------------------------------------------------------


Download Code





No comments:

Post a Comment