1 package com.opensymphony.webwork.dispatcher.mapper; 2 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.logging.LogFactory; 5 6 import javax.servlet.http.HttpServletRequest ; 7 import java.net.URLDecoder ; 8 import java.util.HashMap ; 9 import java.util.Iterator ; 10 import java.util.Map ; 11 import java.util.StringTokenizer ; 12 13 39 public class RestfulActionMapper implements ActionMapper { 40 protected static final Log LOG = LogFactory.getLog(RestfulActionMapper.class); 41 42 public ActionMapping getMapping(HttpServletRequest request) { 43 String uri = request.getServletPath(); 44 45 int nextSlash = uri.indexOf('/', 1); 46 if (nextSlash == -1) { 47 return null; 48 } 49 50 String actionName = uri.substring(1, nextSlash); 51 HashMap parameters = new HashMap (); 52 try { 53 StringTokenizer st = new StringTokenizer (uri.substring(nextSlash), "/"); 54 boolean isNameTok = true; 55 String paramName = null; 56 String paramValue; 57 58 if ((st.countTokens() % 2) != 0) { 60 isNameTok = false; 61 paramName = actionName + "Id"; 62 } 63 64 while (st.hasMoreTokens()) { 65 if (isNameTok) { 66 paramName = URLDecoder.decode(st.nextToken(), "UTF-8"); 67 isNameTok = false; 68 } else { 69 paramValue = URLDecoder.decode(st.nextToken(), "UTF-8"); 70 71 if ((paramName != null) && (paramName.length() > 0)) { 72 parameters.put(paramName, paramValue); 73 } 74 75 isNameTok = true; 76 } 77 } 78 } catch (Exception e) { 79 LOG.warn(e); 80 } 81 82 return new ActionMapping(actionName, "", "", parameters); 83 } 84 85 public String getUriFromActionMapping(ActionMapping mapping) { 86 String base = mapping.getNamespace() + mapping.getName(); 87 for (Iterator iterator = mapping.getParams().entrySet().iterator(); iterator.hasNext();) { 88 Map.Entry entry = (Map.Entry ) iterator.next(); 89 String name = (String ) entry.getKey(); 90 if (name.equals(mapping.getName() + "Id")) { 91 base = base + "/" + entry.getValue(); 92 break; 93 } 94 } 95 96 return base; 97 } 98 } 99 | Popular Tags |