Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Monday, 6 January 2014

Arranging DIVs Horizontally

1 comment
Working with DIV tag is always problem and hard work thats why many web developers avoid creating their websites in DIV tag, in this tutorial, I will show you how to arrange DIVs in horizontal order with CSS.

The HTML Code


This is the html code for 4 divs div.container, div.left, div.middle and div.right.
Note: Below the div.right there is another div with height:0; and width:100% and clear:both, the job of this div is to make sure the floating divs not going outside the container, try on your own to remove the div.clear to see what will happen on those floating div.


   <div class="container">
   <div class="left">Left</div>
   <div class="middle">Middle</div>
   <div class="right">Right</div>
   <div class="clear"></div>
   </div>



The CSS Code


.container{
width:600px;
padding:0;
border:5px solid #ddd;
margin:0 auto;
}

.left{
float:left;
width:150px;
height:300px;
text-align:center;
background:#4b471a;
font:18px Arial, Helvetica, sans-serif;
font-weight:bold;
color:#1b1b1b;
}

.middle{
float:left;
width:300px;
height:300px;
text-align:center;
background:#a19c5a;
font:18px Arial, Helvetica, sans-serif;
font-weight:bold;
color:#1b1b1b;
}

.right{
float:left;
width:150px;
height:300px;
text-align:center;
background:#4b471a;
font:18px Arial, Helvetica, sans-serif;
font-weight:bold;
color:#1b1b1b;
}

.clear{
clear:both;
height:0;
width:100%;
}

Output



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Sunday, 5 January 2014

Google Map API Zoom The Marker Example

Leave a Comment
Google Map API Marker is a powerful API to use for web page to mark on the map for example the location of your business office. This tutorial can use in all framework as long as the framework use html language to render the content to client side.

You can refer here for more information of Google Map API

Let see the example in asp.net framework.

The Javascript to call map and marker

var map;
function initializeGMap() {
           var Centre = new google.maps.LatLng(3.15681, 101.714696);
            var mapOptions = { zoom: 12, center: Centre, mapTypeId: google.maps.MapTypeId.ROADMAP };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            var KLCC = new google.maps.LatLng(3.15681, 101.714696);
            var marker = new google.maps.Marker({ position: KLCC, map: map, title: 'Kuala Lumpur City Center' });  
        }
        google.maps.event.addDomListener(window, 'load', initializeGMap);


The Zoom Marker Script

function getInfo() {
            var contentString = '<div style="width: 400px; min-height: 100px;">';
            contentString += '<table style="font-size:12px; width:400px; height: 100px; border: none !important;">';
            contentString += '<tr style=\"background:none !important;\">';
            contentString += '<td valign=\"top\" style=\"width: 80px; height: 80px;border-bottom:none;\"></td>';
            contentString += '<td valign=\"top\" style=\"border-bottom:none;\">';
            contentString += '<table><tr style=\"background:none !important;\">';
            contentString += '<td style=\"font-size:16px;border-bottom:none;\">';
            contentString += '<b>Kuala Lumpur City Centre</b></td></tr>';
            contentString += '<tr style=\"background:none !important;\">';
            contentString += '<td style=\"border-bottom:none;\">';
            contentString += 'Kuala Lumpur City Centre<br />50450 Kuala Lumpur<br/>Wilayah Persekutuan Kuala Lumpur, Malaysia</td>';
            contentString += '</tr></table></td></tr><tr style=\"background:none !important;\">';
            contentString += '<td style=\"border-bottom:none;\">&nbsp;</td></tr>';
            contentString += '<tr style=\"background:none !important;border-bottom:none;\">';
            contentString += '<td colspan="2"></td></tr><tr style="background:none !important;">';
            contentString += '<td colspan="2" style=\"border-bottom:none;\"><b>Phone:</b>-</td>';
            contentString += '</tr></td></tr></table></div>';
            var infoWindowMarker = new google.maps.InfoWindow({
                content: contentString
            });
            var myLatLng = new google.maps.LatLng(3.15681, 101.714696);
            var myMarker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: 'Kuala Lumpur City Centre'
            });
            infoWindowMarker.close();
            infoWindowMarker.open(map, myMarker);
            map.setCenter(myLatLng);
            map.setZoom(17);

        }


The ASPX Page

<div style="width: 600px; height: 400px; float:left;">
        <div id="map-canvas" style="width: 100%; height: 100%;">
        </div>
    </div>
    <div style="float:right;">
        <div id="Div1" style="width: 100%; height: 100%; text-align:left; padding:20px;">
            <asp:Button ID="Button1" runat="server" Text="Zoom The Marker" OnClientClick="getInfo();return false;" />
        </div>
    </div>


Full Code

Note : This example use default MasterPage from Visual Studio 2010

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>

        var map;

        function initializeGMap() {

            var Centre = new google.maps.LatLng(3.15681, 101.714696);
            var mapOptions = { zoom: 12, center: Centre, mapTypeId: google.maps.MapTypeId.ROADMAP };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            var KLCC = new google.maps.LatLng(3.15681, 101.714696);
            var marker = new google.maps.Marker({ position: KLCC, map: map, title: 'Kuala Lumpur City Center' });
            
        }
        google.maps.event.addDomListener(window, 'load', initializeGMap);
    
        function getInfo() {
            var contentString = '<div style="width: 400px; min-height: 100px;">';
            contentString += '<table style="font-size:12px; width:400px; height: 100px; border: none !important;">';
            contentString += '<tr style=\"background:none !important;\">';
            contentString += '<td valign=\"top\" style=\"width: 80px; height: 80px;border-bottom:none;\"></td>';
            contentString += '<td valign=\"top\" style=\"border-bottom:none;\">';
            contentString += '<table><tr style=\"background:none !important;\">';
            contentString += '<td style=\"font-size:16px;border-bottom:none;\">';
            contentString += '<b>Kuala Lumpur City Centre</b></td></tr>';
            contentString += '<tr style=\"background:none !important;\">';
            contentString += '<td style=\"border-bottom:none;\">';
            contentString += 'Kuala Lumpur City Centre<br />50450 Kuala Lumpur<br/>Wilayah Persekutuan Kuala Lumpur, Malaysia</td>';
            contentString += '</tr></table></td></tr><tr style=\"background:none !important;\">';
            contentString += '<td style=\"border-bottom:none;\">&nbsp;</td></tr>';
            contentString += '<tr style=\"background:none !important;border-bottom:none;\">';
            contentString += '<td colspan="2"></td></tr><tr style="background:none !important;">';
            contentString += '<td colspan="2" style=\"border-bottom:none;\"><b>Phone:</b>-</td>';
            contentString += '</tr></td></tr></table></div>';
            var infoWindowMarker = new google.maps.InfoWindow({
                content: contentString
            });
            var myLatLng = new google.maps.LatLng(3.15681, 101.714696);
            var myMarker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: 'Kuala Lumpur City Centre'
            });
            infoWindowMarker.close();
            infoWindowMarker.open(map, myMarker);
            map.setCenter(myLatLng);
            map.setZoom(17);

        }
      </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div style="width: 600px; height: 400px; float:left;">
        <div id="map-canvas" style="width: 100%; height: 100%;">
        </div>
    </div>
    <div style="float:right;">
        <div id="Div1" style="width: 100%; height: 100%; text-align:left; padding:20px;">
            <asp:Button ID="Button1" runat="server" Text="Zoom The Marker" OnClientClick="getInfo();return false;" />
        </div>
    </div>
</asp:Content>

The Output 

Before Zoom

After Zoom


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Friday, 3 January 2014

Disable Back Browser Button in web Page

Leave a Comment
This example will show how to disable Back button in your browser. To achieve this objective, the javascript will be use to redirect back to the current page if the user click on the browser back button and give message to user. So let see the example.

I'll set the script at HEAD element and use onpageshow and  onload event in the body element.

The Javascript put in Head element

<script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(); document.getElementById("Message").innerHTML = "You cannot Go Back"; }
    </script>


The Html/Aspx/Jsp page

:
: Head element 
: 

<body onpageshow="if (event.persisted) noBack();" onload="noBack();" >

:
: body content

 <div id="Message" style="color:red;">
 </div>

:
:
</body>
</html>


The Output

If the user click on the browser back button, the script will automatically redirect to the current page and give the message "You cannot go back" to user


Note : You can customize the script for example if you want to force logout user if user click on the back button, you can create one page "forceLogout.aspx"  and then edit the script to redirect page to forceLogout.aspx . So everytime user click on the browser back button , user will redirect to forceLogout.aspx page.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday, 25 November 2013

Java - Get Visitor/Client ip address : JSP : Servlet

Leave a Comment
The previous post show how to get Visitor or client ip address in C# / ASP.NET .

This post will show how to get ip address of client / visitor from jsp / servlet application. In order to make this method work, you need to test this method on the server and you are accessing the server from your computer. Otherwise you will get your local ipaddress or ::1 value.

The getClientIpAddr Method

     public static String getClientIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader("X-FORWARDED-FOR");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Thursday, 24 October 2013

How to create zip file to download in JSP- Servlet

Leave a Comment
Hye, my previous post show that how to download zip file in ASP.NET,. In this tutorial i will show the same thing, but in Jsp-Servlet.

Note : In this tutorial i will use this library :-

  • JSTL 1.1

 The JSP File

 <%@ 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>Download File As ZIP File</title>
    </head>
    <body>
       <h1>Download File As ZIP File</h1>
        ${DownloadMessage}
        <br/>
        <form action="<c:url value="/downloadFileServletZip" />" method="post" >
            Default Path is server to download is D:\JAVA\dist\Output\
            <input type="submit" name="bDownload" value="Download Zip file"/>
        </form>
    </body>
</html>





The Servlet

 import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class downloadFileServletZip extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = "D:\\JAVA\\dist\\Output\\";
        File directory = new File(path);
        String[] files = directory.list();
       
        //check if directories have files
        if (files != null && files.length > 0) {
           
            //create zip stream
            byte[] zip = zipFiles(directory, files);
           
           
            // Sends the response back to the user / browser with zip content
            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
           
            sos.write(zip);
            sos.flush();
        }
       
        request.setAttribute("DownloadMessage", "Successfully");
        request.getRequestDispatcher("DownloadZipFile.jsp").forward(request, response);
       
    }
   
    private byte[] zipFiles(File directory, String[] files) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        byte bytes[] = new byte[4096];
       
        for (String fileName : files) {
            try (FileInputStream fis = new FileInputStream(directory.getPath()
                    + "/" + fileName);
                   
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
               
                zos.putNextEntry(new ZipEntry(fileName));
               
                int bytesRead;
                while ((bytesRead = bis.read(bytes)) != -1) {
                    zos.write(bytes, 0, bytesRead);
                }
                zos.closeEntry();
            }
        }
        zos.flush();
        baos.flush();
        zos.close();
        baos.close();
       
        return baos.toByteArray();
    }
   
   
}



The Web.xml

 <servlet-mapping>
        <servlet-name>downloadFileServletZip</servlet-name>
        <url-pattern>/downloadFileServletZip</url-pattern>
    </servlet-mapping>

 <servlet>
        <servlet-name>downloadFileServletZip</servlet-name>
        <servlet-class>sys.servlet.downloadFileServletZip</servlet-class>

</servlet>




Note : This code will throw exception Access denied if the folder  to create zip file contain subfolder.





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Friday, 18 October 2013

Multiple button in one form JSP - SERVLET

Leave a Comment
Hye there, today i will show one simple tutorial to show that which button is clicked in one form.
The idea after i read this post on forum how to find which button is clicked

Note : In this tutorial i will use this library :-

  • JSTL 1.1

Here is the example

The JSP File

<%@ 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>Multiple Buttom In Form</title>
    </head>
    <body>
        <h1>Multiple Button In Form</h1>
        ${message}
        <br/>
        <form action="<c:url value="/servletMultipleButton" />" method="POST">
           <input type="submit" name="BModify" value="Modify" ></input>
           <input type="submit" name="BRemove" value="Remove" ></input>
           <input type="submit" name="BSave" value="Save" ></input>
           <input type="submit" name="BConfirm" value="Cancel" ></input>
           <input type="submit" name="BReset" value="BReset" ></input> <br/>
           
           <input type="submit" name="BModify" value="Modify2" ></input>
           <input type="submit" name="BRemove" value="Remove2" ></input>
           <input type="submit" name="BSave" value="Save2" ></input>
           <input type="submit" name="BConfirm" value="Cancel2" ></input>
           <input type="submit" name="BReset" value="BReset2" ></input>
        </form>
    </body>
</html>

The Servlet

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author coding noted
 */
public class servletMultipleButton extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String actionValue = "";
        String button_selected = "";
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
            button_selected = (String) en.nextElement();            
            actionValue = request.getParameter(button_selected);            
        }
        
        request.setAttribute("message", "Button Clicked : " + button_selected + "<br/>" + "Button Value : " + actionValue);
        request.getRequestDispatcher("/multipleButtonInForm.jsp").forward(request, response);
        
    }

} 

Web.xml

 <servlet>
        <servlet-name>servletMultipleButton</servlet-name>
        <servlet-class>sys.servlet.servletMultipleButton</servlet-class>
    </servlet> 

<servlet-mapping>
        <servlet-name>servletMultipleButton</servlet-name>
        <url-pattern>/servletMultipleButton</url-pattern>
    </servlet-mapping>



Output










References

  1. http://stackoverflow.com/questions/11830351/multiple-submit-buttons-in-the-same-form-calling-different-servlets
  2. http://stackoverflow.com/questions/6639340/can-i-have-two-submit-buttons-in-a-jsp-to-two-different-controllers


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

How to create DataGrid or Gridview in JSP - Servlet

Leave a Comment
Hye there, today i will show tutorial on creating basic datagrid in JSP.
This is my solution but not permanent solution on all other cases. Maybe you can enhance this code to achieve you own goal..In this tutorial i will use basic servlet and JSP .

Note : In this tutorial i will use this library :-
  • MySQL JDBC Driver
  • JSTL 1.1
the project will run on source JDK 7

This is the database table

DROP TABLE IF EXISTS `blogtest`.`usersprofile`;
CREATE TABLE  `blogtest`.`usersprofile` (
  `userid` varchar(30) NOT NULL,
  `firstName` varchar(45) NOT NULL,
  `lastName` varchar(45) NOT NULL,
  `emailAddress` varchar(45) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `usersprofile` VALUES ('Ahmad','Ahmad','Ahmad','Ahmad@gmail.com'),
('Ahmad1','Ahmad1','Ahmad1','Ahmad1@gmail.com'),
('Ahmad10','Ahmad10','Ahmad10','Ahmad10@gmail.com'),
('Ahmad11','Ahmad11','Ahmad11','Ahmad11@gmail.com'),
('Ahmad12','Ahmad12','Ahmad12','Ahmad12@gmail.com'),
('Ahmad13','Ahmad13','Ahmad13','Ahmad13@gmail.com'),
('Ahmad14','Ahmad14','Ahmad14','Ahmad14@gmail.com'),
('Ahmad15','Ahmad15','Ahmad15','Ahmad15@gmail.com'),
('Ahmad16','Ahmad16','Ahmad16','Ahmad16@gmail.com'),
('Ahmad2','Ahmad2','Ahmad2','Ahmad2@gmail.com'),
('Ahmad3','Ahmad3','Ahmad3','Ahmad3@gmail.com'),
('Ahmad4','Ahmad5','Ahmad5','Ahmad5@gmail.com'),
('Ahmad6','Ahmad6','Ahmad6','Ahmad6@gmail.com'),
('Ahmad7','Ahmad7','Ahmad7','Ahmad7@gmail.com'),
('Ahmad8','Ahmad8','Ahmad8','Ahmad8@gmail.com'),
('Ahmad9','Ahmad9','Ahmad9','Ahmad9@gmail.com'); 



The JSP Page

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="sys.userclass.userProfile"%>
<%@page import="sys.userclass.userServices"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript">

            function ConfirmOnDelete(item) {
              if (confirm("Are you sure to delete " + item + "?") === true)
                  return true;
              else
           return false;
           }
        </script>
    </head>
    <body>
        <h1>Data Grid In JSP</h1>
        <br/>
        <br/>
        <fieldset>
            <legend>Users Management</legend>
            ${errorMessage}
            ${successMessage}
            <br/>
            <div>
                <form action="<c:url value="/dataGridServlet" />" method="POST">
                      <%
                          int limitStart = 0;
                          int limitMax = 15;
                          int pageSize = 15;
                          int allUserCount = 0;
                          int pageIndex = 0; //start page from index 0
                          session = request.getSession(false);

                          //check cookie
                          Cookie[] collectionCookies = request.getCookies();
                          String cookieValue = "";
                          for (Cookie c : collectionCookies) {
                              if (c.getName().equalsIgnoreCase("FirstTimeAccessUserManager")) {
                                  if (c.getValue().equalsIgnoreCase("YES")) {
                                      c.setValue("NO");
                                      cookieValue = "NO";
                                  } else if (c.getValue().equalsIgnoreCase("")) {
                                      c.setValue("YES");
                                      session.removeAttribute("limitStart");
                                      session.removeAttribute("limitMax");
                                      session.removeAttribute("pageIndex");
                                      session.removeAttribute("pageSize");
                                  }
                              }
                          }
                          if (cookieValue.equalsIgnoreCase("")) {
                              Cookie cookie = new Cookie("FirstTimeAccessUserManager", "YES");
                              response.addCookie(cookie);
                          }

                          if (session.getAttribute("limitStart") != null) {
                              limitStart = Integer.parseInt(session.getAttribute("limitStart").toString());
                          } else {
                              session.setAttribute("limitStart", limitStart);
                          }

                          if (session.getAttribute("limitMax") != null) {
                              limitMax = Integer.parseInt(session.getAttribute("limitMax").toString());
                          } else {
                              session.setAttribute("limitMax", limitMax);
                          }

                          if (session.getAttribute("pageIndex") != null) {
                              pageIndex = Integer.parseInt(session.getAttribute("pageIndex").toString());
                          } else {
                              session.setAttribute("pageIndex", pageIndex);
                          }

                          if (session.getAttribute("pageSize") != null) {
                              pageSize = Integer.parseInt(session.getAttribute("pageSize").toString());
                          } else {
                              session.setAttribute("pageSize", pageSize);
                          }
 limitMax = pageSize;

                          userServices usersServ = new userServices();

                          List<userProfile> _collectionOfUserProfile = new ArrayList<userProfile>();                          


                          allUserCount = usersServ.countTableDataRow("usersprofile");

                          _collectionOfUserProfile = usersServ.getAllUsers(limitStart, limitMax);                         


                          String tableuser = "<table class=\"mainTable\" cellspacing=\"0\" rules=\"all\" id=\"MainContent_GridView1\" style=\"border-color:Gray;border-width:1px;border-style:Solid;width:95%;border-collapse:collapse;\">";
                          tableuser += "<tr style=\"color:White;background-color:#6699CC;font-weight:bold; padding:4px;\">";
                          tableuser += "<th scope=\"col\">No.</th>";
                          tableuser += "<th scope=\"col\">User ID</th>";
                          tableuser += "<th scope=\"col\">First Name</th>";
                          tableuser += "<th scope=\"col\">Last Name</th>";
                          tableuser += "<th scope=\"col\">Email</th>";
                          tableuser += "<th scope=\"col\">&nbsp;</th>";
                          tableuser += "<th scope=\"col\">&nbsp;</th></tr>";

                          int numberRecord = pageIndex * pageSize;
                          int balance = allUserCount - numberRecord;
                          int startRekodToShow = numberRecord + 1;
                          int index = startRekodToShow;
                          for (userProfile u : _collectionOfUserProfile) {
                              tableuser += "<tr style=\"border-color:Gray;border-width:1px;border-style:Solid;\">";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:20px;padding:4px;\">";
                              tableuser += Integer.toString(index);
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:100px;padding:4px;\">";
                              tableuser += u.getUserid();
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
                              tableuser += u.getFirstName();
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
                              tableuser += u.getLastName();
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
                              tableuser += u.getEmailAddress();
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:50px;padding:4px;\">";
                              tableuser += "<input type=\"submit\" class=\"buttonLikeLink\" name=\"" + u.getUserid() + "\" onclick=\"return ConfirmOnDelete('" + u.getUserid() + "');\" value=\"Remove\" />";
                              tableuser += "</td>";
                              tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:50px;padding:4px;\">";
                              tableuser += "<input type=\"submit\" class=\"buttonLikeLink\" name=\"" + u.getUserid() + "\" value=\"Modify\" ></input>";
                              tableuser += "</td>";
                              tableuser += "</tr>";
                              index++;
                          }
                          tableuser += "</table>";
                          out.print(tableuser);
                      %>
            </form>

           <!-- Create logic next and previous in this section -->
            <%
                if (allUserCount > pageSize) {
                    String form = "<br/><br/>";
                    if (pageIndex > 0) {
                        form += "<h1>Page " + Integer.toString(pageIndex) + "</h1><br/>";
                    }
                    form += "<form action=\"" + request.getContextPath() + "/navigateDatagrid\" method=\"POST\" >";
                    if (limitStart > 0) {
                        if (balance > pageSize) {
                            if ((pageSize + numberRecord) == allUserCount) {
                                //do not show next
                            } else {
                                //show next
                                form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
                            }
                        } else {
                            if ((balance + numberRecord) == allUserCount) {
                                //do not show next
                            } else {
                                //show next
                                form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
                            }
                        }
                       if (startRekodToShow != 1) {
                            form += "<input type=\"submit\" class=\"buttonNav\" id=\"bPrevious\" name=\"action\" value=\"Previous\" />";
                        }
                    } else {
                        form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
                    }
                    form += "</form>";
                    out.print(form);
                }
            %>
        </div>
        <br />
        <br />
        <%
            if (allUserCount > 15) {
                String grid_row_controller = "<div id=\"MainContent_PanelDropDownGVPage\" style=\"display:inline;\">";
                grid_row_controller += "Total Users Per Page :";
                grid_row_controller += "<form method=\"POST\" action=\"" + request.getContextPath() + "/navigateDatagrid\" id=\"pageRowform\" >";
                grid_row_controller += "<select name=\"action\" style=\"width:50px;\" onchange=\"document.forms['pageRowform'].submit()\">";

                if (pageSize == 10) {
                    grid_row_controller += "<option value=\"10\" selected=\"selected\">10</option>";
                } else {
                    grid_row_controller += "<option value=\"10\">10</option>";
                }

                if (pageSize == 15) {
                    grid_row_controller += "<option selected=\"selected\" value=\"15\">15</option>";
                } else {
                    grid_row_controller += "<option value=\"15\">15</option>";
                }

                if (pageSize == 25) {
                    grid_row_controller += "<option selected=\"selected\" value=\"25\">25</option>";
                } else {
                    grid_row_controller += "<option value=\"25\">25</option>";
                }
                if (pageSize == 35) {
                    grid_row_controller += "<option selected=\"selected\" value=\"35\">35</option>";
                } else {
                    grid_row_controller += "<option value=\"35\">35</option>";
                }
                if (pageSize == 50) {
                    grid_row_controller += "<option selected=\"selected\" value=\"50\">50</option>";
                } else {
                    grid_row_controller += "<option value=\"50\">50</option>";
                }

                grid_row_controller += "</select>";
                grid_row_controller += "</form>";
                out.print(grid_row_controller);
            }
        %>        
        <br />
        Show         
        <%

            if (allUserCount > pageSize) {
                if (pageIndex == 0) {
                    out.print("1 - " + pageSize);
                } else {
                    if (balance > pageSize) {
                        out.print(startRekodToShow + " - " + (pageSize + numberRecord));
                    } else {
                        out.print(startRekodToShow + " - " + (balance + numberRecord));
                    }
                }
            } else if (allUserCount == 0) {
                out.print("0");
            } else {
                out.print("1 - " + allUserCount);
            }
        %>      
        Record(s)  From 
        <%
            out.print(allUserCount);
        %>
        User(s)
        <br />
    </fieldset>
</body>
</html>

The Navigator Data Grid Servlet

package sys.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class navigateDatagrid extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String buttonAction = request.getParameter("action");
        HttpSession session = request.getSession(false);
        int limitStart = 0;
        int limitMax = 15;
        int pageSize = 15;
        int allUserCount = 0;
        int pageIndex = 0; //start page from index 0
        session = request.getSession(false);
        if (session.getAttribute("limitStart") != null) {
            limitStart = Integer.parseInt(session.getAttribute("limitStart").toString());
        } else {
            session.setAttribute("limitStart", limitStart);
        }
        if (session.getAttribute("limitMax") != null) {
            limitMax = Integer.parseInt(session.getAttribute("limitMax").toString());
        } else {
            session.setAttribute("limitMax", limitMax);
        }
        if (session.getAttribute("pageIndex") != null) {
            pageIndex = Integer.parseInt(session.getAttribute("pageIndex").toString());
        } else {
            session.setAttribute("pageIndex", pageIndex);
        }
        if (session.getAttribute("pageSize") != null) {
            pageSize = Integer.parseInt(session.getAttribute("pageSize").toString());
        } else {
            session.setAttribute("pageSize", pageSize);
        }
        if (buttonAction.equalsIgnoreCase("Next")) {
            limitStart += pageSize;
            limitMax = pageSize;//max row return from query
            pageIndex += 1;           
        }else if(buttonAction.equalsIgnoreCase("Previous")){
            limitStart -= pageSize;
            limitMax = pageSize;//max row return from query
            pageIndex -= 1;
        }else{
            //reset all value to default
            limitStart  = 0;
            limitMax = 15;//max row return from query
            pageSize = Integer.parseInt(buttonAction);
            pageIndex = 0;
        }
        session.setAttribute("limitMax", limitMax);
        session.setAttribute("pageIndex", pageIndex);
        session.setAttribute("limitStart", limitStart);
        session.setAttribute("pageSize", pageSize);
        response.sendRedirect(request.getContextPath() + "/datagrid.jsp");
    }
}

The Edit Delete Servlet Data Grid

package sys.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sys.userclass.userServices;

public class dataGridServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String actionValue = "";
        String useridselected = "";
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
            useridselected = (String) en.nextElement();            
            actionValue = request.getParameter(useridselected);  
        }
        if(useridselected.trim().equalsIgnoreCase("")){
            request.setAttribute("errorMessage","Cannot find user id");
            request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
        }else{            
            if(actionValue.contains("Remove")){    
                userServices userServis = new userServices();
                if(userServis.deleteUser(useridselected)){
                    request.setAttribute("successMessage", "Successfully delete user: <b>" + useridselected + "</b>");
                    request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
                }else{
                    request.setAttribute("errorMessage", "Failed to delete user: <b>" + useridselected + "</b>, please try again");                    
                   request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
                }                
            }else{
                //process redirect to modify user page with query string user id
                //redirect to modify page
           }
        }
    }
}

The UserServices Class

package sys.userclass;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class userServices {
    public Connection getDbConn() {
        if(_dbConn == null){ 
           _dbConn = CheckConnection();
        }
        return _dbConn;
    }
    public void setDbConn(Connection aDbConn) {
        _dbConn = aDbConn;
    }
    public static String getDbUrl() {
        return _dbUrl;
    }
    public static void setDbUrl(String aDbUrl) {

        _dbUrl = aDbUrl;

    }  
    public static String getUser() {
        return _user;
    }
    public static void setUser(String aUser) {
        _user = aUser;
    }
    public static String getDbPassword() {
        return _dbPassword;
    }

    public static void setDbPassword(String aDbPassword) {
        _dbPassword = aDbPassword;
    }

    private List<userProfile> _collectionOfUserProfile;
    private static Connection _dbConn;
    private static String _dbUrl = "jdbc:mysql://localhost:3306/blogtest";
    private static String _user = "root";
    private static String _dbPassword = "P@ssw0rd";
    private final static Logger LOGGER = Logger.getLogger(userServices.class.getName());

    public userServices() {
        _collectionOfUserProfile = new ArrayList<>();
        _dbUrl = "jdbc:mysql://localhost:3306/blogtest";
        _user = "root";
        _dbPassword = "P@ssw0rd";      
    }
    public List<userProfile> getAllUsers(int limitStart, int limitMax) {
        ResultSet rs = null;
        String strsql = "Select * from usersprofile order by userid DESC limit " + Integer.toString(limitStart) + "," + Integer.toString(limitMax);
        Connection conn = null;
        try {
            conn = CheckConnection();
            conn.setAutoCommit(true);
            PreparedStatement prepStatement = conn.prepareStatement(strsql);
            rs = prepStatement.executeQuery();

            while (rs.next()) {
                userProfile user = new userProfile();
                user.setUserid(rs.getString("userid"));
                user.setFirstName(rs.getString("firstName"));
                user.setLastName(rs.getString("lastName"));
                user.setEmailAddress(rs.getString("emailAddress"));
                _collectionOfUserProfile.add(user);
            }

        } catch (SQLException ex) {
            //handle catch
        } finally {
            closeConnection();
        }
        return _collectionOfUserProfile;

    }    

     public boolean deleteUser(String userid){
        boolean isSuccess = false;
        ResultSet rs = null;
        String strsql = "delete from usersprofile where UserID=?";
        PreparedStatement prepStatement = null;        
        Connection conn = null;
        try {
            conn = CheckConnection();
            conn.setAutoCommit(true);
            int rtnCode = 0;
            getDbConn().setAutoCommit(false);
            prepStatement = conn.prepareStatement(strsql);
            prepStatement.setString(1, userid);
            rtnCode = prepStatement.executeUpdate();
            if (rtnCode > 0) {
                _dbConn.commit();
                isSuccess  =true;
            }else{                
                _dbConn.rollback();
                isSuccess  = false;
            }     

        } catch (SQLException ex) {
           //catch handler
        } finally {
            closeConnection();
        }       

        return isSuccess;
    }
    public int countTableDataRow(String TableName) {
        int ValCount = 0;
        Statement stmt = null;
        Connection conn = null;
        try {
            conn = CheckConnection();
            conn.setAutoCommit(true);
            String strsql = "SELECT Count(*) FROM " + TableName;
            stmt = conn.createStatement();
            try (ResultSet rs = stmt.executeQuery(strsql)) {
                rs.next();
                ValCount = rs.getInt(1);
            }
        } catch (SQLException se) {
            //handle catch
        } finally {
            closeConnection();
        }
        return ValCount;
    }
    public void closeConnection() {
        try {
            if (_dbConn != null) {
                _dbConn.close();
            }
        } catch (SQLException ex) {
            //handle catch
        }
    }
    public Connection CheckConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            LOGGER.info(e.getMessage());                    
        }     

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(_dbUrl, _user, _dbPassword);
        } catch (SQLException e) {
            LOGGER.info(e.getMessage());         
        }
        if (connection != null) {
            LOGGER.info("You made it, take control your database now!");            
            
        } else {
            LOGGER.info("Failed to make connection!");    
        }
        return connection;
    }
    public List<userProfile> getCollectionOfUserProfile() {
        return _collectionOfUserProfile;
    }
    public void setCollectionOfUserProfile(List<userProfile> collectionOfUserProfile) {
        this._collectionOfUserProfile = collectionOfUserProfile;
    }
}

The User Profile Class

package sys.userclass;
public class userProfile {
    private String _userid;
    private String _firstName;
    private String _lastName;
    private String _emailAddress;   

    public userProfile(){
        _userid = "";
        _firstName = "";
        _lastName = "";
        _emailAddress = "";      
    }
    public String getUserid() {
        return _userid;
    }
    public void setUserid(String userid) {
        this._userid = userid;
    }
    public String getFirstName() {
        return _firstName;
    }
    public void setFirstName(String firstName) {
        this._firstName = firstName;
    }   
    public String getLastName() {
        return _lastName;
    }
    public void setLastName(String lastName) {
        this._lastName = lastName;
    }
    public String getEmailAddress() {
        return _emailAddress;
    }
    public void setEmailAddress(String emailAddress) {
        this._emailAddress = emailAddress;
    } 
} 

Web.xml

 <servlet>
        <servlet-name>dataGridServlet</servlet-name>
        <servlet-class>sys.servlet.dataGridServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>navigateDatagrid</servlet-name>
        <servlet-class>sys.servlet.navigateDatagrid</servlet-class>
    </servlet>   
    <servlet-mapping>
        <servlet-name>dataGridServlet</servlet-name>
        <url-pattern>/dataGridServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>navigateDatagrid</servlet-name>
        <url-pattern>/navigateDatagrid</url-pattern>
    </servlet-mapping>

Output


NOTE : After done all of this thing..you need to clear cookie when you enter other page.
Use this code to clear the cookie when you enter another page.

public static void clearCookieUserManager(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] collectionCookies = request.getCookies();
        for (Cookie c : collectionCookies) {
            if (c.getName().equalsIgnoreCase("FirstTimeAccessUserManager")) {
                c.setValue("");
                response.addCookie(c);
                break;
            }
        }
    }


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.