Wednesday, 4 June 2025

Exception Handling

 Exception handling is a critical component of robust application development in Spring Boot. Properly managed exceptions ensure that your application can handle unexpected scenarios gracefully, maintain stability, and provide meaningful feedback to the user.

Why Exception Handling is Important

  • Robustness: Exception handling ensures that your application can recover from unexpected situations.
  • User Experience: Proper error messages help users understand what went wrong.
  • Debugging and Maintenance: Well-handled exceptions make it easier to debug and maintain the application.
  • Compliance and Security: Proper handling prevents sensitive error details from being exposed to the user.
  • Default Spring Boot Exception Handling

    Spring Boot provides a default global error handler, which handles common exceptions and returns a standard JSON response with details like status code, error message, etc.


Controller Level Exception Handling:











Global Exception Handling
Reference link:

https://www.devskillbuilder.com/exception-handling-in-spring-boot-f8d13eace4ba













Monday, 26 May 2025

Java 8 Interview question with solution

 Example:1 / Filter employees with salary > 50000 and get their names(map example)

Solution:

Output:

High Earning Employees: [Alice, Charlie]   

Program:

import java.util.*;

import java.util.stream.Collectors;

class Employee {

    String name;

    double salary;

    Employee(String name, double salary) {

        this.name = name;

        this.salary = salary;

    }

}

public class EmployeeMapExample {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(

                new Employee("Alice", 60000),

                new Employee("Bob", 45000),

                new Employee("Charlie", 70000)

        );


        // Filter employees with salary > 50000 and get their names

        List<String> highEarnerNames = employees.stream()

                .filter(emp -> emp.salary > 50000) // condition

                .map(emp -> emp.name)             // transform Employee to name

                .collect(Collectors.toList());    // collect as List<String>


        System.out.println("High Earning Employees: " + highEarnerNames);

    }

}


Tuesday, 9 July 2024

GitLab - Package registry & mvn command to deploy the package

 Token Name/Username: Test    

  The role should be:Developer


Project id:59093775




.gitlab-ci.yml


# This file is a template, and might need editing before it works on your project.
# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html

# This specific template is located at:

# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Maven.gitlab-ci.yml

# Build JAVA applications using Apache Maven (http://maven.apache.org)
# For docker image tags see https://hub.docker.com/_/maven/
#
# For general lifecycle information see https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

# This template will build and test your projects
# * Caches downloaded dependencies and plugins between invocation.
# * Verify but don't deploy merge requests.
# * Deploy built artifacts from master branch only.
#before_script:
image: maven:3.8.4-openjdk-17



variables:
workload_name: core
core_project: com
# `showDateTime` will show the passed time in milliseconds. You need to specify
`--batch-mode` to make this work.
# MAVEN_OPTS: >-
# -Dhttps.protocols=TLSv1.2
# -Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository
# -Dorg.slf4j.simpleLogger.showDateTime=true
# -Djava.awt.headless=true

# As of Maven 3.3.0 instead of this you MAY define these options in `.mvn/maven.config` so the same config is used
# when running from the command line.
# As of Maven 3.6.1, the use of `--no-tranfer-progress` (or `-ntp`) suppresses download and upload messages. The use
# of the `Slf4jMavenTransferListener` is no longer necessary.
# `installAtEnd` and `deployAtEnd` are only effective with recent version of the corresponding plugins.
# MAVEN_CLI_OPTS: >-
# --batch-mode
# --errors
# --fail-at-end
# --show-version
# --no-transfer-progress
# -DinstallAtEnd=true
# -DdeployAtEnd=true

# This template uses the latest Maven 3 release, e.g., 3.8.6, and OpenJDK 8 (LTS)
# for verifying and deploying images
# Maven 3.8.x REQUIRES HTTPS repositories.
# See https://maven.apache.org/docs/3.8.1/release-notes.html#how-to-fix-when-i-get-a-http-
repository-blocked for more.

stages:
# - test
- build
- package
# - upload
# - release
- deploy

# Cache downloaded dependencies and plugins between builds.
# To keep cache across branches add 'key: "$CI_JOB_NAME"'
# Be aware that `mvn deploy` will install the built jar into this repository. If you notice
 your cache size
# increasing, consider addin g `-Dmaven.install.skip=true` to `MAVEN_OPTS` or in `.mvn/maven.config`
#cache:
# paths:
# - /.m2/repository

# For merge requests do not `deploy` but only run `verify`.
# See https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
#.verify:
# stage: test
# script:
# - 'mvn $MAVEN_CLI_OPTS verify'
# except:
# variables:
# - $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
#
## Verify merge requests using JDK8
#verify:jdk8:
# extends:
# - .verify

# To deploy packages from CI, create a `ci_settings.xml` file
# For deploying packages to GitLab's Maven Repository: See https://docs.gitlab.com/ee/user/
packages/maven_repository/index.html#create-maven-packages-with-gitlab-cicd for more details.
# Please note: The GitLab Maven Repository is currently only available in GitLab Premium / Ultimate.
# For `master` or `main` branch run `mvn deploy` automatically.
#deploy:jdk8:
# stage: deploy
# script:
# - if [ ! -f ci_settings.xml ]; then
# echo "CI settings missing\! If deploying to GitLab Maven Repository, please see
https://docs.gitlab.com/ee/user/packages/maven_repository/index.html#create-maven-packages-
with-gitlab-cicd for instructions.";
# fi
# - 'mvn $MAVEN_CLI_OPTS deploy --settings ci_settings.xml'
# only:
# variables:
# - $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build-app:
stage: build
# tags:
# - docker
script:
- echo "Maven compile started"
- "mvn install"
artifacts:
paths:
- target/core-0.0.1-SNAPSHOT.jar
# - https://gitlab.com/monikasahu200595/microservices/59093775/packages/maven/core-0.0
.1-SNAPSHOT.jar

package-snapshot:
stage: package
# tags:
# - docker
script:
- echo "Jar package started"
- "mvn package"

#deploy-snapshot:
# stage: deploy
# # tags:
# # - docker
# script:
# - echo "Jar deploy started"
# - "mvn deploy"

#upload:
# stage: upload
## before_script:
## - export VERSION=$(grep -m1 '<version>' pom.xml | grep -oP '(?<=>).*(?=<)')
# script:
# - echo $VERSION
## - 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file target/file_name.jar
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/package-name/$VERSION-${CI_COMMIT_SHORT_SHA}/file_name.jar"'
# - 'curl --header "JOB-TOKEN: $CI_JOB_TO

KEN" --upload-file target/core-0.0.1-SNAPSHOT.jar "https://gitlab.com/monikasahu200595/
microservices/59093775/packages/maven/core-0.0.1-SNAPSHOT.jar"'
# dependencies:
# - build-app

deploy:
stage: deploy
script:
- "mvn deploy"
# Configure Maven settings for deployment
# Create a settings.xml file for Maven with GitLab CI/CD environment variables


Where to get Project Name  and Project ID:


Check if you have project access by access token:






Command to deploy image into package registry:

mvn settings.xml deploy -DgeneratePom=true -DaltDeploymentRepository=gitlab-maven::default::https://gitlab.com/api/v4/projects/59093775/packages/maven
























Tuesday, 11 October 2022

ArrayList And 2D ArrayList Iteartions

 package scaler.ifElse2.Arraylist;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> A1 = new ArrayList<Integer>();
A1.add(1);
A1.add(2);
A1.add(3);
List<Integer> A1Stream=A1.stream().collect(Collectors.toList());
System.out.println("A 1 Stream loop :"+A1Stream);
ArrayList<Integer> A2 = new ArrayList<Integer>();
A2.add(11);
A2.add(22);
A2.add(33);
for(int i=0;i<A2.size();i++){
System.out.println("A2 iterate by simple for loop :"+A2.get(i));
}
ArrayList<Integer> A3 = new ArrayList<Integer>();
A3.add(111);
A3.add(222);
A3.add(333);
for(int a3 : A3){
System.out.println("A3 iterate by for each :"+a3);
}
System.out.println(A1);
System.out.println(A2);
System.out.println(A3);
A.add(A1);
A.add(A2);
A.add(A3);
System.out.println("A :"+A);
System.out.println(A.get(0).get(0));

List<ArrayList<Integer>> j=A.stream().collect(Collectors.toList());
System.out.println(j);

A.stream().forEach(a -> System.out.println("For each stream : "+a));


//first way to iterate by for Each
for(ArrayList<Integer> aa:A){
System.out.println("aa :"+aa);
for(Integer aaa:aa){
System.out.println("aaa :"+aaa);
}
}

for(int i=0;i<A.size();i++){
for(int m=0;m<A.get(i).size();m++){
System.out.println("aaa 111111111111111 :"+A.get(i).get(m));
}
}

}

}
OutPut:
"C:\Program Files\Java\jdk1.8.0_311\bin\java.exe" -javaagent:C:\Users\monik\AppData\Local\JetBrains\Toolbox\apps\IDEA-C\ch-0\213.5744.223\lib\idea_rt.jar=64922:C:\Users\monik\AppData\Local\JetBrains\Toolbox\apps\IDEA-C\ch-0\213.5744.223\bin -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_311\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\rt.jar;C:\Monika\springboot\javaPratice\target\classes" scaler.ifElse2.Arraylist.Ans
A 1 Stream loop :[1, 2, 3]
A2 iterate by simple for loop :11
A2 iterate by simple for loop :22
A2 iterate by simple for loop :33
A3 iterate by for each :111
A3 iterate by for each :222
A3 iterate by for each :333
[1, 2, 3]
[11, 22, 33]
[111, 222, 333]
A :[[1, 2, 3], [11, 22, 33], [111, 222, 333]]
1
[[1, 2, 3], [11, 22, 33], [111, 222, 333]]
For each stream : [1, 2, 3]
For each stream : [11, 22, 33]
For each stream : [111, 222, 333]
aa :[1, 2, 3]
aaa :1
aaa :2
aaa :3
aa :[11, 22, 33]
aaa :11
aaa :22
aaa :33
aa :[111, 222, 333]
aaa :111
aaa :222
aaa :333
aaa   111111111111111 :1
aaa   111111111111111 :2
aaa   111111111111111 :3
aaa   111111111111111 :11
aaa   111111111111111 :22
aaa   111111111111111 :33
aaa   111111111111111 :111
aaa   111111111111111 :222
aaa   111111111111111 :333

Process finished with exit code 0

Monday, 14 October 2019

Swing Login example with mySql connectivity


 Scenarios:


Create a New Form :

Enter User Name
Enter Mail Id
Enter Password

Login Form :

Enter User Name :
Enter Password :

>>>If user enters 3 times wrong user name or password...Disable both textfield and display message:
>> Communicate to Admin

otherwise if both are correct ....Display message : Login Succesfull.





Click on Button :Existing User Login:





Three time attempt:



Sucessful login:





 

SignUpDemo.java


package swingdbdemoform;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import swingdbdemo.EmployeeEntry;

/**
 *
 * @author monika
 */
public class SignUpDemo extends javax.swing.JFrame {

    /**
     * Creates new form loginDemoValidation
     */
    public SignUpDemo() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("UserName");

        jLabel2.setText("EmailId");

        jLabel3.setText("Password");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jButton1.setText("Sign Up");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Existing User login");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(49, 49, 49)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(27, 27, 27)
                                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(26, 26, 26)
                                            .addComponent(jTextField2)
                                            .addGap(1, 1, 1))))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(70, 70, 70)
                            .addComponent(jButton1)
                            .addGap(42, 42, 42)
                            .addComponent(jButton2))))
                .addContainerGap(100, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addContainerGap(114, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
       
       
        String UserName  =  jTextField1.getText();
        String EmailId   =  jTextField2.getText();
        String Password  =  jTextField3.getText();
       
        String query="insert into login values ('"+UserName+"','"+EmailId+"','"+Password+"')";
       
       
       
       
       
        System.out.println("Query   :"+query);
         String query1="select * from login ";
       
         try {
            // TODO add your handling code here:
 
             Class.forName("com.mysql.jdbc.Driver");
             con=DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb","root","test"); 
       //here sonoo is database name, root is username and password 
     
             st=con.createStatement();
             ResultSet  rs=st.executeQuery(query1); 
             boolean found=false;
             while(rs.next())
             {
                 if(UserName.equals(rs.getString("username")))
                 {
                     found=true;
                     break;
                 }
             }
            if(found==true)
            {
                     jLabel4.setText("UserName is already Existe, Kindly Enter another UserName");
                     jTextField1.setText("");
                     jTextField2.setText("");
                     jTextField3.setText("");
            }
            else
            {
           
             st.executeUpdate(query);   
             jTextField1.setText("");
             jTextField2.setText("");
             jTextField3.setText("");
             jLabel4.setText("UserName is sucessfully signed up!!!!!");
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(EmployeeEntry.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(EmployeeEntry.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    }                                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
       
        LoginPage loginPage = new LoginPage();
        loginPage.setVisible(true);
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SignUpDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SignUpDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SignUpDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SignUpDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SignUpDemo().setVisible(true);
            }
        });
    }
 Connection con;
     Statement st;
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration                  
}

LoginPage.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package swingdbdemoform;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import swingdbdemo.EmployeeEntry;

/**
 *
 * @author monika
 */
public class LoginPage extends javax.swing.JFrame {

    /**
     * Creates new form LoginPage
     */
    public LoginPage() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("UserName");

        jLabel2.setText("Password");

        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addComponent(jButton1)
                        .addGap(38, 38, 38)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(53, 53, 53)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                            .addComponent(jTextField2))))
                .addContainerGap(95, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(jLabel3))
                .addContainerGap(150, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String UserName  =  jTextField1.getText();
        String Password  =  jTextField2.getText();
       
         String query1="select * from login ";
       
         try {
            // TODO add your handling code here:
 
             Class.forName("com.mysql.jdbc.Driver");
             con=DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb","root","test"); 
       //here sonoo is database name, root is username and password 
     
             st=con.createStatement();
             ResultSet  rs=st.executeQuery(query1); 
             boolean found=false;
             while(rs.next())
             {
                 if(UserName.equals(rs.getString("username")) && Password.equals(rs.getString("password")))
                 {
                     found=true;
                     break;
                 }
             }
            if(found==true)
            {  
                 homePage.setVisible(true);
                    
            }
            else
            {
            count++;
           
            if(count>3)
            {
              
               jButton1.setEnabled(false);
                jTextField1.setEnabled(false);
                 jTextField2.setEnabled(false);
                  jLabel3.setText("Communicate to Admin!!!!!");
            } else
            {
                jLabel3.setText("Wrong User Name or Password!!!!!");
            }
           
           
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(EmployeeEntry.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(EmployeeEntry.class.getName()).log(Level.SEVERE, null, ex);
        }        // TODO add your handling code here:
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginPage().setVisible(true);
            }
        });
    }
     Connection con;
     Statement st;
     HomePage homePage =  new HomePage();
     int count = 0;
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                  
}


HomePage.Jave


 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package swingdbdemoform;

/**
 *
 * @author monika
 */
public class HomePage extends javax.swing.JFrame {

    /**
     * Creates new form HomePage
     */
    public HomePage() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setBackground(new java.awt.Color(51, 51, 255));
        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Welcome to Home Page");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(129, 129, 129)
                        .addComponent(jLabel2)))
                .addContainerGap(82, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(57, 57, 57)
                .addComponent(jLabel2)
                .addContainerGap(204, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HomePage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HomePage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HomePage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HomePage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HomePage().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration                  
}