<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Prafful Lachhwani</title>
    <description>The latest articles on Forem by Prafful Lachhwani (@prafful).</description>
    <link>https://forem.com/prafful</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F490390%2F5ba86db6-507d-4e8f-8897-d602907ddf45.JPG</url>
      <title>Forem: Prafful Lachhwani</title>
      <link>https://forem.com/prafful</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/prafful"/>
    <language>en</language>
    <item>
      <title>6 Tips and Tricks to avoid NullPointerException</title>
      <dc:creator>Prafful Lachhwani</dc:creator>
      <pubDate>Fri, 11 Feb 2022 11:50:06 +0000</pubDate>
      <link>https://forem.com/prafful/6-tips-and-tricks-to-avoid-nullpointerexception-5dd</link>
      <guid>https://forem.com/prafful/6-tips-and-tricks-to-avoid-nullpointerexception-5dd</guid>
      <description>&lt;p&gt;Null references have historically been a bad idea, even Tony Hoare who invented &lt;code&gt;null&lt;/code&gt; references calls it The Billion Dollar Mistake.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object-oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years." ~ Charles Antony Richard Hoare&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Overview &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;NullPointerException can sometimes be frustrating. It can break your application. It could be difficult to find an actual issue from the production server logs. In this article, I will explain what is &lt;code&gt;java.lang.NullPointerException&lt;/code&gt;? Also, we will see various tips and tricks that will help you in writing better code. If you already have some idea about &lt;em&gt;NullPointerException&lt;/em&gt;, skip to the How to avoid NullPointerException? section.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What is NullPointerException? &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;The NullPointerException is a runtime exception when a program tries to access an object with a null reference. Or, does any operation on a null object. Here is a simple code snippet that throws &lt;code&gt;java.lang.NullPointerException&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0feafq8rdgguc7glkne3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0feafq8rdgguc7glkne3.png" alt="carbon.png" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here &lt;code&gt;str&lt;/code&gt; is null, any operations on it will throw NullPointerException. The output if we try to run this code:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzm0jh42jsq3wiksxss2s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzm0jh42jsq3wiksxss2s.png" alt="carbon (1).png" width="800" height="271"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This was a trivial example, imagine if our String &lt;code&gt;str&lt;/code&gt; was given as an argument or in result set from a database call, the application will break. In the next section, we will see some best practices to avoid NullPointerException.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How to avoid NullPointerException? &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;One of the famous ways to avoid &lt;code&gt;java.lang.NullPointerException&lt;/code&gt; is to add null checks wherever plausible. However, this approach will make your code bloated with &lt;code&gt;null != something&lt;/code&gt; statements. Here are some best practices that you can follow to make your code &lt;em&gt;NullPointerException&lt;/em&gt; proof. &lt;/p&gt;

&lt;h3&gt;
  
  
  3.1. Using Optional Class
&lt;/h3&gt;

&lt;p&gt;The optional class feature was introduced in Java 8. Here is an example that explains, how you can leverage the Optional class feature to reduce &lt;em&gt;NullPointerExceptions&lt;/em&gt;?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.Optional&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Example&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;strOpt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ofNullable&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strOpt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;orElse&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;""&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt; &lt;span class="c1"&gt;// prints 0&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;strOpt.orElse("")&lt;/code&gt; gives us an empty string when &lt;code&gt;str&lt;/code&gt; is null otherwise it returns the original string. Below are some more useful methods that can be used with the Optional class for different scenarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;public boolean isPresent()&lt;/code&gt; - Returns &lt;em&gt;true&lt;/em&gt; if there is a value present, otherwise &lt;em&gt;false&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;public T get()&lt;/code&gt; - If a value is present in this &lt;em&gt;Optional&lt;/em&gt;, returns the value, otherwise throws &lt;em&gt;NoSuchElementException&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;public T orElseGet(Supplier&amp;lt;? extends T&amp;gt; other)&lt;/code&gt; - Returns the value if present, otherwise invoke other and return the result of that invocation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To read more about the Optional class refer &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="noopener noreferrer"&gt;Optional (Java Platform SE 8)&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2. Using StringUtils
&lt;/h3&gt;

&lt;p&gt;StringUtils handles &lt;code&gt;null&lt;/code&gt; input Strings quietly. Meaning if a null String is passed it does not throw &lt;em&gt;NullPointerException&lt;/em&gt;. It considers the null String as blank. For using this in your project you may need to import &lt;code&gt;StringUtils&lt;/code&gt; from &lt;a href="https://mvnrepository.com/artifact/org.apache.commons/commons-lang3" rel="noopener noreferrer"&gt;Apache Commons Lang&lt;/a&gt;. Bellow code demonstrate the null safety feature of &lt;em&gt;StringUtils&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;org.apache.commons.lang3.StringUtils&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Example&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StringUtils&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// prints 0&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some useful StringUtils method are as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;public static boolean isNotBlank(CharSequence cs)&lt;/code&gt; - Checks if a CharSequence is not empty, not null and not whitespace only.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;public static boolean equals(CharSequence cs1, CharSequence cs2)&lt;/code&gt; - Compares two CharSequences, returning true if they represent equal sequences of characters. Returns &lt;em&gt;true&lt;/em&gt; if both arguments are &lt;em&gt;null&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more about StringUtils &lt;a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.3. Using Primitive Datatypes
&lt;/h3&gt;

&lt;p&gt;Since primitive datatypes can never be null. Wherever possible try using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;int&lt;/code&gt; instead of &lt;code&gt;Integer&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;boolean&lt;/code&gt; instead of &lt;code&gt;Boolean&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;float&lt;/code&gt; instead of &lt;code&gt;Float&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;double&lt;/code&gt; instead of &lt;code&gt;Double&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;long&lt;/code&gt; instead of &lt;code&gt;Long&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;short&lt;/code&gt; instead of &lt;code&gt;Short&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;char&lt;/code&gt; instead of &lt;code&gt;Character&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3.4. Calling equals on literal
&lt;/h3&gt;

&lt;p&gt;While comparing two Strings or elements of an enum it is always recommended to use a non-null value at the left-hand side. Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Example&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"abc"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"abc"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;// NullPointerException here&lt;/span&gt;
        &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.5. Using Ternary Operator
&lt;/h3&gt;

&lt;p&gt;Using a ternary operator you can prevent your code from throwing &lt;em&gt;NullPointerExceptions&lt;/em&gt;, Here is how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Example&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code will call &lt;code&gt;length()&lt;/code&gt; method only if str is not &lt;em&gt;null&lt;/em&gt; hence preventing &lt;em&gt;NullPointerException&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.6. Throwing IllegalArgumentException
&lt;/h3&gt;

&lt;p&gt;It is always a best practice to throw an &lt;em&gt;IllegalArgumentException&lt;/em&gt; if the argument is null or something that is not expected. This may save hours of figuring out what went wrong. Here is an example code that throws &lt;em&gt;IllegalArgumentException&lt;/em&gt; when the argument passed is null:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Example&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;printStringLength&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;printStringLength&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;IllegalArgumentException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"String str was null"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;str&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Conclusion
&lt;/h2&gt;

&lt;p&gt;One of my favourite way of avoiding NullPointerException is by adding this statement &lt;code&gt;null != obj.getSomething()&lt;/code&gt;. But, we're mature developers we don't want to bloat our code with these null check statements, imagine a code that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt; 
        &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSomething&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; 
        &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSomething&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;fromHere&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;obj&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSomething&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;fromHere&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;property&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// do something with obj.getSomething().fromHere().property()&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Looks crazy right? Trust me I've written this in one of my applications to stop &lt;em&gt;NullPointerExceptions&lt;/em&gt;. However, now we know how to avoid them in a better way.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Thank you for reading! Do let me know in the comments, what was the craziest thing you did for dealing with NullPointerExceptions.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>nullpointerexception</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>How to choose the right backend technology?</title>
      <dc:creator>Prafful Lachhwani</dc:creator>
      <pubDate>Tue, 25 Jan 2022 13:33:31 +0000</pubDate>
      <link>https://forem.com/prafful/how-to-choose-right-backend-26f2</link>
      <guid>https://forem.com/prafful/how-to-choose-right-backend-26f2</guid>
      <description>&lt;p&gt;Web technologies are growing so fast that we now have tons of modern tools and frameworks. Be it a choice of frontend, backend or database.  Many developers have this big question - Which tech stack I should begin with?🤔&lt;/p&gt;

&lt;p&gt;Sometimes we end up choosing the one we worked on before or language we are comfortable in. As human nature, we always stick to our comfort zone and that's where things start going wrong. This may include choosing a framework being overkill.  Or, even worse, we pivot from our existing tech stack in the middle of a project and end up re-writing the code in a different language.🤦‍♂️&lt;/p&gt;

&lt;p&gt;So, it's important to choose the right tech stack before starting a new project. With this post, I will help you with a thought process so that you could choose the best tech stack.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Getting the content
&lt;/h2&gt;

&lt;p&gt;This is a three-part series. In this post, I will talk about various backend technologies such as Node.js, Java - Spring, Laravel - PHP and Python - Django. We will compare them on different aspects such as reliability, scalability, performance, security, developer's experience and most importantly cost of hosting. In the later posts, we will compare different frontend technologies and various databases. So, let's get going!&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What is a backend?
&lt;/h2&gt;

&lt;p&gt;In a nutshell, the backend has the code which runs on the server-side and is responsible for handling and managing storage, database and other resources. The backend is also called the data access layer of software.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fonfaai565vsk32529mzp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fonfaai565vsk32529mzp.png" alt="image.png" width="800" height="556"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One should always start with choosing the right backend. Because it acts as the backbone of your application. We have so many alternatives out there, we will cover some popular backend frameworks in this article and will see which one is appropriate for a given scenario.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Node.js
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://nodejs.org/en/about/" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; uses asynchronous programming! Meaning, it is non-blocking. In other words, It does not wait for a resource to finish the job. It is immediately ready to take up the next request and gives a callback when it's done. Node.js runs like a rocket and it is very scalable.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When to use Node.js?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;When your application is highly event-driven and performs lots of I/O operations. Also, when you have to make various API calls from the backend itself. Here in this scenario, you can leverage its non-blocking feature.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When NOT to use Node.js?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;When you have a heavy algorithm or a job that consumes lots of CPU cycles. Because Node.js runs on a single thread just like client-side js, your application will be very inefficient for CPU intensive jobs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  4. Java - Spring Boot
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://spring.io/" rel="noopener noreferrer"&gt;Spring&lt;/a&gt; is a powerful, lightweight, and most popular framework which makes Java quicker, easier and safer to use. &lt;a href="https://spring.io/projects/spring-boot" rel="noopener noreferrer"&gt;Spring boot&lt;/a&gt; helps you to build production-ready Spring-based applications. It serves 80% of everyone's needs for a modern web application. It is highly useful for creating stand-alone, production-grade applications with minimum effort.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When to use Spring Boot?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;When your primary focus is security, maybe you want to write banking or financial applications. Where you cannot compromise with security, Spring boot will be the best option. As Java supports multithreading out of the box, it becomes a great choice for building complex and highly concurrent web applications. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When NOT to use Spring Boot?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Although, there are no limitations to the spring framework, it can serve all your needs. But, sometimes trivial apps which do not need heavy computation, spring as a backend will be an overkill. The only thing for saying no to Spring boot is that it's a bit complex and requires a lot of expertise.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  5. PHP - Laravel
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;PHP is an old friend who introduced me to web development.🥺 &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://laravel.com/" rel="noopener noreferrer"&gt;Laravel&lt;/a&gt; is an open-source PHP framework. It follows an MVC (Model-View-Controller) architecture. Laravel makes life easier as it has so many developer-friendly features, one of them is query builder or &lt;a href="https://laravel.com/docs/8.x/eloquent#introduction" rel="noopener noreferrer"&gt;ORM&lt;/a&gt; (Object-Relational Mapping). Before Laravel, it seemed like PHP is dying but now it is one of the competitive frameworks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhg5kdzgxu1ymilem1rcf.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhg5kdzgxu1ymilem1rcf.jpeg" alt="is-php-dead-0-1.jpg" width="800" height="456"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When to use Laravel?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;When the time to market is the key, then Laravel is the best choice. Because it has so many salient features that make web development very fast as compared to other frameworks out there. Also, Laravel can be hosted on a shared hosting thus making it cheapest amongst all, so when time and cost is the key you should go with Laravel.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When NOT to use Laravel?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;PHP is not considered much secure as compared to Spring and Node.js, however, Laravel prevents some of the basic attacks such as SQL injection and cross-site scripting attacks and adds an extra layer of security to it. But still, PHP is never recommended for applications where security is a must.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. Python - Django
&lt;/h2&gt;

&lt;p&gt;Django is a fast, secure and scalable high-level Python web framework. Django encourages rapid and clean application development. It takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. &lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When to use Django?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Since, Django is based on python it supports powerful machine learning libraries like PyTorch, NumPy, etc. Its computational and statistical capabilities make it the ideal platform for machine learning applications. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;When NOT to use Django?&lt;/em&gt;
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Django is not suitable for smaller projects with only a few features and requirements. Because it's a "Batteries included" framework, it has so much boilerplate code which small projects don't need. As a result, consuming unnecessary server processing time and bandwidth.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  7. Conclusion
&lt;/h2&gt;

&lt;p&gt;I hope you found the article insightful! We have discussed the four most popular backend frameworks and how to make the right choice.&lt;/p&gt;

&lt;p&gt;And stay tuned for the next article of this series. In that, I will compare the most popular front-end frameworks so that you can make the right decision.&lt;/p&gt;

&lt;p&gt;Please give your valuable feedback in the comment section, tell me what I missed about these frameworks.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>java</category>
      <category>python</category>
      <category>php</category>
    </item>
    <item>
      <title>Spring Boot REST API authentication best practices using JWT</title>
      <dc:creator>Prafful Lachhwani</dc:creator>
      <pubDate>Thu, 20 Jan 2022 15:31:42 +0000</pubDate>
      <link>https://forem.com/prafful/spring-boot-rest-api-authentication-best-practices-using-jwt-2022-3j2d</link>
      <guid>https://forem.com/prafful/spring-boot-rest-api-authentication-best-practices-using-jwt-2022-3j2d</guid>
      <description>&lt;h3&gt;
  
  
  1. Overview
&lt;/h3&gt;

&lt;p&gt;In this tutorial I will explain how you can implement production ready, token based REST API authentication using JWT (JSON Web Tokens). Further we will use these tokens to identify our acting user in a HTTP request to our API. For this tutorial we will use MongoDB to persist our user data, you can choose any database of your choice.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. What is a JWT?
&lt;/h3&gt;

&lt;p&gt;JSON Web Token(JWT) is an encoded string which we will use to identify our user in this case. A JWT consist of three parts separated by a period(&lt;code&gt;.&lt;/code&gt;):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Header&lt;/strong&gt;: It contains signing algorithm like SHA256.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Payload&lt;/strong&gt;: It contains our user data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Signature&lt;/strong&gt;: To verify the message wasn't changed along the way, making it secure.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Combing all three will make our JWT look something like this &lt;code&gt;xxxxx.yyyyy.zzzzz&lt;/code&gt;. To learn more about JWT please visit - &lt;a href="https://jwt.io/" rel="noopener noreferrer"&gt;https://jwt.io/&lt;/a&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  3. Project Initialization
&lt;/h3&gt;

&lt;p&gt;We will start y initializing our Spring Boot project using &lt;a href="https://start.spring.io/#!type=maven-project&amp;amp;language=java&amp;amp;platformVersion=2.6.2&amp;amp;packaging=jar&amp;amp;jvmVersion=11&amp;amp;groupId=com.example&amp;amp;artifactId=api&amp;amp;name=API%20Authentication&amp;amp;description=Demo%20project%20for%20token%20based%20API%20authentication&amp;amp;packageName=com.example.api&amp;amp;dependencies=devtools,lombok,web,security,data-mongodb" rel="noopener noreferrer"&gt;Spring Initiailizr&lt;/a&gt;. For starters I have added 5 dependencies, you can tweak it a little according to your project needs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqo6gnlq2haxtawpxgn9c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqo6gnlq2haxtawpxgn9c.png" alt="spring init.png" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hit generate and import project in your favorite IDE. Also, don't forget to add database properties in &lt;code&gt;application.properties&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.data.mongodb.database=your_db_name_here
spring.data.mongodb.port=27017
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Additional Dependencies
&lt;/h3&gt;

&lt;p&gt;You will have to add following dependencies in order to use &lt;code&gt;JWT&lt;/code&gt; in your project. &lt;code&gt;commons-lang3&lt;/code&gt; is optional, I personally use it for its various utility classes. &lt;/p&gt;

&lt;h4&gt;
  
  
  For maven based projects:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-api&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.11.2&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-impl&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.11.2&amp;lt;/version&amp;gt;
    &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jjwt-jackson&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;0.11.2&amp;lt;/version&amp;gt;
    &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.apache.commons&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;commons-lang3&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.12.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  For gradle based projects:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dependencies {
    implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
    runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2',
             'io.jsonwebtoken:jjwt-jackson:0.11.2',
             'org.apache.commons:commons-lang3:3.0'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Project Structure
&lt;/h3&gt;

&lt;p&gt;We will follow MVC pattern, please refer to following project structure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy7k9g3fb1pe91pv6xzli.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy7k9g3fb1pe91pv6xzli.png" alt="image.png" width="479" height="785"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Configuration
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;WebSecurityConfig.java&lt;/code&gt;, we will modify default spring security features by extending &lt;code&gt;WebSecurityConfigurerAdapter&lt;/code&gt; class. Here we will define our HTTP request filter and a default response when the user is unauthenticated. It will act as a middleware for all our HTTP requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.config;

import com.example.api.util.JwtRequestFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService jwtUserDetailsService;
    private final JwtRequestFilter jwtRequestFilter;

    public WebSecurityConfig(UserDetailsService jwtUserDetailsService, JwtRequestFilter jwtRequestFilter) {
        this.jwtUserDetailsService = jwtUserDetailsService;
        this.jwtRequestFilter = jwtRequestFilter;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests().antMatchers("/auth/*").permitAll().anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint((request, response, authException) -&amp;gt; {
            Map&amp;lt;String, Object&amp;gt; responseMap = new HashMap&amp;lt;&amp;gt;();
            ObjectMapper mapper = new ObjectMapper();
            response.setStatus(401);
            responseMap.put("error", true);
            responseMap.put("message", "Unauthorized");
            response.setHeader("content-type", "application/json");
            String responseMsg = mapper.writeValueAsString(responseMap);
            response.getWriter().write(responseMsg);
        }).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above &lt;code&gt;configure(HttpSecurity httpSecurity)&lt;/code&gt; method we have defined to permit all request starting  with &lt;code&gt;/auth&lt;/code&gt; route that's where we will add our Authentication Controller. If the request is unauthorized our API will throw a &lt;code&gt;401&lt;/code&gt; error message.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpw81od4sag7scr6gkemu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpw81od4sag7scr6gkemu.png" alt="image.png" width="800" height="240"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Request Filter
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;JwtRequestFilter.java&lt;/code&gt; we will define our request filter which we mentioned in our API middleware in previous chapter. For this we will extend &lt;code&gt;OncePerRequestFilter&lt;/code&gt;, Spring guarantees that it is executed only once for a given request. &lt;/p&gt;

&lt;p&gt;In this &lt;code&gt;doFilterInternal()&lt;/code&gt; method we will fetch JWT token from the request header and process it by validating and obtaining username from token's payload. Further if token is valid we will fetch user from database and add it in &lt;code&gt;SecurityContextHolder&lt;/code&gt;, we can further use it any of our service to perform various user related operations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.util;

import com.example.api.service.JwtUserDetailsService;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    private final JwtUserDetailsService jwtUserDetailsService;
    private final JwtTokenUtil jwtTokenUtil;

    public JwtRequestFilter(JwtUserDetailsService jwtUserDetailsService, JwtTokenUtil jwtTokenUtil) {
        this.jwtUserDetailsService = jwtUserDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String requestTokenHeader = request.getHeader("Authorization");
        if (StringUtils.startsWith(requestTokenHeader,"Bearer ")) {
            String jwtToken = requestTokenHeader.substring(7);
            try {
                String username = jwtTokenUtil.getUsernameFromToken(jwtToken);
                if (StringUtils.isNotEmpty(username)
                        &amp;amp;&amp;amp; null == SecurityContextHolder.getContext().getAuthentication()) {
                    UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
                    if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                                new UsernamePasswordAuthenticationToken(
                                        userDetails, null, userDetails.getAuthorities());
                        usernamePasswordAuthenticationToken
                                .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext()
                                .setAuthentication(usernamePasswordAuthenticationToken);
                    }
                }
            } catch (IllegalArgumentException e) {
                logger.error("Unable to fetch JWT Token");
            } catch (ExpiredJwtException e) {
                logger.error("JWT Token is expired");
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }
        chain.doFilter(request, response);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;JwtTokenUtil.java&lt;/code&gt; we will perform all JWT token related operations such as generating new token and Validating given token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil implements Serializable {

    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;

    Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public &amp;lt;T&amp;gt; T getClaimFromToken(String token, Function&amp;lt;Claims, T&amp;gt; claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public String generateToken(UserDetails userDetails) {
        Map&amp;lt;String, Object&amp;gt; claims = new HashMap&amp;lt;&amp;gt;();
        return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000)).signWith(key).compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) &amp;amp;&amp;amp; !isTokenExpired(token));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. Model and Repository
&lt;/h3&gt;

&lt;p&gt;We will use  &lt;a href="https://projectlombok.org/" rel="noopener noreferrer"&gt;Lombok framework&lt;/a&gt; here to quickly create our &lt;code&gt;User.java&lt;/code&gt; model. It is completely optional but it is my favorite way of defining a model class. Afterall life is too short to write getters and setters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document("users")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id
    private String userName;
    private String firstName;
    private String lastName;
    @Indexed(unique = true)
    private String email;
    private String password;
    private String role;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will write our &lt;code&gt;UserRepository.java&lt;/code&gt; interface and define a method to fetch user details from username.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.repository;

import com.example.api.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface UserRepository extends MongoRepository&amp;lt;User, String&amp;gt; {

    @Query(value = "{userName:'?0'}")
    User findUserByUsername(String username);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. UserDetailsService
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;JwtUserDetailsService.java&lt;/code&gt; class we will customize default spring security way of getting user by implementing &lt;code&gt;UserDetailsService&lt;/code&gt; interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.service;

import com.example.api.repository.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JwtUserDetailsService implements UserDetailsService {

    final UserRepository userRepository;

    public JwtUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.example.api.model.User user = userRepository.findUserByUsername(username);
        List&amp;lt;GrantedAuthority&amp;gt; authorityList = new ArrayList&amp;lt;&amp;gt;();
        authorityList.add(new SimpleGrantedAuthority("USER_ROLE"));
        return new User(user.getUserName(), user.getPassword(), authorityList);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  10. Controllers
&lt;/h3&gt;

&lt;p&gt;Last but not the least we will define controllers in order to communicate with our API. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;AuthenticationController.java&lt;/code&gt; will deal with user login and register. In both the routes we will generate JWT tokens and send it in response to the user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.controller;

import com.example.api.model.User;
import com.example.api.repository.UserRepository;
import com.example.api.service.JwtUserDetailsService;
import com.example.api.util.JwtTokenUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

    protected final Log logger = LogFactory.getLog(getClass());

    final UserRepository userRepository;
    final AuthenticationManager authenticationManager;
    final JwtUserDetailsService userDetailsService;
    final JwtTokenUtil jwtTokenUtil;

    public AuthenticationController(UserRepository userRepository, AuthenticationManager authenticationManager,
                                    JwtUserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil) {
        this.userRepository = userRepository;
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @PostMapping("/login")
    public ResponseEntity&amp;lt;?&amp;gt; loginUser(@RequestParam("user_name") String username,
                                       @RequestParam("password") String password) {
        Map&amp;lt;String, Object&amp;gt; responseMap = new HashMap&amp;lt;&amp;gt;();
        try {
            Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username
                    , password));
            if (auth.isAuthenticated()) {
                logger.info("Logged In");
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                String token = jwtTokenUtil.generateToken(userDetails);
                responseMap.put("error", false);
                responseMap.put("message", "Logged In");
                responseMap.put("token", token);
                return ResponseEntity.ok(responseMap);
            } else {
                responseMap.put("error", true);
                responseMap.put("message", "Invalid Credentials");
                return ResponseEntity.status(401).body(responseMap);
            }
        } catch (DisabledException e) {
            e.printStackTrace();
            responseMap.put("error", true);
            responseMap.put("message", "User is disabled");
            return ResponseEntity.status(500).body(responseMap);
        } catch (BadCredentialsException e) {
            responseMap.put("error", true);
            responseMap.put("message", "Invalid Credentials");
            return ResponseEntity.status(401).body(responseMap);
        } catch (Exception e) {
            e.printStackTrace();
            responseMap.put("error", true);
            responseMap.put("message", "Something went wrong");
            return ResponseEntity.status(500).body(responseMap);
        }
    }

    @PostMapping("/register")
    public ResponseEntity&amp;lt;?&amp;gt; saveUser(@RequestParam("first_name") String firstName,
                                      @RequestParam("last_name") String lastName,
                                      @RequestParam("user_name") String userName, @RequestParam("email") String email
            , @RequestParam("password") String password) {
        Map&amp;lt;String, Object&amp;gt; responseMap = new HashMap&amp;lt;&amp;gt;();
        User user = new User();
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setEmail(email);
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user.setRole("USER");
        user.setUserName(userName);
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        String token = jwtTokenUtil.generateToken(userDetails);
        userRepository.save(user);
        responseMap.put("error", false);
        responseMap.put("username", userName);
        responseMap.put("message", "Account created successfully");
        responseMap.put("token", token);
        return ResponseEntity.ok(responseMap);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example of response to our register request:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F87eauis300607rfsbnjb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F87eauis300607rfsbnjb.png" alt="image.png" width="800" height="226"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can save this token from response in local storage of your client (Reactive web or Mobile app) and use this token later in protected routes of your API. If we provide invalid credentials to our login request we will get a response with error code 401:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8a3gz0u1xo6xxa8pm7x7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8a3gz0u1xo6xxa8pm7x7.png" alt="image.png" width="800" height="184"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now its time to actually use our JWT token to identify user associated to a HTTP request. Following code snippet will help you get the authenticated user anywhere in your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Authentication authentication = SecurityContextHolder
                .getContext().getAuthentication();
String username = authentication.getName();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For testing we will define &lt;code&gt;UserController.java&lt;/code&gt;. Here you can get the user we added  earlier during request filter in &lt;code&gt;SecurityContextHolder&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.api.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping
    public Map&amp;lt;String, Object&amp;gt; getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map&amp;lt;String, Object&amp;gt; userMap = new HashMap&amp;lt;&amp;gt;();
        userMap.put("username", authentication.getName());
        userMap.put("error", false);
        return userMap;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we will send the newly created JWT token in Authorization header we will get a proper response as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffk56cz75jse6p8frs9q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffk56cz75jse6p8frs9q.png" alt="image.png" width="800" height="184"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  11. Conclusion
&lt;/h3&gt;

&lt;p&gt;We saw how you can implement token based authentication for REST API and various amazing frameworks to make life easier. &lt;/p&gt;

&lt;p&gt;Complete code for this tutorial is commited in my &lt;a href="https://github.com/iamprafful/rest-api-authentication-tutorial" rel="noopener noreferrer"&gt;Github repository&lt;/a&gt;. Don't forget to hit the star button :p&lt;/p&gt;

&lt;p&gt;Thank you for reading this post, please give your valuable feedback in comments section.&lt;/p&gt;

</description>
      <category>java</category>
      <category>mongodb</category>
      <category>spring</category>
      <category>jwt</category>
    </item>
  </channel>
</rss>
