Execute servlet before loading index.jsp

0

I'm trying to run my servlet before loading index.jsp because the information contained in the index comes from a query in the database. I tried using

<jsp:forward page="/servlet"/>

But it did not work. How can I do this?

    
asked by anonymous 26.08.2016 / 00:21

1 answer

2

Good morning Guilherme.

There are several ways to achieve the goal you want. Using a Filter like @DilneiChain suggested is one of the ways.

Another interesting way is to edit the <welcome-file> tag in your web.xml configuration file ( If your projector is using a, of course) . >

Your configuration file web.xml will look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/servlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>servlet</welcome-file>
    </welcome-file-list>
</web-app>

Note that:

  • /servlet would be the mapping to the Servlet you want to use to fill index.jsp .
  • If you already have the web.xml tag filled with <welcome-file> in your index.jsp it is necessary to override the mapping of your Servlet. (Do not forget to remove% with%)

Finally, in your Servlet, just dispatch the request to / . Thus, within index.jsp , you will have access to the index.jsp that may contain the data you have obtained through your logic within the Servlet.

Your Servlet will look something like this:

public class Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Executar sua lógica para obter os dados
        //...

        // Dispacha a requisição para index.jsp
        request.getRequestDispatcher("/index.jsp").forward(request, response); 
    }

}

Ready. Your project will work with this workaround . Do not forget to always look for alternative solutions to problems.

I hope I have helped. A hug.

    
27.08.2016 / 19:47