Friday, February 17, 2012

Spring Beans and Dependency Injection - Part 5

Using the Spring Beans.

We will create ShopServlet and CheckoutServlet so we can play with the Spring Beans we just created from a browser.

First, let us create a utility class to load the Spring Beans.

In your /src/org/confucius folder, create a class SpringUtils.java, like this:

 package org.confucius;  

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUtils {
private static ApplicationContext springContext = null;

public static ApplicationContext getSpringContext() {
if (springContext == null){
springContext = new ClassPathXmlApplicationContext("spring-beans.xml");
}

return springContext;
}

}



This method loads the Spring Context exactly once, from the spring-beans.xml file.

Now, in your /src/org/confucius, create a Class ShopServlet.java, like this:

 package org.confucius;  

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShopServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Shop shop = (Shop) SpringUtils.getSpringContext().getBean("shop");
Cart cart = shop.getCart();

int numItems = cart.getNumItems();
cart.setNumItems(numItems+1);

response.getWriter().write("Number of items in shopping cart = " + cart.getNumItems());

}

}



This Servlet gets the shop bean and increments the items in its cart.

Now in your /src/org/confucius, create a class CheckoutServlet.java, like this:

 package org.confucius;  

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Checkout checkout = (Checkout) SpringUtils.getSpringContext().getBean("checkout");
Cart cart = checkout.getCart();

response.getWriter().write("Number of items in checkout cart = " + cart.getNumItems());

}

}



This Servlet get the checkout bean and prints the number of items in its cart.


Update your web.xml to use these Servlets, like this:

 <web-app>   
<servlet>
<servlet-name>shop</servlet-name>
<servlet-class>org.confucius.ShopServlet</servlet-class>
</servlet>

<servlet>
<servlet-name>checkout</servlet-name>
<servlet-class>org.confucius.CheckoutServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>shop</servlet-name>
<url-pattern>/shop</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>checkout</servlet-name>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>

</web-app>

No comments: