Question

Is there any method in Spring Framework for converting a string to its URL representation? For example from Majstrovstvá v ľadovom hokeji to majstrovstva-v-ladovom-hokeji.

Was it helpful?

Solution 2

Enhancing example from this answer, you could do it like this:

import java.text.Normalizer;
import java.util.regex.Pattern;

public class UrlifyString {
  public static String deAccent(String str) {
    String norm = Normalizer.normalize(str, Normalizer.Form.NFD);
    Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    return pattern.matcher(norm).replaceAll("").replace(" ", "-").toLowerCase();
  }

  public static void main(String[] args) {
    System.out.println(deAccent("Majstrovstvá v ľadovom hokeji"));
  }
}

Output is:

majstrovstva-v-ladovom-hokeji


One thing to note is that it's a lossy conversion so there's no way to go back from this "simplified" form to the original version. Because of this you should not use this as a key to any of the resources, I'd suggest including a unique identifier to the articles, something like:

http://example.com/article/123/majstrovstva-v-ladovom-hokeji

Spring's @PathVariable would make it easy to handle this transparently.

OTHER TIPS

I don't know about Spring, but you can use URLEncoder.encode and encode for the URL (Output: Majstrovstv%C3%A1+v+%C4%BEadovom+hokeji)

Example:

String input = "Majstrovstvá v ľadovom hokeji";
System.out.println(URLEncoder.encode(input, "UTF-8"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top