Tuesday, September 27, 2011

Populate JSP with messages from a properties file

I had a series of JSP pages that used certain values, questions or messages. Some of these were long, and potentially subject to change by the business group.

To eliminate typing the messages in multiple places, and potentially miss one should it change in the future, I put them all in a properties file, then loaded them to the JSP that way. Here's my setup:

1) Create the messages.properties file in the Eclipse project folder 'WebContent > WEB-INF > classes'. Entries are in the 'title=Page Title' format.

2) Create a new JSP file, messages.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<fmt:bundle basename="messages">
<fmt:message key="title" var="title"/>
</fmt:bundle>


3) At the top of the JSP you wish to use the messages, just include the 'messages.jsp' file. Then reference them like any other variable.

<%@ include file="messages.jsp" %> // ADDED HERE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>${title}</title> // USED HERE

No comments:

Post a Comment