(几乎)一个servlet的所有URL [英] (Almost) all URLs to one servlet

查看:167
本文介绍了(几乎)一个servlet的所有URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有URL映射到一个主servlet,除了我的静态文件(如样式表,图形和东西),并且仍然可以从我的servlet调用JSP ..

I would like to map all URLs to one main servlet, except my static files (like stylesheets, graphics and stuff) and still be able to call JSPs from my servlets..

我的意图是向用户提供虚荣URL,这样任何不指向静态文件或资源的URL都会映射到我的主servlet ..

My intent is to provide "vanity URLs" to users, such that any URL that doesn't point to a static file or resource, gets mapped to my main servlet..

我该怎么做..?

如果有帮助,我可以将所有静态文件和JSP放在单独的文件夹中..有没有办法在/ *映射之前映射到那些文件夹。?

If it helps, I can have all my static files and JSPs in seperate folders.. Is there a way to map to those folders before the /* mapping..?

推荐答案

如何在/ *上映射全局前端控制器servlet时访问静态资源
我提出了这个解决方案:

Inspired by How to access static resources when mapping a global front controller servlet on /* I came up with this solution:

/war/WEB-INF/web.xml 中:

<filter>
    <filter-name>MainFilter</filter-name>
    <filter-class>com.example.mywebsite.MainFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MainFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>com.example.mywebsite.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/MainServlet/*</url-pattern>
</servlet-mapping>

in MainFilter.java

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String path = req.getRequestURI();
    String topfolder = path.substring(1);
    if (topfolder.contains("/")) {
        topfolder = topfolder.substring(0, topfolder.indexOf("/"));
    }

    if (topfolder.startsWith("_")) {
        chain.doFilter(request, response);
    } else if (topfolder.endsWith(":")) {
        request.getRequestDispatcher(path.replaceFirst(":", "")).forward(request, response);
    } else {
        request.getRequestDispatcher("/MainServlet" + path).forward(request, response);
    }

}

现在你可以把你所有的静态将内容放入WAR中的子文件夹中。然后,如果要从HTML链接到 /war/css/style.css ,只需将其称为/ css:/ style .css ..或者您可以在开头用 _ 命名您的文件夹/文件,并像平常一样引用它们。

Now you can put all your static content into subfolders in your WAR. Then if you want to link to /war/css/style.css from your HTML, you simply refer to it as "/css:/style.css".. Or you can name your folders/files with a _ at the beginning and refer to them like normal..

(此外, _ 规则确保Google App Engine开发人员可以访问 / _ ah / admin

(Also the _ rule makes sure that Google App Engine developers can access /_ah/admin)

这篇关于(几乎)一个servlet的所有URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆