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
.
Asked
Active
Viewed 2,063 times
0

kryger
- 12,906
- 8
- 44
- 65

Chorochrondochor
- 100
- 12
-
take a look , u may not need spring , http://stackoverflow.com/questions/573184/java-convert-string-to-valid-uri-object – Asraful May 13 '14 at 09:41
-
BTW. it's called "a slug" ([link](https://en.wikipedia.org/wiki/Clean_URL#Slug)) – kryger May 24 '14 at 21:41
2 Answers
5
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"));

Marco Acierno
- 14,682
- 8
- 43
- 53
-
The result of it is "Majstrovstv%C3%A1+v+%C4%BEadovom+hokeji", that is hard to read. I want characters like `á` to be replaced by `a`, *empty space* with `-` etc. – Chorochrondochor May 13 '14 at 10:06
-
You will not read it, you will use URLDecoder.decode to get the original string. – Marco Acierno May 13 '14 at 10:12
-
The URL would look like this http://domain.com/article/Majstrovstv%C3%A1+v+%C4%BEadovom+hokeji but I want it to look like this http://domain.com/article/majstrovstva-v-ladovom-hokeji, therefore I am looking for a method which will convert a string into the other format. Something like this http://doc.nette.org/en/2.1/strings#toc-webalize but in Java. – Chorochrondochor May 13 '14 at 11:24
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.