我看到 3 种方式:过滤器、基本 servlet(所有请求都通过主 servlet)或“servlet-mapping”
筛选
这个例子重写 url
http://example.org/<int 值>
到
http://example.org/user?id=<int 值>
IE
http://example.org/1234 -> http://example.org/user?id=1234
- web.xml 中的确定过滤器
<filter>
<filter-name>Router</filter-name>
<filter-class>org.example.Router</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>valueOfparam1</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Router</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在 init-param 部分你可以指定路由规则
过滤器类
public class Router implements javax.servlet.Filter {
private static final Pattern REWRITE_PATTERN = Pattern.compile("(^[1-9]\\d*)$");
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
//this method calling before controller(servlet), every request
HttpServletRequest request = (HttpServletRequest) req;
String url = request.getRequestURL().toString();
String number = url.substring(url.lastIndexOf("/")).replace("/", "");
Matcher m = REWRITE_PATTERN.matcher(number);
if(m.find()) {
RequestDispatcher dispatcher = request.getRequestDispatcher("user?id=" + m.group(1));
dispatcher.forward(req, res);
} else {
fc.doFilter(req, res);
}
}
@Override
public void init(FilterConfig fc) throws ServletException {
//here you may read params from web.xml
}}
基本小程序
public class BasicServlet extends HttpServlet {
//route rules here, and rewrite
}
servlet 映射
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<uri-mapping>/user/*</uri-mapping>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PostServlet</servlet-name>
<uri-mapping>/post/*</uri-mapping>
</servlet-mapping>
- 过滤器 - 更灵活,不需要认真修改工作代码
- 基本 servlet - 灵活,需要更改您的代码
- servlet 映射 - 简单,不灵活(针对特定路由规则)