1 //========================================================================
2 //Copyright 2009 Webtide LLC
3 //------------------------------------------------------------------------
4 //Licensed under the Apache License, Version 2.0 (the "License");
5 //you may not use this file except in compliance with the License.
6 //You may obtain a copy of the License at
7 //http://www.apache.org/licenses/LICENSE-2.0
8 //Unless required by applicable law or agreed to in writing, software
9 //distributed under the License is distributed on an "AS IS" BASIS,
10 //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 //See the License for the specific language governing permissions and
12 //limitations under the License.
13 //========================================================================
14 package org.mortbay.jetty.handler.rewrite;
15
16 import java.io.IOException;
17 import java.util.regex.Matcher;
18
19 import javax.servlet.http.HttpServletRequest;
20 import javax.servlet.http.HttpServletResponse;
21
22 /**
23 * Redirects the response by matching with a regular expression.
24 * The replacement string may use $n" to replace the nth capture group.
25 */
26 public class RedirectRegexRule extends RegexRule
27 {
28 private String _replacement;
29
30 public RedirectRegexRule()
31 {
32 _handling = true;
33 _terminating = true;
34 }
35
36 /**
37 * Whenever a match is found, it replaces with this value.
38 *
39 * @param replacement the replacement string.
40 */
41 public void setReplacement(String replacement)
42 {
43 _replacement = replacement;
44 }
45
46 @Override
47 protected String apply(String target, HttpServletRequest request, HttpServletResponse response, Matcher matcher)
48 throws IOException
49 {
50 target=_replacement;
51 for (int g=1;g<=matcher.groupCount();g++)
52 {
53 String group = matcher.group(g);
54 target=target.replaceAll("\\$"+g,group);
55 }
56
57 response.sendRedirect(target);
58 return target;
59 }
60 }