JSP Implicit Objects

JSP Implicit Objects

Table of Contents

JSP implicit objects are created by JSP Engine during translation JSP to Servlet(translation phase). We can use them directly in JSP pages without initializing or declaring them because they are predefined.  There are nine JSP implicit objects: page, out, request, response, session, application, config, pageContext and Exception. Let’s look closer at them.

Object out is an instance of class javax.servlet.jsp.JspWriter. It is used for the output content for client response. It contains methods for writing the value which has been passed them, such as: 

[box type=”shadow” align=”” class=”” width=””]void print();
void println();
void newLine();[/box]

Here is the example of use:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test out implicit object</title>
</head>
<body>
<%
out.println("line 1");
out.newLine();
out.print("line 2");
%>
</body>
</html>

The output will be:

line 1
line 2

The out implicit object has more methods:

void clear() – clears the output buffer without giving possibility to write the content to the client. It is called as: out.clear();

void clearBuffer()– method is similar to the previous clear() method. The difference is that in the case of invoking out.clear() we are already flushed buffer and it throws an exception. In case of out.clearBuffer() it doesn’t.

void flush() – method clears the buffer just like clear() method, but content is forcing to write to the output before flushing it.

boolean isAutoFlush() :  can return true or false boolean value. It returns true if the buffer is automatically flushed.

int getBufferSize() –  the output of this methods is the size of output buffer in bytes.int getRemaining() – the method output is the number of bytes remaining before hitting the buffer overflow condition.

The request implicit object (javax.servlet.http.HttpServletRequest) contains the data that has been sent to the JSP page by the client. A user is prompted to log in and signup forms in JSP,  to fill in some details. All this data is sending to JSP as a request object.

The request Implicit Object contains methods:

getParameter(String name) – method to get the value of a particular request parameter. For example, a user enters the username and password at the login page. After verification, the user is redirected to another page, then using a method request.getParameter we can get the value of username and password:

[box type=”shadow” align=”” class=”” width=””]String Uid= request.getParameter(“username”);
String Pass= request.getParameter(“password”);[/box]

getParameterNames() – method returns an enumeration of all the parameter names from the request. The example of use:

Enumeration e= request.getParameterNames();

getParameterValues(String name) – method returns the all values of a specific parameter. The example of use:

String[] allpasswords = request.getParameterValues(“password”);

getAttribute(String name) – method is used to get the attribute value.  request.getAttribute(“name”) 

getAttributeNames() – method gets the attribute names from the current session. It returns the enumeration.

setAttribute(String,Object) – method to assign an object value to a specific attribute.

removeAttribute(String) – method is using to remove an attribute. 

getCookies() – method returns an array of cookie objects received from the client.

getHeader(String name) – method is used to get specific header information from the request.

getHeaderNames() – method returns enumerator of all header names. 

getRequestURI() –  method returns the URL of current JSP page.

getMethod() – method returns HTTP request method, such as GET for a Get request or POST for a Post Request.getQueryString() – method is used to get the query string associated with the JSP page URL.

The response implicit object(javax.servlet.http.HttpServletResponse) is basically used to build, modify, and dealing with the response that will be sent to the client(browser) after processing the request.

It contains such methods:

void setContentType(String type) – method tells client the type of response data by setting up the MIME type and character encoding. This information helps browser to interpret the response. For example:

response.setContentType(“text/html”);

response.setContentType(“image/gif”);

void sendRedirect(String address) – method redirects the control to the specified page. For example: 

response.sendRedirect(“http://google.com”);

void addHeader(String name, String value) – method adds a specified header name and it’s value to the response. For example:

response.addHeader(“myheader”, “hello”);

void setHeader(String name, String value) –  method overrides the current value of header with the new value. Example:

response.setHeader(“myheader”, “new_hello”);

boolean containsHeader(String name) – method returns a boolean value true if the header is present in the response, otherwise – false. For example 

response.containsHeader(“myheader”);

void addCookie(Cookie cookie) – method adds a specified cookie to the response. 

void sendError(int status_code, String message) – method is used to send an error code and an error message in the response. Here is the example of use:

response.sendError(404, “Page not found”);boolean isCommitted() -method returns true if the Http Response has been sent to the client, else it gives false.

Exampe of use:

<% if(response.isCommited())
{
           <%--do something --%>
}else {
           <%--do something else --%>
} %>

void setStatus(int statuscode) – method is used to set the HTTP status to a given response.For example:

response.setStatus(200);

Here is an example of use response implicit object, that performs the login:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html> 
<head><title>Check Credentials</title>
</head>
<body> 
<% 
String username=request.getParameter("user"); 
String password=request.getParameter("password"); 
if(username.equals("user") && password.equals("qwerty"))
{
 response.sendRedirect("success.jsp");
}
else
{
 response.sendRedirect("failed.jsp");
}
%> 
</body> 
</html>

The session implicit object is used for storing data for an individual user to make it available on other JSP pages until the user session is active.

It has methods to work with attributes:

setAttribute(String, object) – method is used to save an object in a session.

getAttribute(String name) – method fetches from a session an attribute that was set by the method setAttribute.

removeAttribute(String name) – method removes the attribute from the session.

getAttributeNames – method returns an enumeration of all the objects stored in a session. 

Also, the session object contains more methods for different purposes:

getCreationTime() – method returns the time of session activation.

getId() – returns a unique string identifier of a session assigned by the Servlet container during the creation.

isNew() – method returns true if cookies are disabled on the client-side.

invalidate() – method kills a session.

getMaxInactiveInterval() –  method returns session maximum inactivate time interval in seconds.getLastAccessedTime() – method is used to know the last accessed time to a session.

The application implicit object is used for maintaining useful data across the whole JSP application.

It contains methods to work with attributes:

Object getAttribute(String attributeName);

void setAttribute(String attributeName, Object object);

void removeAttribute(String objectName);

Enumeration getAttributeNames(); 

The example of using:

application.setAttribute(“myAttribute”, “some_value”);

String string = (String)application.getAttribute(“myAttribute”);

application.removeAttribute(“myAttribute”);

Some more methods:String getInitParameter(String name) – returns the value of the initialization parameter for a given parameter name. You can get the context parameters from web.xml:

  <web-app>
    …
    <context-param>
    <param-name>param</param-name>
    <param-value>hello</param-value>
    </context-param>
    </web-app>

This line of code will return String “hello”:

String s=application.getInitParameter(“param”);

Enumeration getInitParameterNames() – method returns all the initialization parameters.

Enumeration e= application.getinitParameterNames();

String getRealPath(String value)– method converts a path to file system absolute path.

String abspath = application.getRealPath(“/index.jsp”);

void log(String message)– method writes the given message to the container default log file.

application.log(“Here is our message”);

String getServerInfo() – method returns the name and version of web container.

The exception implicit object (java.lang.Throwable) is used to displaying the error messages. This object is not Null just to the JSP pages with isErrorPage set to true. Here is an example of use:

<%@ page isErrorPage=”true” %> 

An application got this Exception: <%= exception %>

Please correct the issue in your code.

The page implicit object (javax.servlet.jsp.PageContext) is a reference to the current Servlet instance, generated during the translation phase from a JSP page. We would not dip into detail as it is rarely used. It is not a useful object for building an application on JSP technology.

The pageContext implicit object is using to access page, request, application, and session attributes. You can use this object to find attribute, get attribute, set attribute, and remove attribute at any of levels, such as JSP Page, HTTP Request, HTTP Session, Application Level. Here are the methods:

Object findAttribute (String name);

void removeAttribute(String name, int scope);

void setAttribute(String name, Object value, int scope);

Object getAttribute (String name, int scope).

Example of usage:

Object obj = pageContext.getAttribute(“test”, PageContext. PAGE_CONTEXT);

Object obj = pageContext.getAttribute(“test”, PageContext. APPLICATION_CONTEXT);

The config implicit object (javax.servlet.ServletConfig) holds the configuration of JSP, such as a servlet context, a servlet name, configuration parameters, etc. It has such methods:

String getInitParameter(String param) – method to get initialization parameters.

Enumeration getInitParameterNames() – method returns enumeration of initialization parameters.

ServletContext getServletContext() – method returns Servlet context reference.

ServletContext contains methods helpful for communication between servlet and its servlet container: to get the MIME type of a file, dispatch requests, to write to a log file, etc.

String getServletName() – method returns the name of the servlet. We usually define the servlet name in the web.xml file inside tag <servlet-name>.

Let’s look at the example of using the config implicit object. Here is web.xml:

<web-app>
<servlet> 
<servlet-name>TestServlet</servlet-name> 
<jsp-file>/test.jsp</jsp-file> 
</servlet> 

<servlet-mapping> 
<servlet-name>TestServlet</servlet-name> 
<url-pattern>/test</url-pattern> 
</servlet-mapping> 
</web-app>

Here is our test.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head> <title>Testing the config Implicit Object</title>
</head>
<body>
<% 
String name = config.getServletName(); 
out.print("Servlet Name is: "+ name); 
%>
</body>
</html>

The output will be: 

TestServlet

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article