我正在尝试从以下位置重写 URL:
localhost:8080/sendEmail/newEmail.pdf?request_id=23456&emailAddress=
至:
localhost:8080/sendEmail/newEmail.pdf?request_id=23456
过滤器类代码和映射如下。我怎样才能完成这项任务?(高度赞赏一个例子的答案)。
过滤器映射:
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>com.abc.ms.email.filter.RequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
过滤器代码:
public class RequestFilter implements Filter {
private static final Pattern REWRITE_PATTERN = Pattern.compile("(^[1-9]\\d*)$");
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest)req);
String url = wrapper.getRequestURL().toString();
String number = url.substring(url.lastIndexOf("/")).replace("/", "");
Matcher m = REWRITE_PATTERN.matcher(number);
if (m.find()) {
RequestDispatcher dispatcher = wrapper.getRequestDispatcher("request?id=" + m.group(1));
dispatcher.forward(req, res);
} else {
fc.doFilter(wrapper, res);
}
}
}