开发者

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

开发者 https://www.devze.com 2023-03-03 08:35 出处:网络
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.

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 contraini开发者_如何学Cng 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>


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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消