Create Url from a String value in JAVA

884 views Asked by At

Hi people i'm trying to create urls from strings, this is my situation:
I have a table called publication(id_pub, title, content) and i need to transform the title attribute to an url (i.e. localhost:8080/app/firstPublication.html)
I'm using Spring MVC and Hibernate Annotations (Models, Daos, Services and Controllers classes). I don't know even how to make a property question about this problem, please if you need more details just ask me.

1

There are 1 answers

1
Vidya On

It sounds to me like you are trying to generate slugs for the entries in your table, a common task on content sites like ours. Code for this is available all over, but here is one example in Java:

  private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
  private static final Pattern WHITESPACE = Pattern.compile("[\\s]");

  public String makeSlug(String input) {
    String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
    String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
    String slug = NONLATIN.matcher(normalized).replaceAll("");
    return slug.toLowerCase(Locale.ENGLISH);
  }

Just pass the title to this (maybe the date as well if you tweak the method).