Saturday 19 December 2020

CRUD Application using Jsp Servlet and JSTL

Project Code 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" id="WebApp_ID" version="2.5">
  <display-name>JspServletJstlCrud</display-name>
 
  <servlet>
        <servlet-name>UserController</servlet-name>
        <servlet-class>com.ramsiscode.controller.UserController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserController</servlet-name>
        <url-pattern>/UserController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

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

UserController.java

package com.ramsiscode.controller;
 
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ramsiscode.dao.UserDao;
import com.ramsiscode.model.User;
 
public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listuser.jsp";
    private UserDao dao;
 
    public UserController() {
        super();
        dao = new UserDao();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forward="";
        String action = request.getParameter("action");
 
        if (action.equalsIgnoreCase("delete")){
            String userId = request.getParameter("userId");
            dao.deleteUser(userId);
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());  
        } else if (action.equalsIgnoreCase("edit")){
            forward = INSERT_OR_EDIT;
            String userId = request.getParameter("userId");
            User user = dao.getUserById(userId);
            request.setAttribute("user", user);
        } else if (action.equalsIgnoreCase("listUser")){
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else {
            forward = INSERT_OR_EDIT;
        }
 
        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setUname(request.getParameter("uname"));
        user.setPassword(request.getParameter("pass"));
        try {
            Date reg = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParameter("dob"));
            System.out.println("Date >>> "+ reg);
            user.setRegisteredon(reg);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setEmail(request.getParameter("email"));
        String userid = request.getParameter("uname");
//        if(userid == null || userid.isEmpty())
//        {
//            dao.addUser(user);
//        }
//        else
//        {
            user.setUname(userid);
            dao.checkUser(user);
//        }
        RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
        request.setAttribute("users", dao.getAllUsers());
        view.forward(request, response);
    }
}

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

UserDao.java

package com.ramsiscode.dao;
 
import java.sql.*;
import java.util.*;

import com.ramsiscode.model.User;
import com.ramsiscode.util.Database;
 
public class UserDao {
 
    private Connection connection;
 
    public UserDao() {
        connection = Database.getConnection();
    }
 
    public void checkUser(User user) {
        try {
            PreparedStatement ps = connection.prepareStatement("select uname from users where uname = ?");
            ps.setString(1, user.getUname());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) // found
            {
                updateUser(user);
            } else {
                addUser(user);
            }
        } catch (Exception ex) {
            System.out.println("Error in check() -->" + ex.getMessage());
        }
    }
    public void addUser(User user) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("insert into users(uname, password, email, registeredon) values (?, ?, ?, ? )");
            // Parameters start with 1
            preparedStatement.setString(1, user.getUname());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getEmail());          
            preparedStatement.setDate(4, new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public void deleteUser(String userId) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("delete from users where uname=?");
            // Parameters start with 1
            preparedStatement.setString(1, userId);
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public void updateUser(User user) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("update users set password=?, email=?, registeredon=?"
                    + "where uname=?");
            // Parameters start with 1
            System.out.println(new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.setString(1, user.getPassword());
            preparedStatement.setString(2, user.getEmail());
            preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.setString(4, user.getUname());
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from users");
            while (rs.next()) {
                User user = new User();
                user.setUname(rs.getString("uname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRegisteredon(rs.getDate("registeredon"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
        return users;
    }
 
    public User getUserById(String userId) {
        User user = new User();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("select * from users where uname=?");
            preparedStatement.setString(1, userId);
            ResultSet rs = preparedStatement.executeQuery();
 
            if (rs.next()) {
                user.setUname(rs.getString("uname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRegisteredon(rs.getDate("registeredon"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
        return user;
    }
}

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

User.java

package com.ramsiscode.model;
import java.util.Date;

public class User {

  String uname, password, email;
  Date registeredon;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getRegisteredon() {
return registeredon;
}
public void setRegisteredon(Date registeredon) {
this.registeredon = registeredon;
}
}

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

Database.java

package com.ramsiscode.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
      public static Connection getConnection() {
          try  {
              Class.forName("com.mysql.cj.jdbc.Driver");
              Connection con = DriverManager.getConnection
                      ("jdbc:mysql://localhost:3306/test?characterEncoding=utf8",
                      "root","admin123");
              return con;
          }
          catch(Exception ex) {
              System.out.println("Database.getConnection() Error -->" + ex.getMessage());
              return null;
          }
      }
 
       public static void close(Connection con) {
          try  {
              con.close();
          }
          catch(Exception ex) {
          }
      }
}

-------------------------------------------------------------------------------------
listuser.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
        <thead>
            <tr>
                <th>User Name</th>
                <th>Email</th>
                <th>Registration Date</th>
                <th colspan=2>Action</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${users}" var="user">
                <tr>
                    <td><c:out value="${user.uname}" /></td>
                    <td><c:out value="${user.email}" /></td>
                    <td><fmt:formatDate pattern="dd MMM,yyyy" value="${user.registeredon}" /></td>
                    <td><a href="UserController?action=edit&userId=<c:out value="${user.uname}"/>">Update</a></td>
                    <td><a href="UserController?action=delete&userId=<c:out value="${user.uname}"/>">Delete</a></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    <p><a href="UserController?action=insert">Add User</a></p>
</body>
</html>

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

user.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Add new user</title>
    </head>
    <body>
        <form method="POST" action='UserController' name="frmAddUser">
        <Table border="0px;">
            <% String action = request.getParameter("action");
                System.out.println(action);
            %>
            <tr>
            <% if (action.equalsIgnoreCase("edit")) {%>
            <td>
            User Name : </td><td><input type="text" name="uname"
                               value="<c:out value="${user.uname}" />" readonly="readonly"/> (You Can't Change this)</td>
            <%} else {%>
           <td> User Name :</td><td> <input type="text" name="uname"
                               value="<c:out value="${user.uname}" />" /> </td>
            <%}%>
            </tr>
            <tr>
           <td> Password :</td><td> <input
                type="password" name="pass"
                value="<c:out value="${user.password}" />" /> </td>
            </tr>  
            <tr>  
            <td>
            Email : </td><td><input
                type="text" name="email"
                value="<c:out value="${user.email}" />" /> </td>
            </tr>  
            <% if (action.equalsIgnoreCase("edit")) {%>
           <tr>
           <td> Registration : </td><td><input
                type="text" name="dob"
                value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />" readonly="readonly"/>(You Can't Change this)  
            </td>
            <%} else {%>
           <td> Registration : </td><td><input
                type="text" name="dob"
                value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />" />(yyyy/MM/dd) </td>
            <%}%>
            </tr>
            <br/>
            <tr>
           <td> <input  type="submit" value="Submit" /></td><td><input  type="Reset" value="Reset" /></td>
            </tr>
           </Table>
        </form>
    </body>
</html>

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


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