2

我的WAR结构如下:

my-web-app.war/
    views/
        index.html
        blah.html
    META-INF/
        MANIFEST.MF
    WEB-INF/
        web.xml
        lib/
            <!-- Dependencies -->
        classes/
            org.me.mywebapp.controllers/
                MyController.class
            <!-- Other packages/classes as well -->

我想进行配置web.xml,以便在本地部署 WAR 时,index.html可以通过转到http://localhost/my-web-app/index.html.

这是我到目前为止所拥有的:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

    <!-- The display name of this web application -->
    <display-name>My Web App</display-name>

    <listener>
        <listener-class>
            org.me.mywebapp.context.ContextImpl
        </listener-class>
    </listener>
</web-app>

如何配置此 URL 以查看映射?提前致谢!

4

3 回答 3

6

你可以像这样映射你的servlet

<servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.me.mywebapp.controllers.MyController</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>index.html</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>controller2</servlet-name>
    <servlet-class>org.me.mywebapp.controllers.OtherController</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>controller2</servlet-name>
    <url-pattern>blah.html</url-pattern>
</servlet-mapping>

如果你想将 view/blah.html 显示为 /blah.html,在控制器中你只需将请求发送到适当的视图/ * .html 或 jsp 或任何你想要的东西。

编辑:根据您的要求:您可以将请求分派到 servlet 内的另一个页面,如下所示:

RequestDispatcher dispatcher = 
       getServletContext().getRequestDispatcher("/views/blah.html");
dispatcher.forward(request, response);

尽管上面的代码可以工作,但您可能应该在每个 servlet 中实现更“复杂”的方法来决定您将分派到哪个视图,尤其是如果您的应用程序有很多控制器、视图等。如果您尝试阅读有关 MVC 实现的更多信息还没做。

于 2012-08-06T12:53:59.467 回答
1

您可以使用将特定请求路由到view路径的过滤器。查看响应:https ://stackoverflow.com/a/3593513/221951然后您在过滤器中决定是否应将请求传递给 servlet。

您也可以尝试使用 Tuckey URL 重写过滤器http://tukey.org/urlrewrite/

于 2012-08-06T13:05:25.990 回答
-1

您可以通过在过滤器中重写 URL 来做到这一点。

就像它被大多数框架实现一样,如 Struts、Spring MVC、Tapestry、Wicket 等

于 2012-08-06T12:54:30.157 回答