我看到3種方式:濾波器,基本的servlet(經由主servlet的所有請求)或 「小服務程序映射」
濾波器
此示例重寫網址
http://example.org/<int value>
到
http://example.org/user?id=<int value>
即
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
}}
基本sevlet
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映射 - 簡單地說,不靈活(針對具體的路線規則)