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.

Recommended Answers

All 3 Replies

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


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


  // request email from servlet
  String email = (String)request.getAttribute("email");

  // print email 


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>

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.