Saturday, 19 October 2013

How to check if year is a leap year in java and C#

Leave a Comment
Hye there, its quite complicated to check in if else statement the year is a leap year or not.   Today i will show the example how to check if the year is a leap year or not.

Leap Year
  • A Normal day for a year is 365 days
  • Leap year have 366 days (29 days in february)
How to know if the year is  leap year
  • Leap year can be any year that can be divided by 4 without any balance.
WHY leap year occur
  • This is because according to research, The earth rotate about 365.242375
  • but in one year only have 365 days.
  • So something has to be done to handle the remaining 0.242375 balance. that is why the leap year occur only once in 4 years.

The example is pretty easy to follow.

The Java Application

package leapyear;

import java.util.Scanner;

public class LeapYear {
    
    public static void main(String[] args) {
        String Cont = "Y";
        Scanner input = new Scanner(System.in);
        LeapYear lYear = new LeapYear();
        
        System.out.println("---------------------------");
        System.out.println("Program to check if year is leap year or not");
        System.out.println("---------------------------");
        
        while(Cont.equalsIgnoreCase("Y")){
            
            System.out.println("Please Enter the year to check in format \"YYYY\"");
            String year = "";
            while(year.length() != 4){
                year = input.nextLine();
                if(year.length() != 4){
                    System.out.println("Please Enter the year in format \"YYYY\"");
                }               
            }
            System.out.println("Year " + year + " is a leap year : " + lYear.checkIfYearIsLeapYear(Integer.parseInt(year)));
            
            System.out.println("Do you want to check abother year?(Y,N)");
            Cont = input.nextLine();
            
        }
    }
    
    public boolean checkIfYearIsLeapYear(int iYear){
        if ((iYear % 400 == 0) || ((iYear % 4 == 0) && (iYear % 100 != 0))) {
            return true;
        } else {
            return false;
        }
    }
}
 

The C# Program

using System;
using System.Text;

namespace Check_LeapYear
{
    class Program
    {
        static void Main(string[] args)
        {
            String Cont = "Y";

            Program lYear = new Program();

            Console.WriteLine("---------------------------");
            Console.WriteLine("Program to check if year is leap year or not");
            Console.WriteLine("---------------------------");

            while (Cont.ToUpper().Equals("Y"))
            {

                Console.WriteLine("Please Enter the year to check in format \"YYYY\"");
                String year = "";
                while (year.Length != 4)
                {
                    year = Console.ReadLine();
                    if (year.Length != 4)
                    {
                        Console.WriteLine("Please Enter the year in format \"YYYY\"");
                    }
                }
                Console.WriteLine("Year " + year + " is a leap year : " + lYear.checkIfYearIsLeapYear(Convert.ToInt32(year)));

                Console.WriteLine("Do you want to check abother year?(Y,N)");
                Cont = Console.ReadLine();

            }
        }

        public bool checkIfYearIsLeapYear(int iYear)
        {
            if ((iYear % 400 == 0) || ((iYear % 4 == 0) && (iYear % 100 != 0)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
} 

The Output

---------------------------
Program to check if year is leap year or not
---------------------------
Please Enter the year to check in format "YYYY"
1989
Year 1989 is a leap year : false
Do you want to check abother year?(Y,N)
Y
Please Enter the year to check in format "YYYY"
89
Please Enter the year in format "YYYY"
2011
Year 2011 is a leap year : false
Do you want to check abother year?(Y,N)
Y
Please Enter the year to check in format "YYYY"
1996
Year 1996 is a leap year : true
Do you want to check abother year?(Y,N)
N


C# output

















References



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

Wednesday, 16 October 2013

How to upload file using jsp and servlet

Leave a Comment
In this tutorial i will like to show how to upload file in jsp page and servlet.

Note : Please add JSTL1.1 library and Apache Common FileUpload

*JSTL 1.1 library is in global libraries.(Im using Netbean 7.3.1)

JSP file

<%@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 Upload page - servlet</title>
    </head>
    <body>
        <h1>Upload file JSP!</h1>
        ${uploadMessage}
        <br/>
        <form action="<c:url value="/uploadservlet" />" method="post" enctype="multipart/form-data">
            <input type="file" id="FUploadDoc" name="afile" size="50" /> 
            <input type="submit" name="bUpload" value="upload file"/>
        </form>
    </body>
</html> 

web.xml Configuration

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

The Servlet

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@MultipartConfig
@SuppressWarnings("unchecked")
public class uploadservlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
        if (isMultipart) {
            File file = null;
            int maxFileSize = 50000 * 1024;
            int maxMemSize = 50000 * 1024;
            boolean configExist = false;    

            // Verify the content type
            String contentType = request.getContentType();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(maxMemSize); // maximum size that will be stored in memory
            factory.setRepository(new File("C:/DataUpload/"));
            
            String workingDir = "C:/DataUpload/";   
            ProcessUpload(file, factory, maxFileSize,request,workingDir);

        }else{
            request.setAttribute("uploadMessage", "upload form must be in multipart");
        }
        //redirect back to upload page
        request.getRequestDispatcher("/UploadPage.jsp").forward(request, response);
    }

     
    public void ProcessUpload(File file, DiskFileItemFactory factory, int maxFileSize,
            HttpServletRequest request,String UploadPath) {
        
        ServletFileUpload upload = new ServletFileUpload(factory); // Create a new file upload handler
        upload.setSizeMax(maxFileSize); // maximum file size to be uploaded.
        String Msg = "";
        boolean fileHaveContent = false;
        try {
                  
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) { 
                
                if(!new File(UploadPath).exists()){
                    new File(UploadPath).mkdir();
                }  

                //upload using stream
                Part uploadFile = request.getPart("afile");
                String fileName = getFileName(uploadFile);
                OutputStream out = null;
                InputStream filecontent = null;
                out = new FileOutputStream(new File(UploadPath + File.separator
                        + fileName));
                filecontent = uploadFile.getInputStream();
                
                int read = 0;
                final byte[] bytes = new byte[1024]; 

                while ((read = filecontent.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                
                Msg += "New file (" + fileName + ") created at " + UploadPath;
                out.close();
                filecontent.close();
                fileHaveContent = true; 

            } else {
                Msg = "No File Upload";
                
            }
            request.setAttribute("uploadMessage", Msg);
            
        } catch (Exception ex) {
            request.setAttribute("uploadMessage", ex.getMessage());
        }
    }

    private String getFileName(final Part part) {
        String partHeader = part.getHeader("content-disposition");
        String FileName = "";
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                FileName = content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }

        //means user use Browser IE to upload file, So the above method will not work. This will handle 
        //for user using browser IE to upload file
        if(FileName.contains(":")){ 
            String[] FileNameArr = FileName.split("\\\\");
            FileName = FileNameArr[FileNameArr.length - 1];
        }
        return FileName;
    }

}

Output

  • Before Upload
  • After upload finish



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 read XML file in Java - JSP

Leave a Comment
Hye there, this is my first post and first tutorial. So i will like to show how to read xml file using jsp.

There are many way how to read xml file. But i will show you how to read xml file using DOM xml Parser. DOM will parser the entire XML document and load into memory.

Since DOM will load XML document into memory, it will cost performance of the system if the xml document contains lot of data. Please consider SAX parser as solution if you have lot of data in xml document.

XML file example

this will be example of xml document.

<?xml version="1.0" encoding="UTF-8"?>
<domparsersys>    
    <web-page id="001">
        <page-name>index.jsp</page-name>
        <roles>*</roles>
    </web-page>   
    <web-page id="002">
    <page-name>usermanager.jsp</page-name>
        <roles>ADMINISTRATOR</roles>
    </web-page> 
</domparsersys> 

JSP file

<%@page import="org.w3c.dom.Element"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="org.w3c.dom.Document"%>
<%@page import="javax.xml.parsers.DocumentBuilder"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory"%>
<%@page import="java.io.File"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <h1>Read Xml using DOM parser</h1>
        <%
    try {
       
        File xmlFile = new File("D:/Data/example1.xml");
        DocumentBuilderFactory docBuilderFac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFac.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlFile);
        //optional, but
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("web-page");
 

        for (int temp = 0; temp < nList.getLength(); temp++) {

           Node nNode = nList.item(temp);
            System.out.println("<br/>Current Element :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                out.println("<br/>Page id : " + eElement.getAttribute("id"));
                out.println("<br/>Page Name : " + eElement.getElementsByTagName("page-name").item(0).getTextContent());
                out.println("<br/>Roles : " + eElement.getElementsByTagName("roles").item(0).getTextContent());
            }
        }  

    } catch (Exception ex){
        out.println(ex.getMessage());
    }



    %>
  
    </body>
</html>

Output 

Page id : 001 
Page Name : index.jsp 
Roles : * 
Page id : 002 
Page Name : usermanager.jsp 
Roles : ADMINISTRATOR 




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, 3 October 2013

Step by step how to add iReport query as parameter

Leave a Comment
Someone ask me how to pass sql statement as parameter in iReport.

So i did a little research and test by myself. There is a one trick to put sql query statement as a parameter in ireport. The purpose to do this is when you want to call the jasper report in your application is either client or the web, you can pass the specific query to your jasper report.

Here is the step:

  1. Create your report
  2. Use Static query for example like "Select * Fom Companies";
  3. Add your field to your report.
  4. Create one parameter let say "sql_input_param" as java.lang.String
  5. Set the default value same like step no 2.(just in case you forgot to pass the parameter, the default value will handle it.

HERE IS THE TRICK

  1. Modify your query to be $P!{sql_input_param} < -- as you can see, there is a exclamation symbol after letter P. Its is used to pass parameter as sql query in ireport query.

Now you can test to pass query statement as parameter in ireport

HashMap<String, Object> parameters = new HashMap<>();
var sql = "SELECT * FROM companies WHERE companies.company_id = " + forms.frm_company.company_id + " order by companies.company_id";
parameters .put('sql_input', sql);

Connection jdbcConnection;
JasperReport jasperReport;
JasperPrint jasperPrint;
JRPdfExporter exporter = new JRPdfExporter();

JasperDesign jasperDesign = JRXmlLoader.load(F);
jasperReport = JasperCompileManager.compileReport(jasperDesign);
jasperPrint = JasperFillManager.fillReport(jasperReport, param, jdbcConnection);
::
::
::
::
now you can pass the query statement as parameter in iReport. 

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, 8 September 2013

[SOLVED] A debugger is already attached.

Leave a Comment
Attaching the Script debugger to process '[xxxx] iexplore.exe'
 on machine XXXXXXXXXX failed. A debugger is already attached.

As you can see the error above. the problem occur when you update your IE from version 9 to 10 in window 7. and then try to debug web application using MSVS2010 .

The Quick solution :

1. Run Command Prompt As Admin
2. Run this script  : regsvr32.exe "%ProgramFiles(x86)%\Common Files\Microsoft Shared\VS7Debug\msdbg2.dll
3. Problem Solved.

Refer Original Post here 
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.