0

Столкнулся с проблемой: при интернационализации с помощью Spring в index.jsp не работает тег <fmt:message>. Хотя в остальных jsp всё отображается корректно, хотя ссылаются на один файл пропертей. На index.jsp выводит:

???app.title???

???vote.title???

Перенос index.jsp в папку WEB-INF/jsp проблему не решает.

вот мои файлы:

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
     <title>Java Enterprise (VotingSystem)</title>
</head>
<body>
<h3><fmt:message key="app.title"/> </h3>
<hr>
<ul>
    <li><a href="votes"><fmt:message key="vote.title"/></a></li>
</ul>
</body>
</html>

spring-mvc.xml:

 <?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven/>

<context:component-scan base-package="ru.alvisid.**.web"/>

<!--  all resources inside folder src/main/webapp/resources are mapped so they can be referred to inside JSP files -->
<mvc:resources mapping="/resources/**" location="/resources/"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp"/>

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
      p:cacheSeconds="5"
      p:defaultEncoding="UTF-8">
    <property name="basenames" value="file:///#{systemEnvironment['VOTINGSYSTEM_ROOT']}/config/messages/app"/>
    <property name="fallbackToSystemLocale" value="false"/>
</bean>
</beans>

web.xml:

 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<display-name>Votingsystem</display-name>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>hsqldb,datajpa</param-value>
</context-param>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring/spring-app.xml
        classpath:spring/spring-db.xml
    </param-value>
</context-param>

<!-- Spring MVC -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

app.properties:

 app.title=Voting system
 app.home=Home

 vote.title=All votes
 vote.date=date
 vote.restaurant=restaurant
 vote.votesrest=votes for restaurant
 votes.total=total votes

 datefilter.from=from date
 datefilter.to=to date

 filter.filter=filter
 filter.reset=reset filter

app_ru.properties:

 app.title=Система голосования
 app.home=На главную

 vote.title=Все голоса
 vote.date=дата
 vote.restaurant=ресторан
 vote.votesrest=количество голосов
 votes.total=всего голосов

 datefilter.from=от даты
 datefilter.to=до даты

 filter.filter=отфильтровать
 filter.reset=сбросить фильтр

votes.jsp:

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 <html>
 <head>
     <title>Votes</title>
 </head>
 <body>
 <h3><a href="../../index.jsp"><fmt:message key="app.home"/></a></h3>
 <h2><fmt:message key="vote.title"/></h2>
 <form method="post" action="votes">
     <dl>
         <dt><fmt:message key="datefilter.from"/></dt>
         <dd><input type="date" name="startDate" value="${param.startDate}">          </dd>
     </dl>
     <dl>
         <dt><fmt:message key="datefilter.to"/></dt>
         <dd><input type="date" name="endDate" value="${param.endDate}"></dd>
     </dl>
     <button type="submit"><fmt:message key="filter.filter"/></button>     <button type="reset"><fmt:message key="filter.reset"/></button>
 </form>
 <table border="1" cellpadding="8" cellspacing="0">
     <thead>
     <tr>
         <th><fmt:message key="vote.date"/></th>
         <th><fmt:message key="vote.restaurant"/></th>
         <th><fmt:message key="vote.votesrest"/></th>
         <th><fmt:message key="votes.total"/></th>
     </tr>
     </thead>
     <c:forEach items="${votes}" var="vote">
         <jsp:useBean id="vote" scope="page"           type="ru.alvisid.votingsystem.to.RestaurantVotes"/>
         <tr>
             <fmt:parseDate value="${vote.date}" pattern="yyyy-MM-dd"      var="parsedDate" type="both"/>
             <td>
                 <fmt:formatDate pattern="dd.MM.yyyy"      value="${parsedDate}"/>
             </td>
             <td>${vote.restaurantName}</td>
             <td>${vote.totalVotesForRestaurantADay}</td>
             <td>${vote.totalVotesForADay}</td>
         </tr>
     </c:forEach>
 </table>
 </body>
 </html>

Подскажите, пожалуйста, как заставить этот тег работать.

2 ответа 2

0

У тэга <fmt:message> есть свойство bundle которое вы можете использовать, чтобы "заставить этот тэг работать".

Создайте файл app.properties и положите его в resources. В файле напишите ключи/значения.

app.title=u0422u0438u0442u0443u043B
vote.title=u0422u0438u0442u0443u043B

В JSP вы можете написать:

<fmt:setBundle basename="app" var="lang"/>
<fmt:setLocale value="ru_RU"/>
<fmt:message key="app.title" bundle="${lang}"/>
<fmt:message key="vote.title" bundle="${lang}"/>
8
  • Дело в том, что У меня есть такой файл. А Спринг должен нормально видеть UTF-8 без <fmt:setBundle, как есть. И собственно видит на другой странице (код добавил выше), всё выводится отлично. app.properties добавил. 5 июн 2018 в 13:44
  • 1
    Напрямую обращаться к index.jsp неправильно.
    – Roman C
    5 июн 2018 в 15:02
  • Заменил "../../index.jsp" на "${pageContext.request.contextPath}/", но проблема остаётся, к тому же у меня файлы пропертей вынесены и доступ к ним через переменную окружения. 5 июн 2018 в 17:13
  • Переменную окружения надо удалить.
    – Roman C
    5 июн 2018 в 17:55
  • Для чего? На странице Votes.jsp всё корректно отображается. Я думал это из-за того что index.jsp не находится в папке WEB-INF/jsp, но при переносе её в эту папку всё равно отображаются вопросы 5 июн 2018 в 18:04
0

Проблема решилась следующим образом: 1) index.jsp перенесен в WEB-INF/jsp; 2) в контроллер добавлен переход на index.jsp

@GetMapping("/")
public String root() {
    return "index";
}

И всё заработало.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.