@WebServlet annotation web.xml welcome-file

konze picture konze · Mar 19, 2013 · Viewed 23.8k times · Source

I would like to set the welcome-file of my JSP/JavaBeans project. I have a servlet named 'Controller.java' with the following @WebServlet annotation:

@WebServlet(name="Controller", urlPatterns={"/login", "/show_dbs"})

and I hava a web.xml file with the following content:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <welcome-file-list>
        <welcome-file>Controller</welcome-file>
    </welcome-file-list>
</web-app>

Almost all things are going well, I can open http://localhost:8080/PROJECT/login and http://localhost:8080/PROJECT/show_dbs and I come to Controller.java. But when I open http://localhost:8080/PROJECT/ I get a 404 error.

I'm using Eclipse with a 'Dynamic Web Project', the Controller.java file is located under /src (default package) and the web.xml file is under /WebContent/WEB-INF.

I hope you have a tip for me.

Answer

konze picture konze · Mar 21, 2013

Thank you for your help. Here comes my solution:

If you want to set your servlet as welcome file you have to do the following:

Define a standard html as welcome-file such as index.html in your web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

Make sure this file (index.html) doesn't exist.

Define your urlPatterns in @WebServlet like this:

@WebServlet(name="Controller", urlPatterns={"/index.html", "/login", "/show_dbs"})

Now every request to http://.../PROJECT/ (root) will be redirected to http://.../PROJECT/index.html and this calls the servlet.