JSP Code Formatting
General Guidelines
- Use two spaces for indentation instead of tabs.
- Save all files with UTF-8 encoding.
- Ensure content is encoded in UTF-8.
For JSP pages, use JSTL (JavaServer Pages Standard Tag Library) to separate logic from markup. Keep HTML clean by moving code into custom tags or Java Beans when possible. For Bloomreach-specific functionality, use HST (Hippo Site Toolkit) tags.
When writing expressions in JSTL, use the following operators:
- Use
divinstead of/for division. - Use
modinstead of%for modulo (remainder). - Use
eqinstead of==to test for equality. - Use
neinstead of!=to test for inequality. - Use
ltinstead of<to test for less than. - Use
gtinstead of>to test for greater than. - Use
leinstead of<=to test for less than or equal. - Use
geinstead of>=to test for greater than or equal. - Use
andinstead of&&for logical AND. - Use
orinstead of||for logical OR. - Use
notinstead of!for unary boolean complement. - Use
emptyto test for emptiness.
Output Escaping
Always escape output to prevent cross-site scripting (XSS) vulnerabilities and to ensure valid XHTML.
| Code Example | Output |
|---|---|
<c:out value="Bed & breakfast"/> | Bed & breakfast |
<c:out value="<script>alert('hoi');</script>"/> | <script>alert("hoi")</script> |
Internationalization
Do not hardcode text in JSP files. Always use a resource bundle for all display text.
Example:
<fmt:message key="your.message.key" var="submitValue"> <input type="submit" id="zoek-submit" name="submit" value="${submitValue}"/>
Use the fmt:formatDate tag to display dates. Specify date patterns in the resource bundle, and reference them in the tag.
Example:
<jsp:useBean id="now" class="java.util.Date" /> <fmt:message key="date.format.key" var="myDatePattern"> <fmt:formatDate value="${now}" pattern="${myDatePattern}"/>
EclipseHTMLEditor is an Eclipse plugin that supports editing JSP files.
You can use JettyLauncher to run your JSP site within Eclipse.
Refactoring
To support refactoring in JSP files, declare all variables with the following syntax:
<%--@elvariable id="document" type="org.myproject.MyBean"--%>
Always specify the concrete type for each variable. This enables IDEs such as IntelliJ IDEA to refactor EL expressions (for example, updating ${document.name} to ${document.title} if you rename the getName method to getTitle in your bean).