Home Tutorial Servlet Java Servlet : Setting Attribute

 
 

Share on Google+Share on Google+
Java Servlet : Setting Attribute
Posted on: October 8, 2012 at 12:00 AM
Advertisement
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.

Parameters:
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.

SetAttributeExample.java - This is servlet in which we are setting attribute name and forward to the jsp page.

package net.roseindia;

import java.io.IOException;
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
				.getRequestDispatcher("/setAttributeExample.jsp");
		rd.forward(request, response);
	}

}

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


<html>

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

web.xml -

<?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>SetAttributeExample</display-name>

<servlet-name>SetAttributeExample</servlet-name>
<servlet-class>net.roseindia.SetAttributeExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetAttributeExample</servlet-name>
<url-pattern>/SetAttributeExample</url-pattern>
</servlet-mapping>
</web-app>

Output :

Advertisement

Related Tags for Java Servlet : Setting Attribute:


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.

Posted on: October 8, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com