user3534092
user3534092

Reputation: 1

How to invoke init on program execution? Servlet, JSP

I am using the Eclipse IDE, a HelloServlet.java and index.jsp file.

When I right-click my project and click "Run As" the program executes. The JSP file then produces, but first, I need my servlet to collect some data, and send it to the JSP file.

Currently, I must click a button in the JSP file to execute my Servlet (the HelloServlet.java file). I need it vice versa, where the program starts, the HelloServelt's init method fires, collects my data and sends it to the JSP file.

Perhaps, someone could aid me in achieving this.

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello Servlet</title>
</head>
<body>
Add
<form action="HelloServlet">
        <input type="text" value="x" />
    </form>


<hr/>
</body>
</html>

HelloServlet.java

public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("Constructor initializing");
    }

    public void init(ServletConfig config) throws ServletException {
         String x = "data collected!";
         System.out.println("init initializing");
    }

Again, it seems the only way to invoke the servlet is by clicking the text field in the JSP file. I need to invoke the Servlet on program execution, and then give that data to the JSP file.

Upvotes: 0

Views: 742

Answers (2)

Mart&#237;n Schonaker
Mart&#237;n Schonaker

Reputation: 7305

What I would do is to collect the data a in a ServletContextListener, and then share the data with the page using a context attribute: adding it to the context, and retrieving it for the page using the expression language.

Upvotes: 0

Bennet
Bennet

Reputation: 387

In web.xml you need to add <load-on-startup> tag to load the servlet while application is getting deployed in server. This are basics of servlet.

<servlet>
    <servlet-name>Servlet</servlet-name>
    <display-name>Simple Servlet</display-name>
    <servlet-class>com.package.ServletClass</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>

Upvotes: 2

Related Questions