Tomcat, Groovy and clean urls
-
22-09-2019 - |
Question
I'm trying to get Groovy running inside Tomcat with clean urls. Since my knowledge of Tomcat's url mapping and filters is quite limited, I'm running into a brick wall.
What I'd like is to create a front-controller called index.groovy
that handles all incoming requests. The problem is that I can't seem to figure out how to create the correct web.xml
mappings. This is what I currently have (which is pretty much standard):
<servlet>
<servlet-name>Groovy</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Groovy</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
If I now try to access my instance with the following url, I get a 404
.
http://localhost:8080/GroovyTest/index.groovy/test
Of course, ideally I'd like the index.groovy
script to be executed where I can pick up the rest of the path.
Solution
I think that the main problem here is your misunderstanding on how both the servlet mapping an the GroovyServlet works. So, here is a brief explanation:
- When you describe such mapping, it indicates that all the URLs matching the "/*" pattern will be sent to the GroovyServlet class. With such generic pattern, all the url are valid, which can lead to some issues, for example when trying to access images, styles, etc...
- The GroovyServlet is already a dispatcher. If you look at it source code, you'll see that, due to it's inheritance, it will simply check that the given path exist under the "/WEB-INF/groovy/" directory. In your example, it means that it looks for a "/WEB-INF/groovy/index.groovy/test" file
- If this file exists, it is executed as a Groovy script (with some decorator), and the result is returned with a "text/html" mime type.
Now I think you can clearly understand why it does not work on you example. I would rather suggest you two other approaches to achieve you goal: