Skip to content

Instantly share code, notes, and snippets.

@itzg
Created October 11, 2012 04:48
Show Gist options
  • Save itzg/3870230 to your computer and use it in GitHub Desktop.
Save itzg/3870230 to your computer and use it in GitHub Desktop.
Using messages in Spring MVC

First declare a messageSource bean and using that specific id is important.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <bean id="messageSource"
    	class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    	<property name="basename" value="classpath:messages"></property>
    </bean>
</beans>

With the configuration here place your messages.properties file (and language specific derviatives) in src/main/resources, such as

errors.invalid-name = Please provide a valid name

and then reference the message code in JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"  %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="my" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<body>
  <div>
    <spring:message code="errors.invalid-name"></spring:message>
  </div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment