Home Tutorial Servlet Pass parameters from JSP to Servlet

 
 

Pass parameters from JSP to Servlet
Posted on: November 18, 2009 at 12:00 AM
In this section, you will learn how to pass parameters from JSP page to servlet.

Pass parameters from JSP to Servlet

In this section, you will learn how to pass parameters from JSP page to servlet. For this purpose, we have used setAttribute() method. This method sets the value of the attribute for the request which is retrieved later in the servlet by passing the request object through the dispatcher method. The set value of the attribute is retrieved by the getAttribute() method of the request object.

Here is the code of jsptoServlet.jsp:

<%@page language="java"%>
<%
request.setAttribute("Company Name","Roseindia");
request.setAttribute("Address","Rohini,Delhi");
String strViewPage="../GettingParameter";
RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
if (dispatcher != null){
dispatcher.forward(request, response);

%>

Here is the code of GettingParameter.java:

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

public class GettingParameter extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws IOException {
ServletOutputStream out = res.getOutputStream();
String name = req.getParameter("name");
String address = req.getParameter("address");
res.setContentType("text/html");
out.println("Name is: " + req.getAttribute("Company Name"));
out.println("Address is: " + req.getAttribute("Address"));
	}
}

Output

Name is: Roseindia Address is: Rohini,Delhi

Related Tags for Pass parameters from JSP to Servlet:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.