我試圖從重寫URL:Servlet過濾器重寫URL
localhost:8080/sendEmail/newEmail.pdf?request_id=23456&emailAddress=
要:
localhost:8080/sendEmail/newEmail.pdf?request_id=23456
Filter類代碼和映射在下面。我怎樣才能完成這項任務? (一個例子的答案將不勝感激)。
過濾器映射:
<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);
}
}
}
我明白reluctancy推倒重來,但我不能相信任何人都會認爲在servlet容器之前添加Apache只是爲了重寫URL而不是用幾行代碼創建一個簡單的過濾器。 – stepanian 2016-04-06 06:44:06
@stepanian是的,這是過度的,這就是爲什麼我首先提出Java解決方案,並說如果你已經有Apache(無論出於什麼原因),mod_rewrite可能是一種替代方法。 – marc82ch 2016-04-07 11:49:34