Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP 2.0 SEO friendly links encoding

Currently I have something like this in my JSP

<c:url value="/teams/${contact.id}/${contact.name}" />

The important part of my URL is the ID, I just put the name on it for SEO purposes (just like stackoverflow.com does).

I was just wondering if there is a quick and clean way to encode the name (change spaces per +, latin chars removal, etc). I'd like it to be like this:

<c:url value="/teams/${contact.id}/${supercool(contact.name)}" />

Is there a function like that out there or should I make my own?

like image 288
victor hugo Avatar asked May 02 '10 09:05

victor hugo


2 Answers

Nothing like that is available in JSTL functions. You'll need to create your own. I'd by the way rather replace spaces by -.

To the point, you want to perform the following steps:

  1. Lowercase the string.

    string = string.toLowerCase();
    
  2. Normalize all characters and get rid of all diacritical marks.

    string = Normalizer.normalize(string, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
    
  3. Replace all remaining non-alphanumeric characters by - and collapse when necessary.

    string = string.replaceAll("[^\\p{Alnum}]+", "-");
    

You can wrap this in an EL function:

package com.example;

import java.text.Normalizer;
import java.text.Normalizer.Form;

public final class Functions {
     private Functions() {}

     public static String prettyURL(String string) {
         return Normalizer.normalize(string.toLowerCase(), Form.NFD)
             .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
             .replaceAll("[^\\p{Alnum}]+", "-");
     }
}

Which you register in a /WEB-INF/functions.tld like follows:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <display-name>Custom Functions</display-name>    
    <tlib-version>1.0</tlib-version>
    <uri>http://example.com/functions</uri>

    <function>
        <name>prettyURL</name>
        <function-class>com.example.Functions</function-class>
        <function-signature>java.lang.String prettyURL(java.lang.String)</function-signature>
    </function>
</taglib>

Which you can use in JSP as follows:

<%@taglib uri="http://example.com/functions" prefix="f" %>
...
<a href="teams/${contact.id}/${f:prettyURL(contact.name)}">Permalink</a>
like image 130
BalusC Avatar answered Sep 21 '22 01:09

BalusC


Look for server.urlencode, all the major server side languages today have them.

like image 25
SBR Avatar answered Sep 22 '22 01:09

SBR