06 May 2026

Java top 30 in 2026

 Question 1. What are the key features of Java 17 and later LTS versions? Modern Java focuses on conciseness, safety, and readability. Java 8 introduced Streams and Lambdas. Java 11 added the HTTP Client. Java 17 brought Records for immutable data classes, Sealed Classes for controlled inheritance hierarchies, Pattern Matching to reduce boilerplate, Switch Expressions for cleaner conditional logic, and Text Blocks for multi-line strings. These features make Java more expressive and closer to modern language design.  Question 2. Explain JVM Architecture. The Java Virtual Machine is the engine that runs your Java programs. It has three main components. The ClassLoader loads your compiled bytecode into memory. The Runtime Data Areas include the Heap, Stack, Method Area, and PC Registers. The Execution Engine runs the bytecode using either an Interpreter for quick startup or the JIT Compiler for optimized performance. Understanding JVM architecture is essential for writing performant Java applications.  Question 3. What is the difference between Heap and Stack memory? The Stack stores method call frames and local variables. It is thread-specific and automatically cleaned up when a method returns. It is fast but limited in size. The Heap stores all objects created with the new keyword. It is shared across threads and managed by the Garbage Collector. The Heap is much larger but involves GC overhead. Stack overflow errors and OutOfMemoryErrors are the typical failure modes for each.  Question 4. What is Garbage Collection in Java? Garbage Collection is Java's automatic memory management system. The JVM periodically identifies objects that are no longer reachable from any live reference and reclaims their memory. This prevents memory leaks and reduces the burden on developers. The GC uses algorithms like Mark and Sweep, Copying, and Generational collection to efficiently manage memory across the Young Generation and Old Generation heap spaces.  Question 5. What are the different types of Garbage Collectors in Java? Java offers several GC implementations. Serial GC is single-threaded and suited for small applications. Parallel GC uses multiple threads for throughput-focused workloads. G1 GC, the default since Java 9, balances throughput and latency by dividing the heap into regions. ZGC is a low-latency collector introduced in Java 11, targeting pause times under one millisecond. Shenandoah is another low-pause collector available in OpenJDK. Concurrency & Memory  Question 6. What is Multithreading in Java? Multithreading allows a Java application to execute multiple threads concurrently, making better use of CPU cores. Each thread is an independent path of execution. Java supports multithreading via the Thread class, the Runnable interface, and higher-level abstractions in the java.util.concurrent package. Multithreading improves responsiveness in UI applications, throughput in server applications, and enables parallel computation.  Question 7. What is the difference between Runnable and Callable? Both Runnable and Callable represent tasks to be executed by a thread. Runnable's run method returns void and cannot throw checked exceptions, making it simpler for fire-and-forget tasks. Callable's call method returns a typed value and can throw checked exceptions. Callable is used with ExecutorService and returns a Future object, allowing you to retrieve the result or handle exceptions asynchronously.  Question 8. What is Synchronization in Java? Synchronization controls concurrent access to shared resources, preventing race conditions and data corruption. The synchronized keyword can be applied to methods or blocks. When a thread enters a synchronized block, it acquires a lock on the object. Other threads attempting to enter the same block are blocked until the lock is released. Proper synchronization ensures thread safety but must be used carefully to avoid deadlocks and performance bottlenecks.  Question 9. What is the Volatile keyword? The volatile keyword ensures that a variable's value is always read from and written to main memory, not from a thread's local CPU cache. This guarantees visibility of the latest value across all threads. Volatile is useful for simple flags and state variables but does not provide atomicity for compound operations like increment. For atomic compound operations, use classes from java.util.concurrent.atomic.  Question 10. What is the Java Memory Model? The Java Memory Model defines how threads interact with memory. It specifies when changes made by one thread become visible to another. The JMM introduces the happens-before relationship: if action A happens-before action B, then A's effects are visible to B. Synchronized blocks, volatile reads and writes, and thread start and join operations all establish happens-before guarantees. Understanding the JMM is critical for writing correct concurrent programs. Collections, Generics & OOP Question 11. What is the Stream API? The Stream API, introduced in Java 8, enables functional-style processing of data collections. A stream is a sequence of elements supporting operations like filter, map, sorted, distinct, and collect. Streams can be sequential or parallel. They promote declarative programming, making code more readable and concise. Streams are lazy — intermediate operations are not executed until a terminal operation like collect, forEach, or reduce is invoked. Question 12. What is the difference between HashMap and ConcurrentHashMap? HashMap is not thread-safe. Concurrent modifications can cause data corruption or infinite loops. ConcurrentHashMap is designed for concurrent access. In Java 8 and later, it uses CAS operations and synchronized blocks at the bucket level, avoiding full-table locks. It allows multiple threads to read and write simultaneously with high throughput. Use ConcurrentHashMap whenever a map is shared across threads. Question 13. What are Java Generics? Generics allow you to write type-safe, reusable code by parameterizing classes, interfaces, and methods with type parameters. For example, List of String ensures only strings can be added, eliminating casts and preventing ClassCastException at runtime. Generics use type erasure, meaning type parameters are removed at compile time. Wildcards provide flexibility in generic API design. Question 14. What is the difference between Abstract Class and Interface? An Abstract Class can have both abstract and concrete methods, instance variables, and constructors. A class can extend only one abstract class. An Interface defines a contract. Since Java 8, interfaces can have default and static methods. A class can implement multiple interfaces, enabling multiple inheritance of behavior. Use abstract classes for shared state and behavior; use interfaces for defining capabilities and contracts. Design Patterns & Architecture Question 15. What is the SOLID Principle? SOLID is a set of five object-oriented design principles. Single Responsibility: a class should have one reason to change. Open-Closed: classes should be open for extension, closed for modification. Liskov Substitution: subtypes must be substitutable for their base types. Interface Segregation: clients should not depend on interfaces they don't use. Dependency Inversion: depend on abstractions, not concrete implementations. Following SOLID leads to maintainable, flexible, and testable code. Question 16. What are Design Patterns? Design patterns are reusable solutions to common software design problems. They are categorized into three groups. Creational patterns like Singleton, Factory, and Builder manage object creation. Structural patterns like Adapter, Decorator, and Proxy deal with composition. Behavioral patterns like Observer, Strategy, and Command define communication between objects. Knowing design patterns helps you write cleaner, more maintainable code. Question 17. What is the Singleton Pattern? The Singleton pattern ensures a class has only one instance and provides a global access point to it. Common implementations include eager initialization, lazy initialization with double-checked locking, and the enum-based approach, which is the most concise and thread-safe. The Singleton is used for shared resources like configuration managers, connection pools, and logging utilities. Question 18. What is Dependency Injection? Dependency Injection is a design pattern where an object receives its dependencies from an external source rather than creating them itself. This promotes loose coupling, testability, and separation of concerns. DI is commonly implemented via constructor injection, setter injection, or field injection. Frameworks like Spring manage DI using an IoC container that automatically wires dependencies based on annotations like Autowired and Component. Spring & Microservices Question 19. What is Spring Boot and how does it differ from Spring? Spring is a comprehensive framework for enterprise Java development. Spring Boot is an opinionated layer on top of Spring that simplifies setup through auto-configuration, embedded servers like Tomcat, and starter dependencies. With Spring Boot, you can create a production-ready application with minimal configuration. It is ideal for building microservices and RESTful APIs quickly. Question 20. What are Microservices? Microservices is an architectural style where an application is structured as a collection of small, independently deployable services, each responsible for a specific business capability. Services communicate via REST APIs, messaging queues, or gRPC. Benefits include independent scaling, technology diversity, and faster deployment cycles. Challenges include distributed system complexity, network latency, and the need for service discovery tools like Kubernetes. Question 21. What is RESTful API design? REST is an architectural style for designing networked APIs. RESTful APIs use standard HTTP methods: GET for reading, POST for creating, PUT for updating, and DELETE for removing resources. Resources are identified by URIs. Responses are typically in JSON format. REST principles include statelessness, uniform interface, and client-server separation. Good REST design uses proper HTTP status codes, versioning, and consistent resource naming. Advanced Java Question 22. What is Exception Handling in Java? Java uses a try-catch-finally mechanism for exception handling. Checked exceptions must be declared or caught at compile time. Unchecked exceptions extending RuntimeException do not require explicit handling. The finally block always executes, making it ideal for cleanup. Java 7 introduced try-with-resources for automatic resource management and multi-catch blocks for handling multiple exception types concisely. Question 23. What is Java Reflection? Reflection allows Java code to inspect and manipulate classes, methods, and fields at runtime. You can dynamically create objects, invoke methods, and access private members using the java.lang.reflect package. Reflection is widely used in frameworks like Spring, Hibernate, and JUnit. However, it bypasses compile-time safety and can impact performance, so it should be used judiciously. Question 24. What is the difference between Comparable and Comparator? Comparable defines the natural ordering of a class by implementing the compareTo method within the class itself. It is used for the default sort order. Comparator defines an external ordering strategy implemented in a separate class or lambda. Comparator is more flexible, allowing multiple sort orders for the same class. Java 8 enhanced Comparator with methods like comparing, thenComparing, and reversed for fluent, composable sorting. Question 25. What are Java Annotations? Annotations are metadata markers applied to classes, methods, fields, or parameters. They do not directly affect program logic but provide information to the compiler or runtime. Built-in annotations include Override, Deprecated, and SuppressWarnings. Framework annotations like Spring's Autowired, JPA's Entity, and JUnit's Test drive behavior through reflection and annotation processors. Question 26. What is the Optional class? Optional, introduced in Java 8, is a container object that may or may not hold a non-null value. It is designed to replace null returns and make the absence of a value explicit in APIs. Common methods include isPresent, ifPresent, get, orElse, orElseGet, and map. Using Optional reduces NullPointerExceptions and encourages explicit handling of absent values. It should be used as a return type in APIs. Question 27. What is the Fork-Join Framework? The Fork-Join Framework, introduced in Java 7, is designed for parallel computation by recursively splitting tasks into smaller subtasks and combining results. It uses a work-stealing algorithm where idle threads steal tasks from busy threads' queues, maximizing CPU utilization. The main class is ForkJoinPool. Tasks extend RecursiveTask for result-returning tasks or RecursiveAction for void tasks. Java 8's parallel streams use the Fork-Join Framework under the hood. Question 28. What is Java NIO? Java NIO provides non-blocking, channel-based IO operations. Key components include Channels for reading and writing, Buffers for data storage, and Selectors for monitoring multiple channels with a single thread. NIO is ideal for high-performance network applications handling thousands of concurrent connections. It contrasts with traditional blocking IO where each connection requires a dedicated thread. Question 29. What are Functional Interfaces? A Functional Interface is an interface with exactly one abstract method, making it eligible as a lambda expression target. Java 8 introduced the java.util.function package with built-in functional interfaces: Function maps input to output, Predicate tests a condition, Consumer accepts input without returning a value, Supplier provides output without input, and BiFunction works with two inputs. Question 30. What are CompletableFuture and Reactive Programming? CompletableFuture, introduced in Java 8, enables asynchronous, non-blocking programming with chainable operations. You can compose async tasks using thenApply, thenCompose, thenCombine, and handle exceptions with exceptionally. Reactive Programming treats asynchronous data streams as first-class citizens with back-pressure support. Libraries like Project Reactor and RxJava implement reactive principles. Spring WebFlux builds on Project Reactor to enable fully non-blocking, reactive web applications essential for high-throughput microservices. Wrap Up And that wraps up the Top 30 Java Interview Questions for 2026. From JVM internals to reactive programming, mastering these topics will set you apart in any senior Java interview. Keep practicing, keep building, and good luck.

18 January 2020

K8S

Kubernetes cluster manages the containers for
1.Deployment
2.Maintenance
3.Scaling.


Steps to create a deploy a spring boot application to google cloud with kubernetes cluster
1.Create a spring boot app and push it to git.
2.Login to google cloud console and create a docker image by pulling application
3.Deploy container image to kubernetes cluster.
4.Allow traffic
5.Test it by  adding additional containers and changing versions.

HTML5

25%  <meter><progress>

This
is
 formatted  <pre>
text

 <input range>

iam small  <small>

marked text  <mark>

JavaPro9NoYesquoted
<sup><sub><del><q>

<FieldSet>
Java9pro Java
HTML
DS


<bdo> Writing left to right Is it right 

<Audio>

<Video> 

14 October 2018

Caching with Spring Boot

What-Why Cache?
Cache is a memory between an application and database to reduce the number of
Database hits.It improves performance of applications by reducing expensive
operations(Ex:DB hits), if it is stored with frequently accessed data.
Data which changes less frequently(static master data) and frequently accessed
data can be stored in cache.


Spring boot Cache:
Spring framework provides cache
api to integrate with different cache providers.
Spring boot provides @EnableCaching annotation to enable cache management.
When @Cacheable annotation is used at method level, Spring manages the request and response in cache.@Cacheable annotation has "key" attribute to decide a request to be cached.

Example:
Check code at https://github.com/java9pro/java9pro-cache
Project structure look like


pom.xml
Add dependency spring-boot-starter-cache for enabling cache management.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro</groupId>
    <artifactId>java9pro.springboot.cache</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-archiver</artifactId>
            <version>3.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.9</source>
                    <target>1.9</target>
                    <jdkToolchain>
                        <version>9</version>
                    </jdkToolchain>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
    </build>

</project>
ProductController
It has request mapping with url path parameter as "id" and calls service method.
package com.cache.java9pro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestControllerpublic class ProductController {
    @Autowired    MobileService mobileService;

    @GetMapping("/mobile/{id}")
    public   Mobile findMobileDetailById(@PathVariable String id)
    {
       return mobileService.getMobileDetailByID(id);
    }
}
Mobile
It is a simple POJO with required attribute id
package com.cache.java9pro;

public class Mobile {
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getRam() {
        return ram;
    }

    public void setRam(String ram) {
        this.ram = ram;
    }

    String id;
    String model;
    String ram;
    public Mobile(String id, String model, String ram) {
        this.id=id;
        this.model=model;
        this.ram=ram;
    }
}
MobileService
It has @Cacheable annotation enabled method  getMobileDetailByID 
which call DAO method if and only if the request/response are not available in cache. 
package com.cache.java9pro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Servicepublic class MobileService {

    @Autowired    MobileDAO  mobileDAO;

    @Cacheable(value="mobile", key="#id")
    public Mobile getMobileDetailByID(String id)
    {
        Mobile mobile=null;
        try {
            System.out.println("Getting from database");
            Thread.sleep(5000);
            mobile = mobileDAO.getMobileInfo(id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mobile;
    }
}

MobileDAO
To simulate database access, provided switch-case implementation for different ids
package com.cache.java9pro;

import org.springframework.stereotype.Component;

@Componentpublic class MobileDAO {

    public Mobile getMobileInfo(String id) {
        switch (id){
            case "1" : return new Mobile(id,"Samsung","4GB");
            case "2" : return new Mobile(id,"Apple","6GB");
            case "3" : return new Mobile(id,"Motorola","2GB");
            case "4" : return new Mobile(id,"Lenovo","3GB");

        }
        return null;
    }
}
CacheApplication

It is Spring boot application method with annotation @EnableCaching

package com.cache.java9pro;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication@EnableCachingpublic class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

application.properties
application.port=8080
Upon running main method application starts on port 8080.
To test the application execute the following URLs
  1. http://localhost:8080/mobile/1
  2. http://localhost:8080/mobile/2
  3. http://localhost:8080/mobile/3
  4. http://localhost:8080/mobile/4
  5. http://localhost:8080/mobile/1
  6. http://localhost:8080/mobile/2
  7. http://localhost:8080/mobile/3
  8. http://localhost:8080/mobile/4
First 4 URLs will access DAO method.
Last 4 URLs (5,6,7,8) will not access DAO method and
will provide response from cache.
Sample output looks like







28 April 2018

LinkedList with Side nodes


LinkedList with side nodes



class SidelyLinkedList  {
    static Node head;
    static class Node {
        int item;
        Node next;
        Node side;
        Node(int item) {
            this.item =item;
            next = null;
            side = null;
        }
    }
    public static void main(String[] args) {
        SidelyLinkedList list = new SidelyLinkedList();
        list.head = new Node(51);
        list.head.next = new Node(10);
        list.head.next.next = new Node(15);
        list.head.next.next.next = new Node(18);
        list.head.next.next.next.next= new Node(21);
        list.head.side = new Node(34);
        list.head.side.side = new Node(48);
        list.head.next.side = new Node(23);
        list.head.next.side.side = new Node(67);
        list.head.next.next.side = new Node(12);
        list.head.next.next.side.side = new Node(89);
        list.head.next.next.next.side = new Node(67);
        list.head.next.next.next.side.side = new Node(92);
        list.head.next.next.next.next.side = new Node(56);
        list.head.next.next.next.next.side.side = new Node(97);
        Node res1 = list.singleList(head);
        list.printSidelyLinkedList(res1);
       }

    private Node singleList(Node node) {
        if(node.next==null){
            return node;
        }
        else{
            Node temp = node;
            Node temp1= node.next;
            while(temp.side!= null){
                temp= temp.side;
            }
            temp.side= temp1;
            node.next=temp1.next;
            return singleList(node);
        }
    }

    private void printSidelyLinkedList(Node head) {
        if(head==null){
            return;
        }
        else            {
            System.out.println(head.item +"->");
                printSidelyLinkedList(head.side);
        }
    }


}

Output:
51->
34->
48->
10->
23->
67->
15->
12->
89->
18->
67->
92->
21->
56->
97->




03 March 2018

Spring Boot Application

Spring boot framework:

1.Helps to build applications rapidly by removing the need to configure boiler plate configuration code.

2.Though it has no additional features to add to spring framework, It helps to build production
 ready applications quickly.

3.It provides necessary endpoints out of the box to check metrics, health check with spring boot actuator module.

4.Embedded servers(tomcat,jetty) and embedded databases can be added to build the application
without looking into the database configuration details.

We can build a simple HelloWorld Spring MVC application with Spring Boot in 2 minutes.

Project structure:  It does not need web.xml. Spring boot will take care of these configurations.

spring boot
Add caption


pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro</groupId>
    <artifactId>java9pro.springboot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>


</project>

LoginController:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class LoginController {


        @RequestMapping("/")
        @ResponseBody        String home() {
            return "Hello World!";
        }

        public static void main(String[] args) throws Exception {
            SpringApplication.run(LoginController.class, args);
        }
    }

It has annotation @EnableAutoConfiguration, which will load the required jar dependencies.It will
initialize the application context, registers the dispatcher servlet, registers the beans for JMX.

After running the main method of LoginController, Application will start on the embedded tomcat on default port 8080.

Output can be viewed on this URL.

http://localhost:8080

server port can be changed by adding configuration to application.properties file in resources.

server.port = 8090.

Then server starts on port 8090 and URL http://localhost:8090 will give the result.







25 February 2018

HTTP Vs HTTPS

HTTP is short form for Hyper Text Transfer  Protocol. It is used for communication between website and user(browser). Information going to and from the server is plain text.

HTTPS is nothing but the (S)Secured HTTP protocol. Information going to and from the server is encrypted.

How this security is assured:
How to convert a website to use https:

SSL certificate does this job.SSL is short form for Secure Socket  Layer.
One need to buy a SSL certificate from certified authorities(CA) and it need to be installed in host.
All popular browsers recognize the certificates from CAs.

How HTTPS works with SSL certificate:

SSL is the protocol used to make the communication secure by encrypting the messages between website and user.
It uses asymmetric keys to secure the transport between browser and server.
It uses asymmetric and symmetric encryption techniques to encrypt the messages between sender and receiver.
Server uses private key to decrypt the message.Public key is shared across all the clients.
Server sends SSL certificate certified by trusted authorities.It includes public key information.
Client(browser) generates a key(client key) and encrypts the message with it and encrypt the message again with it public key.
Server receive the message and decrypt it with its private key.
Now the communication happens with the symmetric key generated by client and it is valid for that session. For every new session,client generates new symmetric key.

How asymmetric key works:

Message will by multiplied by certain number(public key) and the inverse of the same can be used as  private key.
Example:
If a message has been multiplied by it self 3 times, 0.33(1/3) will be private key and 3 is the public key.
Sender -M--->M*M*M--->M*M*M--->M3(1/3)-->M- Receiver.
Popular asymmetric encryption algorithms use different number with log functions to generate symmetric and asymmetric keys.
Examples:
RSA


11 November 2017

Java 9 Modules

What is a Java Module:

Java 9 has introduced modules.Module is nothing but a set of packages.
A new java file module-info.java in every module tells the following
1.Required packages for a modules
2.Exported packages from module.
Tools can generate this file, when we create a java modular application.

So the current access specifier of class "public" can have 3 definitions based on module-info.java.

Public class in a package
1.Can't be accessed outside the module if it is not exported.
Thus JDK encapsulates internal APIs.
2.Can be accessed outside the module if it is exported.
3.Can be accessed to some modules outside the module and can't be accessed by some modules outside the module.

Why we need --What are the advantages:

1.All the public classes can't be accessed outside the module,if module-info.java defined to
not to be accessed.Public classes of JDK internal APIs can't be accessed outside.So provides security improvement.

2.Java9 JDK has removed rt.jar and introduced 95 smaller modules.User can import the required module.Since there is no need to add big jars like rt.jar,which was essential to add java runtime libraries,the application size will be small

3.It will restrict to not to write packages with same name in two modules.
It will throw runtimeexception.So no split packages

Example:

“java.base” module is the base module.
module-info.java for java.base
module java.base {
    exports java.io;
    exports java.lang;
    exports java.math;
    exports java.net;
}
Every module requires java.base module.New folder in JDK jmods folder has all the modules and it looks like





04 November 2017

Spring security application with password hashing

Spring security framework provides solutions for developing applications with authorization and authentication.We use password encoder in with this example.

To build Spring MVC based web application,which uses Spring Security framework for login,
We need
1.JDK
2.Apache Maven
3.Intellij/Eclipse(Editor tool)
4.Apache Tomcat

We have developed a sample Spring MVC application in this link.
Project structure look like



DelegatingFilterProxy is an impelmentation of the javax.servlet.Servlet filters can intercept requests before reaching servlet.
We have to configure this DelegatingFilterProxy in web.xml,it acts as filter.
We have to define a spring spring-security.xml  in context param.
web.xml :

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee"                  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                   
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/java9pro-springmvc-servlet.xml
        /WEB-INF/java9pro-security.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
    </listener>
    <servlet>
        <servlet-name>java9pro-springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>java9pro-springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


</web-app>

We have to define a  spring-security.xml .Spring security framework provides BCryptPasswordEncoder to hash the passwords.
So the hashed password for java9pro is  $2a$10$p.r1COYmT0kl8iU3Eq56EeCm1.QdcwIRozzkJ5GVOLxAGICAxCLIy.
Same has been provided as password for user java9pro.
Following util class can be used to generate the hashed password.

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class Utils {
    public static void main(String[] args) {
            String password = "java9pro";
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         System.out.println(passwordEncoder.encode(password));

        }
}

http configuration is used to intercept the url access along with the role.
authentication manager configuration consists of  user service configuration to fetch the user credentials to authenticate the application.
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"       xmlns="http://www.springframework.org/schema/security"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       http://www.springframework.org/schema/security       http://www.springframework.org/schema/security/spring-security-3.2.xsd ">

    <http auto-config="true">
        <intercept-url pattern="/login" access="ROLE_USER" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder ref="passwordEncoder"/>
            <user-service>
                <user name="java9pro" 
password="$2a$10$p.r1COYmT0kl8iU3Eq56EeCm1.QdcwIRozzkJ5GVOLxAGICAxCLIy"
 authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="passwordEncoder" 
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

</beans:beans>

 pom.xml:

Add  below jars
spring-security-core
spring-security-config
spring-security-web

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"        
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro.springmvc</groupId>
    <artifactId>java9pro.springmvc.arti</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <finalName>springJava9ProMVC</finalName>
    </build>

    <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>

    </dependencies>


</project>

Controller Class Java9ProController looks like
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controllerpublic class Java9ProController {
    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/")
    public String logoutPage(){

        return "logout";
    }

}

Spring MVC bean confiuration file java9pro-springmvc-servlet.xml



<beans xmlns="http://www.springframework.org/schema/beans"       
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       
xmlns:context="http://www.springframework.org/schema/context"      
 xmlns:mvc="http://www.springframework.org/schema/mvc"       
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd      
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd      
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd ">

    <context:component-scan base-package="com.becomeJavaPro.springmvc"/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>


Spring Security will automatically create a login URL at /spring_security_login


When Username as java9pro and Password as java9pro


When bad credentials