1 5 6 package org.infohazard.maverick.view; 7 8 import java.io.IOException ; 9 import java.net.URLEncoder ; 10 import java.util.Iterator ; 11 import java.util.Map ; 12 13 import javax.servlet.ServletException ; 14 15 import org.infohazard.maverick.flow.View; 16 import org.infohazard.maverick.flow.ViewContext; 17 18 28 public class RedirectView implements View 29 { 30 33 protected String target; 34 35 38 RedirectView(String target) 39 { 40 this.target = target; 41 } 42 43 56 public void go(ViewContext vctx) throws IOException , ServletException 57 { 58 String result = this.target; 59 60 if (vctx.getModel() instanceof Map ) 61 { 62 result = this.addQueryParams(result, (Map )vctx.getModel()); 63 } 64 else if (vctx.getModel() instanceof String ) 65 { 66 result = (String )vctx.getModel(); 67 } 68 69 result = this.addQueryParams(result, vctx.getViewParams()); 71 72 result = vctx.getRealResponse().encodeRedirectURL(result); 74 75 vctx.getRealResponse().sendRedirect(result); 76 } 77 78 80 protected String addQueryParams(String start, Map params) 81 { 82 if (params == null || params.isEmpty()) 83 return start; 84 85 StringBuffer url = new StringBuffer (start); 86 87 boolean first = (start.indexOf('?') < 0); 89 90 Iterator entries = params.entrySet().iterator(); 91 while (entries.hasNext()) 92 { 93 Map.Entry entry = (Map.Entry )entries.next(); 94 String key = entry.getKey().toString(); 95 96 if ("#".equals(key)) 98 continue; 99 100 if (first) 101 { 102 url.append("?"); 103 first = false; 104 } 105 else 106 url.append("&"); 107 108 if (entry.getValue() instanceof Object []) 109 { 110 Object [] values = (Object [])entry.getValue(); 111 for (int i = 0; i < values.length; i++) 112 { 113 if (i > 0) 114 url.append("&"); 115 116 addQueryParam(url, key, values[i]); 117 } 118 } 119 else 120 { 121 addQueryParam(url, key, entry.getValue()); 122 } 123 } 124 125 Object namedAnchor = params.get("#"); 126 if (namedAnchor != null) 127 { 128 url.append("#"); 129 url.append(URLEncoder.encode(namedAnchor.toString())); 130 } 132 133 return url.toString(); 134 } 135 136 protected void addQueryParam(StringBuffer url, String key, Object value) { 137 url.append(URLEncoder.encode(key)); 138 url.append("="); 140 url.append(URLEncoder.encode(value.toString())); 141 } 143 } | Popular Tags |