Wednesday 3 August 2022

Create A Pagination Application using jsp Servlet





----------------------------------- ConnectionFactory.java -------------------------------------------

package com.ramsiscode.db;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class ConnectionFactory {
    //static reference to itself
    private static ConnectionFactory instance =
                new ConnectionFactory();
    String url = "jdbc:mysql://localhost:3306/exampledb";
    String user = "asdfg";
    String password = "cctns@7777";
    String driverClass = "com.mysql.jdbc.Driver";
 
    //private constructor
    private ConnectionFactory() {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    public static ConnectionFactory getInstance()   {
        return instance;
    }
 
    public Connection getConnection() throws SQLException,
    ClassNotFoundException {
        Connection connection =
            DriverManager.getConnection(url, user, password);
        return connection;
    }
}


----------------------------------- EmployeeServlet.java -------------------------------------------


package com.ramsiscode.servlets;
 
import java.io.IOException;
import java.util.List;
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.EmployeeDAO;
import com.ramsiscode.to.Employee;
 
/**
 * Servlet implementation class EmployeeServlet
 */
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    public EmployeeServlet() {
            super();
    }
 
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        int page = 1;
        int recordsPerPage = 8;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
                                 recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("displayEmployee.jsp");
        view.forward(request, response);
    }
}



----------------------------------- EmployeeDAO.java -------------------------------------------

package com.ramsiscode.dao;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.ramsiscode.db.ConnectionFactory;
import com.ramsiscode.to.Employee;
 
public class EmployeeDAO {
    Connection connection;
    Statement stmt;
    private int noOfRecords;
 
    public EmployeeDAO() { }
 
    private static Connection getConnection()
            throws SQLException,
                ClassNotFoundException
    {
        Connection con = ConnectionFactory.
                getInstance().getConnection();
        return con;
    }
 
    public List<Employee> viewAllEmployees(
                int offset,
                int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit "
                 + offset + ", " + noOfRecords;
        List<Employee> list = new ArrayList<Employee>();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt("emp_id"));
                employee.setEmployeeName(rs.getString("emp_name"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setDeptName(rs.getString("dept_name"));
                list.add(employee);
            }
            rs.close();
 
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
            if(rs.next())
                this.noOfRecords = rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally
        {
            try {
                if(stmt != null)
                    stmt.close();
                if(connection != null)
                    connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
 
    public int getNoOfRecords() {
        return noOfRecords;
    }
}

--------------------------------------- Employee.java ---------------------------------------


package com.ramsiscode.to;
 
public class Employee {
    private int employeeId;
    private String employeeName;
    private double salary;
    private String deptName;
 
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}


---------------------------------- displayEmployee.jsp -----------------------------------------



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Employees</title>
</head>
<body>
    <table border="1" cellpadding="3" cellspacing="3">
        <tr>
            <th>Emp ID</th>
            <th>Emp Name</th>
            <th>Salary</th>
            <th>Dept Name</th>
        </tr>
 
        <c:forEach var="employee" items="${employeeList}">
            <tr>
                <td>${employee.employeeId}</td>
                <td>${employee.employeeName}</td>
                <td>${employee.salary}</td>
                <td>${employee.deptName}</td>
            </tr>
        </c:forEach>
    </table>
 
    <%--For displaying Previous link except for the 1st page --%>
    <c:if test="${currentPage != 1}">
        <td><a href="employee.do?page=${currentPage - 1}">Previous</a></td>
    </c:if>
 
    <%--For displaying Page numbers.
    The when condition does not display a link for the current page--%>
    <table border="1" cellpadding="5" cellspacing="5">
        <tr>
            <c:forEach begin="1" end="${noOfPages}" var="i">
                <c:choose>
                    <c:when test="${currentPage eq i}">
                        <td>${i}</td>
                    </c:when>
                    <c:otherwise>
                        <td><a href="employee.do?page=${i}">${i}</a></td>
                    </c:otherwise>
                </c:choose>
            </c:forEach>
        </tr>
    </table>
 
    <%--For displaying Next link --%>
    <c:if test="${currentPage lt noOfPages}">
        <td><a href="employee.do?page=${currentPage + 1}">Next</a></td>
    </c:if>
 
</body>
</html>

------------------------------------ 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_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>JSPPagination</display-name>
   <welcome-file-list>
    <welcome-file>employee.do</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>com.ramsiscode.servlets.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/employee.do</url-pattern>
  </servlet-mapping>
</web-app>

Download Code

Friday 15 July 2022

CRUD Web Application using JSTL Library in jsp











--------------------------------------------------Insert.jsp------------------------------------------

<%@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>Choose Option</h1>
        <a href="insert.jsp">Insert Record</a><p></p>
        <a href="display.jsp">Display Record</a>
    </body>
</html>

--------------------------------------------------index.jsp------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="insertdb.jsp" method="post">
            <table border="0" cellspacing="2" cellpadding="5">
                <thead>
                    <tr>
                        <th colspan="2">Purchase Product</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><label>Product Name</label></td>
                        <td><input type="text" name="pname"/></td>
                    </tr>
                    <tr>
                        <td><label>Quantity</label></td>
                        <td><input type="text" name="qty"/></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Save" /></td>
                        <td><input type="reset" value="reset"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
        <font color="red"><c:if test="${not empty param.errMsg}">
            <c:out value="${param.errMsg}" />
            <a href="index.jsp">Go Back</a>
        </c:if></font>
        <font color="green"><c:if test="${not empty param.susMsg}">
            <c:out value="${param.susMsg}" />
            <a href="index.jsp">Go Back</a>
        </c:if></font>
 
    </body>
</html>

-----------------------------------------------------updatedb.jsp----------------------------------------------
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
        <sql:update dataSource="${dbsource}" var="count">
            UPDATE product SET pname = ?, quantity=?
            WHERE id='${param.id}'
            <sql:param value="${param.pname}" />
            <sql:param value="${param.qty}" />
        </sql:update>
        <c:if test="${count>=1}">
            <font size="5" color='green'> Congratulations ! Data updated
            successfully.</font>
              <a href="index.jsp">Go Home</a>        
        </c:if>
    </body>
</html>

-------------------------------------------------update.jsp----------------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
 
       <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:query dataSource="${dbsource}" var="result">
            SELECT * from product where id=?;
            <sql:param value="${param.id}" />
        </sql:query>
        <form action="updatedb.jsp" method="post">
            <table border="0" width="40%">
                <caption>Update Product</caption>
                <tr>
                    <th>Product Name</th>
                    <th>Quantity</th>
                </tr>
                <c:forEach var="row" items="${result.rows}">
                    <tr>
                        <td><input type="hidden" value="${param.id}" name="id"/>
                            <input type="text" value="${row.pname}" name="pname"/></td>
                        <td><input type="text" value="${row.quantity}" name="qty"/></td>
                        <td><input type="submit" value="Update"/></td>
                    </tr>
                </c:forEach>
            </table>
            <a href="index.jsp">Go Home</a>
        </form>
    </body>
</html>
-------------------------------------------------------deletedb.jsp---------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
  <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:update dataSource="${dbsource}" var="count">
            DELETE FROM product
            WHERE id='${param.id}'
        </sql:update>
        <c:if test="${count>=1}">
            <font size="5" color='green'> Congratulations ! Data deleted
            successfully.</font>
              <a href="index.jsp">Go Home</a>        
        </c:if>
    </body>
</html>
---------------------------------------------------------display.jsp---------------------------------------------

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
    <head>
        <title>SELECT Operation</title>
        <script>
            function confirmGo(m,u) {
                if ( confirm(m) ) {
                    window.location = u;
                }
            }
        </script>
    </head>
    <body>
 
        <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:query dataSource="${dbsource}" var="result">
            SELECT * from product;
        </sql:query>
    <center>
        <form>
            <table border="1" width="40%">
                <caption>Product List</caption>
                <tr>
                    <th>Product ID</th>
                    <th>Product Name</th>
                    <th>Quantity</th>
                    <th colspan="2">Action</th>
                </tr>
                <c:forEach var="row" items="${result.rows}">
                    <tr>
                        <td><c:out value="${row.id}"/></td>
                        <td><c:out value="${row.pname}"/></td>
                        <td><c:out value="${row.quantity}"/></td>
                        <td><a href="update.jsp?id=<c:out value="${row.id}"/>">Update</a></td>
                        <td><a href="javascript:confirmGo('Sure to delete this record?','deletedb.jsp?id=<c:out value="${row.id}"/>')">Delete</a></td>
                         
                    </tr>
                </c:forEach>
            </table>
        </form>
        <a href="index.jsp">Go Home</a>
    </center>
</body>
</html>

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



Download Code

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