Search code examples
javaspringresourcebundle

Spring MVC - one message code works, another not and both are in the same file


I'm getting this error:

No message found under code 'DuplicateKey.user.username' for locale 'sk_SK'.

There are many questions on SO about messages files not loading properly, but my problem is that the file is loaded properly for sure. In my resource bundle I have two files: messages.properties messages_sk_SK.properties

The contents of messages_sk_SK.properties are:

Size.user.username=Meno musi mat 5 az 80 znakov.
DuplicateKey.user.username=Uzivatel s takym menom uz existuje.

The first message works fine. Code from my Entity:

@Size(min = 5, max = 80)
private String username;

The second error message is also for username. Here's the code from my controller:

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signupPost(@Valid User user, BindingResult result) {
    if (result.hasErrors()) {
        return "signup";
    }

    user.setAuthority("user");
    user.setEnabled(true);

    try {
        userService.create(user);
    } catch (DuplicateKeyException e) {
        result.rejectValue("username", "DuplicateKey.user.username");
        return "signup";
    }

    return "accountcreated";
}

DuplicateKeyException is thrown on duplicate username. How is this possible?


Solution

  • OK, I solved it. According to the comments in the tutorial I'm following (link), you have to do it another way in IntelliJ IDEA (they use Eclipse in the tutorial). I did move the messages files to resources folder, so now my dir structure is

    src
      - main
        - java (sources)
        - resources (messages files)
        - webapp (WEB-INF, JSPs etc.)
    

    and in my config xml:

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" value="messages"/>
    </bean>
    

    You have to right-click on resources directory and Mark Directory As -> Resources Folder. The messages files should appear inside another node called Resource Bundle 'messages'. Now it works as it should. If it doesn't find a message in messages_sk_SK.properties, it tries to find it in messages.properties.

    dir structure