How to configure tomcat's web.xml with my Front Controller

对着背影说爱祢 提交于 2019-12-13 21:12:48

问题


I've written a simple Front Controller for my Java EE application. This controller intercepts all the urls to redirect them to the corresponding method in the right class.

A typical url looks like this: http://domain.tld/appName/Controller/method

I'm facing 3 issues with tomcat at the moment:

  1. If I try to access to my base url, http://domain.tld/appName/ (with or without the ending slash), my front controller isn't called and I've got a 404.
  2. If I try to access to an url like this: domain.tld/appName/Controller/method/ (remark the ending slash) same thing than point number 1. But without the ending slash it works fine.
  3. Finally, since all my requests are routing to my front controller I have to define all the static file to be served to the default servlet, in my web.xml. A less contraining and ugly solution would be nice.

Here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <servlet>
        <servlet-name>FrontController</servlet-name>
        <servlet-class>controllers.FrontController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FrontController</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
</web-app>

回答1:


Add this to your web.xml file, before the first servlet:

<welcome-file-list>
    <welcome-file>FrontController</welcome-file>
</welcome-file-list>



回答2:


As said in comment, my FrontController was kinda ugly. Rewriting it properly did the trick with the same web.xml.



来源:https://stackoverflow.com/questions/5920870/how-to-configure-tomcats-web-xml-with-my-front-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!