Share on Google+Share on Google+

Java Servlet : Setting Attribute

In this tutorial, we will discuss how setAttribute() method works.

Java Servlet : Setting Attribute

In this tutorial, we will discuss how setAttribute() method works.

setAttribute(String name,Object obj) :

If we want to limit the scope of an attribute to the request then we will set attribute on a request object. request.setAttribute(String name,Object obj) method stores an attribute in the request.

name - it is of String type and specify the name of the attribute
obj - Object to be stored

ExampleIn this example we are setting attribute whose scope is to the request. - This is servlet in which we are setting attribute name and forward to the jsp page.

package net.roseindia;

import javax.servlet.*;
import javax.servlet.http.*;

public class SetAttributeExample extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = "Roseindia";
		request.setAttribute("Name", name);
		ServletContext context = getServletContext();
		RequestDispatcher rd = context
		rd.forward(request, response);


setAttributeExample.jsp - In this jsp page we are displaying value which we set on the servlet.


Value which we set on servlet using request.setAttribute() method:
<font color="blue">
<%=request.getAttribute("Name") %>

web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">


Output :


Posted on: October 8, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.