Sobes.tech
Junior

Describe the general practical principles of working with JavaServer Pages (JSP).

sobes.tech AI

Answer from AI

  • Avoid business logic in JSP. Use servlets or Spring MVC controllers for this.
  • Separate data presentation and business logic using the Model-View-Controller (MVC) pattern.
  • Use JSP Standard Tag Library (JSTL) instead of scriptlets for iteration, conditional operators, and data output.
  • Use Expression Language (EL) to access data from request, session, or application context.
  • Import necessary classes and libraries once using the directive <%@ page import="..." %> or <c:import ... />.
  • Use page, include, taglib directives to configure the page, include other resources, and use custom tags.
  • Ensure security by sanitizing user input before displaying it on the page to prevent XSS attacks.
  • Minimize the use of comments <%-- ... --%>, as they are processed by the server. Use XML comments <!-- ... --> for HTML comments.

Example of using JSTL and EL:

<%-- Example of using JSTL and EL --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Example</title>
</head>
<body>
    <h1>Hello, <c:out value="${requestScope.userName}"/>!</h1>

    <c:if test="${not empty requestScope.items}">
        <h2>Item list:</h2>
        <ul>
            <c:forEach var="item" items="${requestScope.items}">
                <li>${item}</li>
            </c:forEach>
        </ul>
    </c:if>

    <c:if test="${empty requestScope.items}">
        <p>The item list is empty.</p>
    </c:if>
</body>
</html>

Comparison of scriptlets and JSTL:

Characteristic Scriptlets (<% ... %>) JSTL (<c:forEach>, <c:if>, etc.)
Readability Low High
Maintenance Difficult Easy
Separation of logic and presentation Poor Good
Performance May be lower due to translation Often optimized
XML Compatibility No Yes

It is recommended to completely abandon scriptlets in favor of JSTL and EL.

Describe the general practical principles of working… - sobes.tech