这被称为“漂亮的URL”或“友好的URL”。基本上,你需要创建一个过滤器或者一个前端控制器servlet来完成这项工作。假设你去过滤方向,它会看起来像如下:
private Map<String, String> mapping;
@Override
public void init() {
mapping = new HashMap<String, String>();
mapping.put("/product/some-lovely-carrots", "/product.jsp?id=2");
// ...
// You can of course also fill this map based on some XML config file or
// even a database table.
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
String target = mapping.get(path);
if (target != null) {
req.getRequestDispatcher(target).forward(req, res);
} else {
chain.doFilter(req, res);
}
}
地图这个过滤器上的/*
的URL模式,改变链接如下
<a href="${pageContext.request.contextPath}/product/some-lovely-carrots">Some lovely carrots</a>