Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Spring Locale from Request

farenda 2017-04-07 0

Spring Framework is really great when it comes to i18n. It applies different strategies to get user’s locale from request. In this post we’ll show how apply that!

Spring Locale from Request

This is the simplest Spring REST Controller illustrating how to get Locale from HTTP Request. All we need to do is to add Locale parameter to the method receiving HTTP Request:

package com.farenda.spring.tutorial.rest.locale;

import org.springframework.web.bind.annotation.*;

import java.util.Locale;

import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class LocalizedController {

    @RequestMapping(value = "/echo", method = GET,
            produces = TEXT_PLAIN_VALUE)
    public String getLocaleName(Locale locale) {
        return "Locale from request: " + locale;
    }
}

Why that works? When a request comes in it goes to Spring’s DespatcherServlet, which tries to find a LocaleResolver that can provide locale based on some strategy – “accept-language” header, cookies, user’s session, etc. Locale from request is then available through RequestContext.getLocale(), but also can be injected as we did here.

Spring test of REST Controller

We can pretty easily test the above controller using MockMvcBuilders from the Spring Test package. The only thing we need to do is to call locale(Locale) method, when we build GET Request, to set our Locale on the request – you can pass more locales if you want.

package com.farenda.spring.tutorial.rest.locale

import org.springframework.test.web.servlet.setup.MockMvcBuilders
import spock.lang.Specification
import spock.lang.Subject

import static org.springframework.http.MediaType.APPLICATION_JSON
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

class LocalizedControllerTest extends Specification {

    @Subject
    def localeApi = new LocalizedController()

    def mockMvc = MockMvcBuilders.standaloneSetup(localeApi).build()

    def 'should return locale from request'() {
        given:
        def myLocale = Locale.CHINA
        def expectedResponse = 'Locale from request: ' + myLocale

        when:
        def result = mockMvc.perform(
                get('/echo').contentType(APPLICATION_JSON)
                        .locale(myLocale))

        then:
        result.andExpect(status().isOk())
                .andExpect(content().string(expectedResponse))
    }
}

Experiment with the above code and use different locales, pass more than one locale, or even add parameters to the API method.

References:

  • Check out other cool stuff in Spring Tutorial!
  • See Spock Framework Tutorial if you don’t use it yet!
Share with the World!
Categories Spring Framework Tags java, rest, spring
Previous: MongoDB import/export data
Next: How to generate random test data in MongoDB

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok