2012-02-19 50 views
0

如果问题措辞不当,我很抱歉......我不太确定如何去询问。根据查询字符串更改URL [JSP/Servlet]

我怎么会去改变取决于查询字符串的URL,例如:

如果有人点击网址,而不是被foo.com/product.jsp?id=一个链接,一些可爱的胡萝卜, 2它将是foo.com/product/some-lovely-carrots。

我尝试添加映射到web.xml,但我认为我没有正确的方式。

任何帮助,将不胜感激。

回答

0

这被称为“漂亮的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>