Spring Security. Multilanguage login page based on url

I have locales as a part of url in my Spring Boot application:

/site - default locale

/en/site - English locale

I use custom interceptor for this:

import org.springframework.beans.propertyeditors.LocaleEditor
import org.springframework.util.Assert
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import org.springframework.web.servlet.support.RequestContextUtils

import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.util.Locale
import java.util.regex.Pattern

class CustomLocaleChangeInterceptor : HandlerInterceptorAdapter() {

private var localePattern: Pattern? = null

private fun setLocalePattern(localePattern: String) {
    Assert.isTrue(localePattern.matches(".*\\(.*\\).*".toRegex()), "Your pattern needs to define a match group")
    this.localePattern = Pattern.compile(localePattern)

override fun preHandle(request: HttpServletRequest?, response: HttpServletResponse?, handler: Any?): Boolean {


    val pathTranslated = request!!.requestURI.substring(request.contextPath.length)

    if (pathTranslated.isNotEmpty()) {
        val matcher = localePattern!!.matcher(pathTranslated)
        if (matcher.find()) {
            resolver(request, response, matcher.group(1))
        } else {
            resolver(request, response, "th")
    // Proceed in any case.
    return true


private fun resolver(request: HttpServletRequest, response: HttpServletResponse?, locale: String) {
    val localeResolver = RequestContextUtils.getLocaleResolver(request) ?: throw IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?")
    val localeEditor = LocaleEditor()
    localeEditor.asText = locale
    localeResolver.setLocale(request, response, localeEditor.value as Locale)


The question is what is the best way to handle two custom login pages in Spring? When restricted url contains /en user should be redirected to /en/login page (with English language) otherwise if page has default locale it should be redirect to /login url (with default language)

0 Comment



Captcha image