Sunday, November 26, 2023

How Request mapping or HandlerMapping works in Spring MVC? @RequestMapping Example

Hello guys, In last a couple of articles, we have learned how Spring MVC framework works and what is the role of DispatcherServlet in Spring MVC. We have briefly touched another frequently asked Spring MVC interview question, how does requests are mapped to controllers in Spring MVC? In this article, we'll expand our knowledge on that. You have learned that DispatcherServlet is the front controller in Spring MVC framework, it is the single point entry and all incoming request goes through it, but instead of processing those request it just dispatches the request to the appropriate handler methods based on the request mapping, but how does it do that?

Monday, November 20, 2023

How to secure an URL using hasRole() in Spring Security? Is it enough to hide sections of JSP to protect URL? Example?

One of the Spring security question asked to me on a recent interview was about is it enough to hide portions of JSP to protect a URL from unauthorized access in Spring security? First of all I didn't understand the question, so I ask him to clarify a bit more. He explained to me that there are different roles in his application e.g. DEVELOPER, ADMIN, TRADER, OPERATION and each role can only see the functionalities based upon their role. For example, an ADMIN has a right to add or remove new users into the system, while DEVELOPER can only see test order, but OPERATION can see all orders. 

Monday, November 13, 2023

How to show current logged in username in JSP using Spring Security? Example Tutorial

One of the common feature of secure Java web application to show the username as link on the top right corner of web application once user successfully logged in. Some application also show the logout or sign-out link like that but how do you display the current user or principal name in a JSP page secured using Spring security library? Well, Spring Security provides a small but userful JSP tag library which contains custom tags similar to JSTL, which can show a lot of useful authentication and authorization details of current user. For example, you can use <s:authetication> tag to display the current principal details including the username of currently logged in user. The tag name is authentication here and s is the prefix you specify while importing tag using taglib directive in JSP. 

Sunday, November 5, 2023

5 Ways to Update Values in ConcurrentHashMap in Java 8 - Example Tutorial

In last article, I have showed you how to update value in HashMap and today we'll learn about how to update value in a ConcurrentHashMap. Some of you may question, can we use the same technique we used to update a value in HashMap here? well, you can but you need to keep in mind the difference between an HashMap and a ConcurrentHashMap. The HashMap is only meant to be updated by one thread at a time, hence you don't need to pay any attention to thread-safety or concurrency, but ConcurrentHashMap can be updated by multiple threads at the same time, hence you need to pay special attention. 

Monday, October 30, 2023

Why Java and Spring Developers Should Learn RESTful Web Services and Microservices

More and More companies are adopting  Microservices architecture e.g. Uber and Netflix already uses it and many startups I know is choosing REST and MicroService as the standard way to build and provide their services. This is fueling the demand for programmers who can develop robust and scalable Microservices and RESTful Web Services. Since Java is one of the most popular language for developing backend, it is also benefiting from this trend. The demand for Java developers who knows Spring framework and understand how to build RESTful web services is huge and that's why it has become a key skill in Java application development job market. 

Monday, October 23, 2023

15 Example of print() and println() methods in Java

Hello guys, if you have learned Java in early 2000 then there is  good chance that you must have written your first Java code using System.out.println(). For a long time, I have no idea what that mean but I alway use it to print messages on console. When I started working in Java and preparing for Java certification then I come to know that System is a class and out is an object of PrintStream which has println() method. That was a revelation for me. I also found that Java provides a powerful set of I/O classes for handling various input and output operations. Among these, the PrintStream class stands out as a versatile tool for writing formatted text to output streams. The print()printf() and println() methods within the PrintStream class, as well as System.out.println(), are particularly useful for printing different types of data to the console or other output destinations.

Tuesday, October 10, 2023

How to fix Eclipse - Could not reserve enough space for object heap in Java? Solution

If you are running Java program in Eclipse and ever tried playing with -Xmx parameter you know about those virtual machine initialization error e.g. "“Error occurred during initialization of VM; Could not reserve enough space for object heap”. This error usually occur when you to try to give your program, running on 32-bit JVM more than 1.4G of memory in Eclipse in Windows. It doesn't matter how much memory your machine have e.g. I have seen this error in laptops running 4GB of memory. The important thing which matter is whether JRE or JVM you are using with Eclipse is 32-bit or 64-bit. If you use 64-bit JRE in Eclipse, you can potentially allocate more than 1.4G of memory in Windows itself.

Monday, October 9, 2023

How to fix java.net.SocketException: Connection reset by peer: socket write error? [Solved]

"Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error" comes when you are writing into a connection which is already closed by your peer i.e. the other party in the connection. For example, if you are server and sending response to client but client closed its connection before you complete writing response, the write() method of DataOutputStream will throw this error. It's not necessary that this error will only come when you are using DataOutputStream, it can come even if you are just using and OutputStream or SocketOutputStream point is you are writing in a socket which is closed by other end. Here is the actual error message with stacktrace:

Friday, October 6, 2023

How does Remember Me functionality works in Spring Security?

In the last article, You have learned how to enable the remember-me functionality in Spring security and today you will learn how does Remember Me work under the hood. So far, you know that remember-me functionality uses cookie to remember users and allow auto-login (without entering password again), so you might have guessed that spring security provides hooks to generate that cookie as well as process those cookie when an already signed user open the application after the break e.g. after a day or two. As long as cookie is not expired and token is valid i.e. user hasn't changed the password, he should be able to login to your application. 

Wednesday, October 4, 2023

6 ways to sort ArrayList in Java 8? List.sort() + Collections.sort() Example Tutorial

There are many ways to sort an ArrayList in Java 8; for example. you can use the old but still rocking way to sort a List by using Collections.sort() method, or you can use the newly added sort() method in the List interface in Java, or you can use the new java.util.stream API to sort a list of objects. You now have multiple choices when it comes to sort a List or Array in Java. Though, my preferred way is Collections.sort() method because it is available to all the Java versions and its easy to use and it also allows you to sort in any custom order.  The method is overloaded which gives you ability to sort a list of objects into their natural order as well allow you to supply a Comparator of your choice to sort elements into customer order. 

Tuesday, October 3, 2023

How to enable RememberMe Functionality in Spring Security

Hello guys, most of the web application has login or authentication functionality where user need to enter their username and password to access functionalities provided by application. This is great from application's perspective because functionalities are protected from anonymous user but from user's perspective he would appreciated something which would not ask him/her to enter username and password every now and then. This is what remember me functionality of Spring security does. It allow you to build a web application which can remember their user and allow them to automatically login when the restart their browser or come back another day. 

Saturday, September 30, 2023

10 Exception handling Best Practices in Java Programming

Exception handling is an important part of writing robust Java applications. It’s a non-functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input, and so on. Java provides several exception handling features, in built-in the language itself in form of try, catch, and finally keywordJava programming language also allows you to create new exceptions and throw them using  throw and throws keyword. In reality, Exception handling is more than knowing the syntax. Writing a robust code is an art more than science, and here we will discuss few Java best practices related to Exception handling.

How to Fix Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program? Example

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

How to fix java.io.FileNotFoundException: (Access is denied)? Example

Earlier my impression was that java.io.FileNotFoundException: (Access is denied) comes when you try to read a text or binary file for which you don't have permission from the Java program but this can also come while you are using the jar command. jar command internally uses java.util.zip.ZipFile class to open any jar or war file which can throw java.io.FileNotFoundException: (Access is denied). I was trying to see the contents of the war file which was created using a recent build when I stumble upon this error, see the exact command below:

test@dev454:war-store/target jar -tvf maven-eclipse-web-demo
java.io.FileNotFoundException: maven-eclipse-web-demo (Access is denied)
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:127)
        at java.util.zip.ZipFile.<init>(ZipFile.java:88)
        at sun.tools.jar.Main.list(Main.java:979)
        at sun.tools.jar.Main.run(Main.java:224)
        at sun.tools.jar.Main.main(Main.java:1149)

How to resolve java.lang.UnsupportedClassVersionError:Unsupported major.minor version 49.0 to 65 with example

The java.lang.UnsupportedClassVersionError  is a quite common error after NoClassDefFoundError or ClassNotFoundException they all seems to related to class files but they all are different and there cause and resolution are different. In this java tutorial, we will see what is UnsupportedClassVersionError in Java? Why UnsupportedClassVersionError comes in Java? What are a class file format and version numbers associated with it and finally how to resolve UnsupportedClassVersionError in Java?