Learn JSP in less than 5mins
Tags: java, jee, jsp, servlet
Published: 2022-08-28 01:26:00

The Java ecosystem is evolved a lot over the last 20 years, and this is shown by it's constancy and popularity in the market. And when we talk about a robust community we can guarantee the diversity and richness of libraries/frameworks like Spring, Vert.x, Quarkus, ...etc.

Unfortunately, many JEE developers start using frameworks like Spring Boot without diving into details and concepts! Well, this works if you have a solid background in one of the other programing languages or if you are a fresh developer but with time you will feel importance of these things and how to make difference and be mandatory to grow more as a Java developer/engineer.

One of these notions is related to our article, it's "Servlet" which isn't easy to present in a few lines because we need to cover other APIs and concepts like "Applets" but we can say "Servlet is a Java class used to extend the capabilities of a server".

> Sadly, I can't dive into these concepts this time but sure, I will do in the future.

## What's JSP?

In the past, building JEE applications was based on Servlets which is painful because we don't separate between layers. This pain was resolved by the MVC (Model-View-Controller) pattern that pushes the JEE ecosystem to introduce JSP.

> You can say: 
> {
>   "Model": "JDBC"
>   "View": "JSP"
>   "Controller": "Servlet"
> }

JavaServer Pages (JSP) is a technology for building web pages that support dynamic content by helping to insert Java code into HTML pages.

> You can think of it like a template engine!

## JSP Manual

### Expression

When you need to print dynamic content on your page from a variable or method value, you should use the expression tag;

```jsp
<%= some java expression (variable/method) %>
```

Example:

```jsp
<!-- jsp file -->
<h1>5 multiplied by 10 equals: <%= 5*10 %></h1>
<!-- generated html -->
<h1>5 multiplied by 10 equals: 50</h1>
```

### Scriptlet

When you need to write java code inside jsp for some reasons, you can use the scriptlet tag;

```jsp
<% some java code (1 to n lines) %>
```

Example: 

```jsp
<!-- jsp file -->
<%
int sum = 0;
for (int i = 0; i <= 5; i++) {
  // some logic
  sum += i;
}
out.println(String.format("<span> sum: %s </span>", sum));
%>
<!-- generated html -->
<span> sum: 15 </span>
```

> "out" is one of the JSP implicit objects which gives the ability to print the value on the page.

### Declaration

When you need to declare java variable and/or method inside jsp to re-use it later or any reason, you can use the declaration tag;

```jsp
<%! java variable/method declaration %>
```

Example: 

```jsp
<!-- jsp file -->
<%!
String makeItLower (String str) {
  return str.toLowerCase();
} 
%>
Lower case "Hello World!": <%= makeItLower("Hello World!") %>
<!-- generated html -->
Lower case "Hello World!": hello world! %>
```

### Best Practice

Declaring java code inside jsp file isn't a good idea because will ship a bad development experience. So, we can reduce the `scriptlet` and `declaration` tags usage by calling java class from jsp by;

```jsp
<%@ page import="<package-name>.<class-name>" %>
```

Example:

```java
// java file
package com.imedjaberi.jspartile;

public class Utils {
  public static String makeItLower (String str) {
    return str.toLowerCase();
  }
}
```

```jsp
<!-- jsp file -->
<%@ page import="com.imedjaberi.jspartile.Utils" %>
<html>
  <body>
    Say: <%= Utils.makeItLower("Hello World!") %>
  </body>
</html>
```

> This is not the only way to call java method inside jsp file, we can also use the inline way;
> ```jsp
> <html>
>  <body>
>    Say: <%= com.imedjaberi.jspartile.Utils.makeItLower("Hello World!") %>
>  </body>
> </html>
> ```

For import methods from different packages;

```jsp
<%@ page import="com.imedjaberi.jspartile.*, java.utils.ArrayList" %>
```

### Implicit Objects

As we mention from the beginning JSP is a server technology, so it's designed with few implicit objects to interact with server capabilities.

List of commonly used JSP objects:

Object        | Type                  | Description                                           |
------------- | --------------------- | ----------------------------------------------------- |
request      | HttpServletRequest    | Contains HTTP request headers and form data           |
response      | HttpServletResponse   | Provides HTTP support for sending response            |
out           | JspWriter             | JspWriter for including content in HTML page          |
session       | HttpSession           | Unique session for each user of the web application   |
application   | ServletContext        | Shared data for all users of the web application      |

### Compose UI

When you're the project be bigger, this section will be your bible.
You can imagine that you have 10 pages and they all have the same header and footer blocks, you will find yourself re-creating the two blocks 10 times. You can do some math if you have more pages and/or more blocks. 

As software engineers, we try as much as possible to follow engineering principles like DRY and from this perspective, we must split these blocks into separate files and use them as reusable blocks. This be possible through the include tag; 

```jsp
<jsp:include page="<file-namle>.<extension[html|jsp]>" />
```

Example: 

```html
<!-- header.html -->
<header>
  <h1>Welcome to header block!</h1>
</header>
```

```jsp
<!-- footer.jsp -->
<footer>
  <h1>Welcome to footer block (Last updated: <%= new java.util.Date() %>)!</h1>
</footer>
```

```jsp
<!-- index.jsp -->
<html>
  <body>
    <jsp:include page="header.html" />
    <main>
      Blah blah blah ... <br />
      Blah blah blah ... <br />
    </main>
    <jsp:include page="footer.jsp" />
  </body>
</html>
```

### Forms

In this section, we'll cover a quick example of how to navigate between pages and access form data.

```jsp
<!-- index.jsp -->
<form action="board.jsp">
  Full name: <input name="fullName" />
  Country: <select name="country">
      <option>Tunisia</option>
      <option>UK</option>
      <option>Spain</option>
      <option>Germany</option>
      <option>France</option>
  </select>
  Gender: <br />
  <input type="radio" name="gender" value="Male" /> Male
  <input type="radio" name="gender" value="Female" /> Female
  Favorite programing language: <br />
  <input type="radio" name="fPLang" value="JavaScript" /> JavaScript
  <input type="radio" name="fPLang" value="Java" /> Java
  <input type="radio" name="fPLang" value="Go" /> Go
  <input type="radio" name="fPLang" value="Elixir" /> Elixir
  <input type="radio" name="fPLang" value="Elm" /> Elm

 <button type="submit">Submit</button>
</form>
```

```jsp
<!-- board.jsp -->
The developer is confirmed: <%= request.getParameter("fullName") %>
The developer country: <%= request.getParameter("country") %>
The developer gender: <%= request.getParameter("gender") %>
The developer favorite programing language: <br/>
<ul>
  <% 
    String[] langs = request.getParameterValues("fPLang");
    for (String lang: langs) {
      out.println("<li>" + lang + "</li>");
    }
  %>
</ul>
```

> We have an alternative to `<%=request.getParameter("fullName")%>` is `${param.fullName}`.


### State Management

When we talk about the UI, we can't ignore talk about state management which is handled through [session](https://www.w3schools.in/jsp/session) and cookies on jsp.

> This isn't covered in the current article but in the near future, will do through an article that talks about building an app based on the MVC pattern with Servlet, JSP, and JDBC.

<hr />

#### 📚 Ressources:

- https://www.javatpoint.com/jsp-tutorial
- https://dev.to/3imed_jaberi/connect-your-java-with-any-sql-databases-362p

<hr />

#### Did I miss something? Let me know in the comment section and let’s work on that.

#### Thank you for reading. I hope this will help you on your