JSP Response setHeader

JSP Response setHeader


Posted in : Java Posted on : May 11, 2012 at 5:49 PM Comments : [ 0 ]

In this tutorial you will learn about how to set response header in JSP.

JSP Response setHeader

In this tutorial you will learn about how to set response header in JSP.

In JSP header can be set to the response by using the setHeader() method of HttpServletResponse interface. However addHeader() method of this interface is also used for this purpose but in perspective of setHeader() method it sets the header by overwrites over the header if the header is already existed and the addHeader() method adds the new header. To check whether the header is already set or not response.containsHeader() method can be used.

Syntax of setHeader() :

void setHeader(String name, String value)

Both argument is of String type, where the first argument specifies the name of the header and second specifies the value of the corresponding header name.

Example :

An example that is being given here will help in understanding how to set response header. In this example I have created a JSP page where I have designed a form to take input through the user. Then wrote the java code using scriptlets into which at first I have checked for the header name I want to add to the response header, then adds the header by name "Author" and again used the containsHeader() method for checking the existence of currently added response header.

jspResponseSetHeader.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.net.URL"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Response setHeader</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter your Name :</td>
<td><input type="text" name="name" />
</td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
<%
String nm = request.getParameter("name");

if (nm != null) {
out.println("The Header <b>" + nm + "</b> has been already set : "
+ response.containsHeader("Author")+"<br>");
response.setHeader("Author", nm);
out.println("Author : " + nm+"<br>");
out.println("The Header <b>" + nm + "</b> has been already set : "
+ response.containsHeader("Author"));
}
%>
</body>
</html>

Output :

When you will execute the above JSP page a front page will be displayed to you for enter some value in the textbox as follows :

When you will click on Submit button after filling value in the given textbox then the output will be as follows :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics