Showing posts with label servlet context. Show all posts
Showing posts with label servlet context. Show all posts

Wednesday, March 23, 2011

Quick Recap: Chapters 6 to 19

Let us quickly go through what we learnt in the previous chapters…

Request Handling Basics:

• The HTTP methods GET, POST, and PUT are how browsers and Web servers trade data with each other
• The GET retrieves a page without providing much information, while a POST can package huge amounts of information with its request
• The most important objects in the servlet process are the request and response objects
• The request parameters for the servlet are the strings sent by the client to the Servlet Container. The container parses the request and puts the information in a HttpServletRequest object which is passed to the servlet
• The container wraps the response parameters with the HttpServletResponse object which is passed back to the container

Scope:

• When something has Context scope it is application-wide and all users can share data
• Session scope means one user can share data across page views, but other users can't
• Request scope restricts data to only that page


Servlet Lifecycle:

• The init() method is used to initialize the Servlet
• The service() methods (doGet(), doPost() etc) get invoked everytime a user request gets submitted
• The destroy() method is used to kill/invalidate the Servlet once it is no longer required.


Key Terms we Learnt:

The key terms we learnt and understood in these chapters were:

1. Redirection
2. Servlet Life-Cycle
3. Servlet Forwarding and Includes
4. Servlet attribute
5. Context parameters
6. Application session
7. listeners

Previous Chapter: Chapter 19 - Listeners & Interfaces in the Web Context

Next Chapter: Self Test - Chapters 6 to 19

Thursday, March 17, 2011

Chapter 16: Servlet Context

In the previous chapter, we saw how data can be stored and utilized per user session. The session is specific to a users navigation of a website and is not shared among users. If you want the system to retain some information that needs to be shared among various users of the system, we need to user the Context. In this chapter, we are going to see what the context is and what are the methods that are available for us to use.

So, lets get started!!!

The Servlet Context

A Web application includes many parts. It is more than just one servlet or JSP. Numerous JSPs and one or more Servlets and other supporting java classes together form the web application. To help manage an application, you will sometimes need to set and get information that all of the servlets share together, which we will refer to as context-wide.

For Example, if you want a single name using which you can refer to the application, you can set it in the servlet context and have it shared across all instances that use the application.

Ex Code:
public void init(ServletConfig config) throws ServletException
{
super.init(config);
// Get the Context
ServletContext context =config.getServletContext();
// Set the attribute
context.setAttribute(“appName", "My Test App");
}

Any time you want, you can refer to this attribute in the context and get its value like below:

String appName = context.getAttribute(“appName”);

After the above line of code, the variable appName will have the value “My Test App”

Methods in the Servlet Context

Apart from setting and getting custom attributes used for our application, the context also contains various methods that we can use to retrieve specific information about the application and other aspects. They are:

getAttributeNames() - Returns an Enumeration object containing the attribute names available within this servlet context.
getContext(String uripath) - Returns a ServletContext object that corresponds to a specified URL on the server.
getInitParameter(String name) - Returns a string containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.
getInitParameterNames() - Returns the names of the context's initialization parameters as an Enumeration of string objects, or an empty Enumeration if the context has no initialization parameters.
getMajorVersion() - Returns the major version as an int of the Java Servlet API that this Servlet Container supports.
getMimeType(java.lang.String file) - Returns the MIME type as a string of the specified file, or null if the MIME type is not known.
getMinorVersion() - Returns the minor version as an int of the Servlet API that this Servlet Container supports.
getNamedDispatcher(String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
getRealPath(String path) - Returns a string containing the real path for a given virtual path.
getRequestDispatcher(String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
getResource(String path) - Returns a URL to the resource that is mapped to a specified path.
getResourceAsStream(String path) - Returns the resource located at the named path as an InputStream object.
getServerInfo() Returns the name and version as a String of the Servlet Container on which the servlet is running.

So, as you can see, the context is extremely powerful and useful for any J2EE developer…

Previous Chapter: Chapter 15 - Session

Next Chapter: Chapter 17 - Servlet Life Cycle

Wednesday, March 2, 2011

Chapter 11: Obtaining a Servlets Initialization Parameters

We know what a Servlet is (I wouldn't blame you if you said “I know it pal. All you have spoken about in the past chapters is Servlets only”). We also know that a Servlet needs to be initialized in order to be of any use in our application. In this chapter, we are going to find out, how we can access the ServletContext and figure out the Servlets Initialization Parameters.

So, lets get started!!!

The Servlet Context

A Web application consists of many parts. It can be a combination of JSP pages, servlets, tag libraries, Java beans, and other class files. The Java Virtual Machine creates a memory box for all of these called a ServletContext object which maintains information about our Web application. If you want to know more about your application and its state, the first place to go is the “ServletContext”. As the Servlet API states, the ServletContext allows you get many kinds of information about the Application. You can get application-level initialization parameters. You can also set and get application attributes, as well as the major and minor version of the Servlet API that this Servlet Container supports. One very interesting capability is to get hold of RequestDispatcher object to forward requests to other application components within the server, or to include responses from certain components within the servlet and to log a message to application log file. The ServletContext object is how you can set, get, and change application level attributes and talk to the Servlet Container.

Exam Trivia:
The Servlet context can be used to get, set and change application level attributes. This cannot be used to alter session parameters. Many people get confused about the ServletContext and its ability to alter the Session.

Servlet Context Methods

The getInitParameter and getInitParameterNames methods retrieve the application wide or rather the “Web application” parameters.
• The getInitParameter method returns a string containing the value of the parameter or null if the parameter does not exist.
• The getInitParameterNames method retrieves the names of the servlet's initialization parameters as an Enumeration of string objects. If there aren't any, it returns an empty Enumeration.

A Servlet that Reads the ServletContext

Let us now take a look at a simple servlet that is going to read the ServletContext and understand the initialization parameters.

Servlet Code

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletContextReadingServlet extends HttpServlet
{
/**
* Method that is going to read the Servlet Context
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{

response.setContentType("text/html");
PrintWriter writer = response.getWriter();

writer.println("< h1 >ServletConfig " + "Initialization Parameters < / h1 >");
writer.println("< ul >");
Enumeration params = getServletConfig().getInitParameterNames();
while (params.hasMoreElements())
{
String param = (String) params.nextElement();
String value =
getServletConfig().getInitParameter(param);
writer.println("< li >< b >" + param + "< / b > = " + value);
}
writer.println("< / ul >");
writer.println("< hr >");
}
}

The above Servlet is pretty straight forward (Aren’t all of our example Servlets straight forward?). It gets all the initialization parameters as an enumeration using the getInitParameterNames() method and then just prints them all on screen, one after the other.

Previous Chapter: Chapter 10 - Form Parameters

Next Chapter: Chapter 12 - Retrieving HTTP Request Header Information
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers