Run Servlet before loading index.jsp

Asked

Viewed 853 times

0

I am trying to run my Servlet before loading index.jsp, as the information contained in the index comes from a query in the database. I tried to use

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

but it didn’t work out. How can I do this?

  • 1

    You need a Filter :)

1 answer

2

Good morning Guilherme.

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

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

Your configuration file web.xml will be more or less 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 the index.jsp.
  • If in his web.xml the tag already exists <welcome-file> filled with index.jsp it is necessary to replace for the mapping of your Servlet. (Don’t forget to remove the /)

Finally, in your Servlet, just dispose the request to the index.jsp. Thus, within index.jsp, you will have access to request which may contain the data you 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. Don’t forget to always look for alternative solutions to problems.

I hope I helped. A hug.

  • Thank you, Andrew Ribeiro. It was the same case: .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.