修改“黑盒子”Servlet响应输出

时间:2012-10-24 10:37:52

标签: java regex httpresponse servlet-filters

问题:

我有一个生成报告的servlet,更具体地说是报告的表体。这是一个黑盒子,我们无法访问源代码。

尽管如此,它的工作令人满意,并且servlet不打算在短期内重写或更换。

我们需要修改其响应文本,以便将其生成的一些链接更新到其他报告中,我正在考虑使用过滤器来查找锚文本并使用正则表达式替换它。

研究

我遇到了this question,它有一个正则表达式过滤器。它应该是我需要的,但也许不是。

我并不是试图严格意义上解析parsing一词,而是我没有使用该语言的完整规范。我所拥有的是组成表体的HTML标记的子集,并且没有嵌套表,因此servlet生成的HTML子集不是递归的。

我只需要找到/替换锚点目标并为标记添加属性。

所以问题是:

我需要修改servlet的输出才能更改所有类型的链接:

<a href="http://mypage.com/servlets/reports/?a=report&id=MyReport&filters=abcdefg">

进入以下链接:

<a href="http://myOtherPage.com/webReports/report.xhtml?id=MyReport&filters=abcdefg" target="_parent">

我应该使用@ Jeremy Stein编写的正则表达式过滤器还是有更好的解决方案?

2 个答案:

答案 0 :(得分:1)

假设目标A标记中唯一不同的部分是href属性的查询组件,那么这个经过测试的正则表达式解决方案应该做得非常好:

// TEST.java 20121024_0800
import java.util.regex.*;
public class TEST {
    public static String fixReportAnchorElements(String text) {
        Pattern re_report_anchor = Pattern.compile(
            "<a href=\"http://mypage\\.com/servlets/reports/\\?a=report&id=([^\"]+)\">",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher m = re_report_anchor.matcher(text);
        return m.replaceAll(
            "<a href=\"http://myOtherPage.com/webReports/report.xhtml?id=$1\" target=\"_parent\">"
            );
    }
    public static void main(String[] args) {
        String input =
            "test <a href=\"http://mypage.com/servlets/reports/?a=report&id=MyReport&filters=abcdefg\"> test";
        String output = fixReportAnchorElements(input);
        System.out.println(output);
    }
}

答案 1 :(得分:0)

我使用了Jeremy Stein (click to go to question)个类,但有一些更改:

a)确保没有人关注过滤器链或servlet不要在包装器对象上调用getOutputStream(),否则会抛出invalidStateException(检查主题上的this answer by BalusC)。

b)我想在页面上进行一次更改,所以我没有在web.xml上放置任何filterConfig。

b.2)我也没有在web.xml上放任何东西。在类本身上使用javax.servlet.annotation.WebFilter

c)我设置了Pattern并直接在类上替换字符串:

Pattern searchPattern = Pattern.compile("<a (.*?) href=\".*?id=(.*?)[&amp;|&]filtros=(.*?)\" (.*?)>(.*?)</a>");
String replaceString = "<a $1 href=\"/webReports/report.xhtml?idRel=$2&filtros=$3\" target=\"_parent\" $4>$5</a>";

请注意.*?尽可能少地匹配,以避免匹配超过想要的匹配。

为了测试匹配和正则表达式,我在研究主题时使用了this applet I found

希望这可以帮助任何有同样问题的人。

相关问题