Sending Parameters to Servlet

 Sending Parameters to Servlet in Java

 


 

ServletsHome

Sometimes the user request may contain some data. It is sent through URL in the form of  name value pairs. This is generally known as a query string.

When URL submitted servlet will read this data from the query string, process it and sends a response back to the user.

 

Today, you are going to lean how to pass data and read it in servlet.

 Sending Parameters to Servlet using query string

→ In the URL after the servlet name query string  added.

Query string and URL separated by  ' ? ' .

  with query string, we pass parameter name  values to servlet.

http://localhost:8080/FirstWebApplication/PostParameterServlet?name=abc

Here we are using a simple GenericServlet example.

A service method taking two parameters - request,response

Inside the service method, a PrintWriter object reference(out) is created. 

That point to the PrintWriter object, which is return by response.getWriter().

Using out object println() method we can display a message on client screen. 

Finally out.close() closes the stream.

 

 

Example:
 
PostParametersServlet.java 
 
import java.io.*;

import javax.servlet.*; 
 
 
public class PostParametersServlet extends GenericServlet{

 public void service(ServletRequest request,ServletReresponse response)
	throws ServletException,IoException{
 
	 PrintWriter out= response.getWriter(); 
 
        String pname= request.getParameter("name"); 
 
        out.println("Hello..!!" + pname); 
 
        out.close(); 
 
}
 
 

Create the above servlet in web project, and add the servlet to web.xml

 

Open the Servlet URL in a browser and parameters along with URL as 

shown in below URL.

 

http://localhost:8080/FirstWebApplication/PostParameterServlet?name=abc

 
Output:
 
Hello abc 
 
 
 
Example2: 
 
 
import java.io.*;

import javax.servlet.*;

 

public class PostParametersServlet2 extends GenericServlet{

  public void service(ServletRequest req,ServletReresponse res)

      throws ServletException, IOException{

  PrintWriter out= res.getWriter();

  String sname= req.getParameter("t1");



  out.println("Hello..." + sname);

  out.close();

}

}

 


 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP