DEV Community

Imed Jaberi
Imed Jaberi

Posted on

Learn JSP in less than 5mins

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;

<%= some java expression (variable/method) %>
Enter fullscreen mode Exit fullscreen mode

Example:

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

Scriptlet

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

<% some java code (1 to n lines) %>
Enter fullscreen mode Exit fullscreen mode

Example:

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

"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;

<%! java variable/method declaration %>
Enter fullscreen mode Exit fullscreen mode

Example:

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

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;

<%@ page import="<package-name>.<class-name>" %>
Enter fullscreen mode Exit fullscreen mode

Example:

// java file
package com.imedjaberi.jspartile;

public class Utils {
  public static String makeItLower (String str) {
    return str.toLowerCase();
  }
}
Enter fullscreen mode Exit fullscreen mode
<!-- jsp file -->
<%@ page import="com.imedjaberi.jspartile.Utils" %>
<html>
  <body>
    Say: <%= Utils.makeItLower("Hello World!") %>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is not the only way to call java method inside jsp file, we can also use the inline way;

<html>
 <body>
   Say: <%= com.imedjaberi.jspartile.Utils.makeItLower("Hello World!") %>
 </body>
</html>

For import methods from different packages;

<%@ page import="com.imedjaberi.jspartile.*, java.utils.ArrayList" %>
Enter fullscreen mode Exit fullscreen mode

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:include page="<file-namle>.<extension[html|jsp]>" />
Enter fullscreen mode Exit fullscreen mode

Example:

<!-- header.html -->
<header>
  <h1>Welcome to header block!</h1>
</header>
Enter fullscreen mode Exit fullscreen mode
<!-- footer.jsp -->
<footer>
  <h1>Welcome to footer block (Last updated: <%= new java.util.Date() %>)!</h1>
</footer>
Enter fullscreen mode Exit fullscreen mode
<!-- 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>
Enter fullscreen mode Exit fullscreen mode

Forms

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

<!-- 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>
Enter fullscreen mode Exit fullscreen mode
<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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 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.


πŸ“š Ressources:


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

Top comments (0)