0

So I'm working on a blog, but I'm stumbeling on organizing content with clear URL paths. Basically, I want every post that is created to have a unique URL path like "http://www.site.com/article/article_name." At this point I have my URLs look like "http://www.site.com/article.jsp?article=article_name," where article.jsp generates different content through:

request.getParameter("requestedArticleName");

I'm aware of servlet mapping to invoke servlets based on URL patterns, but I'm not quite sure how that works, and whether if I need it at all.

4

1 回答 1

0

您可以用来实现此目的的一种方法是创建您自己的方法Filter,它将接收来自http://www.site.com/article/*的所有请求并将它们重定向到您的 article.jsp?name=*。

例子 :

public class URLFilter implements Filter
{
    @Override
    public void  init(FilterConfig config) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest p_oRequest, ServletResponse p_oResponse, FilterChain p_oChain) throws IOException, ServletException
    {
        String sName = oRequest.getRequestURI();

        if(sName.lastIndexOf('/') != -1)
        {
            sName = sName.substring(sName.lastIndexOf('/') + 1);
        }
        else
        {
            // You could trap that in your article.jsp to show error message
            sName = "404";
        }

        p_oRequest.getRequestDispatcher("/article.jsp?name=" + sName).forward(p_oRequest,p_oResponse);
    }
}

当然,您需要改进它并进行一些验证。此外,此代码尚未经过测试,但基于我的 JSF CMS URLFilter。

不要忘记将其包含在您的web.xml!

<filter>
    <filter-name>URLFilter</filter-name>
    <filter-class>path.to.your.URLFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>URLFilter</filter-name>
    <url-pattern>/article/*</url-pattern>
</filter-mapping>
于 2013-05-26T20:03:23.660 回答