Hi javaAddicts

I am a novice java programmer.
I am in a learning process in java servlets.

How to load a servlet and invoke its method from index.jsp.

I want the servlet to execute first and dispatch its value to index.jsp

and also i dont want to use redirect from jsp and again dispatching the values from servlet.
Is there is a way to access it.

This is an simple approach to dispatch a value to index.jsp

index.html:

<html>
<body>
<h1 align="center">Select Person</h1>
<form method="POST" action="Person.do">
<select name="person" size="1">
<option value="a@example.com">Fred</option>
</select>
<br><br>
<center><input type="Submit"></center>
</form>
</body></html>

result.jsp:

<p>
<%
  // request email from servlet
  String email = (String)request.getAttribute("email");

  // print email 
  out.println("<br>"+email);
%>
</p>

Person.java:

package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Person extends HttpServlet
{
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String p = request.getParameter("person");

		// display email stored in web.xml
		PrintWriter out = response.getWriter();
		request.setAttribute("email", p);
		
		RequestDispatcher view = request.getRequestDispatcher("result.jsp");
		view.forward(request, response);
	}
}

web.xml (stored inside WEB-INF):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Person Servlet Example</display-name>
  <servlet>
    <servlet-name>Person</servlet-name>
    <servlet-class>com.example.Person</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Person</servlet-name>
    <url-pattern>/Person.do</url-pattern>
  </servlet-mapping>
</web-app>

Thanks for the reply but i dont need to send the form data s into the servlets.
On visiting my site's index.jsp (ie. on running the project the first page what i see) should make a call to a servlet and dispatch its value to index.jsp

for example, if i want to list out all the existing users in index.jsp what i should do now.

why no write Java class and call it object there?

class HelpJava{
	public void printMe(String name, PrintWriter out){
		out.print('Hello: '+name);		
	}
	
}
<%
PrintWriter out = request.getPrintWriter();
 HelpJava obj = new HelpJava();
 obj.printMe("Stefano", out);
%>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.