How can I avoid Java code in JSP files, using JSP 2?

 

In JSP 2 (JavaServer Pages version 2), you can reduce the amount of Java code embedded in your JSP files by using Expression Language (EL) and JSTL (JavaServer Pages Standard Tag Library) tags. This separation of concerns makes your JSP files cleaner, more maintainable, and easier to read.

Here's an example of how you can avoid using Java code directly in JSP files using EL and JSTL:

Assuming you have a simple scenario where you want to display a list of names from a Java List in your JSP:

  1. Create a Java Servlet:

First, create a Java Servlet that retrieves the list of names and sets it as a request attribute.

java
import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); request.setAttribute("names", names); // Forward the request to the JSP request.getRequestDispatcher("/myPage.jsp").forward(request, response); } }
  1. Create a JSP File:

Next, create a JSP file (myPage.jsp) that uses EL and JSTL tags to display the list of names.

jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>My JSP Page</title> </head> <body> <h1>List of Names</h1> <ul> <c:forEach var="name" items="${names}"> <li>${name}</li> </c:forEach> </ul> </body> </html>

In this example, the c:forEach tag from the JSTL library is used to iterate over the list of names stored in the ${names} attribute, and EL (${name}) is used to display each name.

By using EL and JSTL, you avoid directly embedding Java code in your JSP file and achieve a better separation of concerns. This approach makes your JSP files more readable and easier to maintain.

Comments