How to Inject Spring Beans into Servlets Revisited.

Back in November I wrote a post about How to Inject Spring Beans into Servlets, since then one of the comments made on the post by angel, mentioned an interface and Servlet that comes with spring that does this the proper spring way. Thank you very much angel, this is what I was looking for before I wrote the last post 🙂

The proper way how this should be achieved is to write a class that implements HttpRequestHandler and define this class in your applicationContext.xml. Then you define a servlet in web.xml with a class of HttpRequestHandlerServlet and make sure the name of the servlet is the same as the bean you defined in applicationContext.xml.

First lets write a class that we want to inject into a servlet…

package name.kayley.httprequesthandlertest;

public interface ServiceToInject {
  public String someMethod();
}
package name.kayley.httprequesthandlertest;

public class ServiceToInjectImpl implements ServiceToInject {
  public String someMethod() {
      return "someMethod called";
  }
}

Next we’ll write a class that implements the HttpRequestHandler this is basically our servlet.

package name.kayley.httprequesthandlertest;

public class MyHttpRequestHandler implements HttpRequestHandler {

   private ServiceToInject serviceToInject;

   public void setServiceToInject(ServiceToInject serviceToInject) {
       this.serviceToInject = serviceToInject;
   }

   public void handleRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {

       System.out.println("******* HELLO *******");
       System.out.println(serviceToInject.someMethod());
   }
}

Next all we need to do is configure our web.xml and applicationContext.xml…

First applicationContext.xml…

<xml version="1.0" encoding="UTF-8">
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="serviceToInject" class="name.kayley.httprequesthandlertest.ServiceToInjectImpl"/>

    <bean id="myhttprequesthandler" class="name.kayley.httprequesthandlertest.MyHttpRequestHandler">
        <property name="serviceToInject" ref="serviceToInject"/>
    </bean>

</beans>

And finally configure your web.xml …

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>myhttprequesthandler</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myhttprequesthandler</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
    </servlet-mapping>
</web-app>

Now run your web app and go to http://localhost:8080/MyServlet

You should see in your console log the output of your injected servlet…

******* HELLO *******
someMethod called

Brilliant 🙂 Thanks again angel.

Technorati Tags: , , , ,

Clob Handling Made Easy in Java with Oracle 10g

I found out a pretty neat thing last week about the JDBC Driver for Oracle 10g.

Previously when I’ve had to use a CLOB (Character Large OBject) in Java using Oracle

I’ve had to use the Oracle specific classes, rather than use the java.sql classes.

i.e…


String sql = "SELECT DATA FROM MY_TABLE WHERE ID = ? FOR UPDATE";

PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, primaryKey);
ResultSet res = stmt.executeQuery();

oracle.sql.CLOB clob = (oracle.sql.CLOB)res.getClob(1);

Then you had to use methods on the CLOB class that are not available on javax.sql.Clob to stream the bytes to / from the database.
If you tried to use the methods that should have been used on the javax.sql.Clob class you got some sort of error, an Unsupported Driver Operation or the like (Haven’t done this for a while and my memory’s a bit rusty on it)

Since the 10g driver the oracle CLOB and BLOB classes both implement the jdbc interface properly, so you can just use the jdbc classes/interfaces
instead of putting oracle specific classes in your code.

This allows you to use


javax.sql.Clob clob = res.getClob(1);

and for writing using the jdbc methods…

out = clob.setAsciiStream(0);

and for reading …

in = new BufferedInputStream(clob.getAsciiStream());

Recently I’ve had to use a clob again, and I have always wondered why can’t I just go stmt.setClob() and rs.getClob() without having to use a load of byte streaming code.
Well the nice guys n gals at Oracle have done something similar for the 10g driver which I think is fantastic.

No more selecting for update, all you do is use the setString and getString methods on PreparedStatement and ResultSet.

You will need to set some oracle specific settings in the driver properties if you want to put data in that’s bigger than 32k.

I found this information out here

Nice one oracle, its about time 🙂 I wonder if they’ve done something similar for Blob handling!!

Technorati Tags: , , , ,

@Deprecated: How to Inject Spring Beans into Servlets.

This post has been Deprecated, see this post instead

A couple of months ago I was working on an application that used Servlets as entry points to an application, sort of like a web service. This was a new application and I decided to use the Spring framework for dependancy injection and to make using Hibernate easier.

I am fairly new to Spring and never needed to inject any spring beans into servlet before, and I thought there must be a way to do it. However after browsing through a number of websites, blog posts and forum posts, it appeared that there wasn’t a clean spring way to do this.

Solution 1

In the end I read somewhere that you could inject spring beans into the ServletContext, so I took this route.

With this you have to declare this little piece in your applicationContext.xml

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
 <property name="attributes">
     <map>
         <!-- inject the following beans into the servlet
context so the servlets can access them. -->
         <entry key="myBeanFromSpring">
             <ref bean="myBeanFromSpring"/>
         </entry>
     </map>
 </property>
</bean>

As you can see this puts the spring bean myBeanFromSpring into the servlet context. Therefore in your servlet code you can do the following…

protected void doGet(HttpServletRequest reqest, HttpServletResponse response)
                                         throws ServletException, IOException {

   MyBeanFromSpring myBean = MyBeanFromSpring)getServletContext().getAttribute("myBeanFromSpring");
   myBean.someOperation();
   ...
}

Although this works it still doesn’t feel very spring like.

Solution 2

There is another way to achieve the same thing. You can use WebApplicationContext and get the beans directly from Spring without having to inject anything into the servlet context.

void doGet(HttpServletRequest reqest, HttpServletResponse response)
                                         throws ServletException, IOException {

   WebApplicationContext springContext =
       WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   MyBeanFromSpring myBean =(MyBeanFromSpring)springContext.getBean("myBeanFromSpring");
   myBean.someOperation();
   ...
}

Although this achieves the same thing and is probably more concise than Solution 1, it still is not achieving what I initially wanted, which was dependancy injection into the servlet.

Solution 3

Although I stayed with Solution 1 for the application it got me thinking. So I set out to write a sub class of HttpServlet that would use the servletContext solution and use reflection to figure out if the servlet had any setters on that spring should call.

My original servlet that had to do all the stuff with getting the servlet context suddenly looks a lot more spring-like…

import name.kayley.springutils.SpringDependencyInjectionServlet;

public class MyServlet extends SpringDependencyInjectionServlet {

   private MyBeanFromSpring myBean;

   public void setMyBeanFromSpring(MyBeanFromSpring myBean) {
       this.myBean = myBean;
   }

   protected void doGet(HttpServletRequest reqest, HttpServletResponse response)
                                           throws ServletException, IOException {

       myBean.someOperation();
   }
}

And here is the source of the SpringDependencyInjectionServlet, go easy on it, Its the first version and it passes the unit tests i have written for it, use it at your own risk or as a starting point, but like I said it appears to work ok so far.

I have attempted to keep in with the spring autowiring of giving 2 options, autowire by type and by name, so you can override autowireByType if you want to autowire by name. I think they need some work as I believe that autowire by name should go off the name of the parameter to the setter method and not the setter method name itself… keep coming back for updates.

package name.kayley.springutils;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class SpringDependencyInjectionServlet extends HttpServlet {

   private static final Logger logger =
Logger.getLogger(SpringDependencyInjectionServlet.class.getName());


   protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
       Enumeration attributeNames = getServletContext().getAttributeNames();

       while (attributeNames.hasMoreElements()) {

           String name = (String) attributeNames.nextElement();
           logger.log(Level.INFO, "attempting to autowire " + name);

           autowire(name);
       }

       super.service(request, response);
   }

   protected boolean autowireByType() {
       return true;
   }

   private void autowire(String name) {
       if (name != null) {
           Object attribute = getServletContext().getAttribute(name);
           Class c = getClass();
           while (c != null && c != c.getSuperclass()) {
               try {
                   if (autowireByType()) {
                       if (byType(c, attribute)) {
                           break;
                       }
                       else {
                           c = c.getSuperclass();
                       }
                   }
                   else {
                       if (byName(c, name, attribute)) {
                           break;
                       }
                       else {
                           c = c.getSuperclass();
                       }
                   }
               }
               catch (NoSuchMethodException e) {
                   c = c.getSuperclass();
               }
           }
       }
   }

   private boolean byName(Class c, String name, Object attribute)
       throws NoSuchMethodException {
       boolean success = false;

       if (attribute != null) {

           Method[] methods = c.getDeclaredMethods();
           for (Method method : methods) {
               if (method.getName().equals(getMethodName(name))) {
                   Class[] paramTypes = method.getParameterTypes();

                   if (paramTypes.length == 1) {
                       success = invokeSpringBeanSetter(method, attribute);
                   }
               }
           }
       }
       return success;
   }

   private boolean byType(Class c, Object attribute) {
       boolean success = false;

       if (attribute != null) {
           Method[] methods = c.getDeclaredMethods();

           for (Method method : methods) {
               Class[] paramTypes = method.getParameterTypes();

               Class attributeClass = attribute.getClass();
               if (paramTypes.length == 1 &&
          paramTypes[0].equals(attributeClass)) {
                   boolean succeeded = invokeSpringBeanSetter(method,attribute);
                   if (!success && succeeded) {
                       success = succeeded;
                   }
               }
           }
       }
       return success;
   }

   private boolean invokeSpringBeanSetter(Method method, Object attribute) {
       boolean success = false;
       try {
           method.invoke(this, attribute);
           success = true;
       }
       catch (Exception e) {
           // TODO do we care?
       }
       return success;
   }

   private String getMethodName(String contextName) {
       return "set" + StringUtils.capitalize(contextName);
   }
}

Technorati Tags: , , , ,

Hello World!

I’m new to all this blogging malarkey, I have been advised to do so by my friend and colleague Andrew Beacock. It appears I am worthy of sharing some of my knowledge of all things java and software development related to the world.

So lets start with a bit of geeky fun…

public class FirstBlogPost {
    public FirstBlogPost() {
        System.out.println("Hello World!");
    }
}
class FirstBlogPost
  def initialize
    puts 'Hello World!'
  end
end

Maybe I should have named this post “Hello World in Java and Ruby” :o)

That’s all for now, check back later for more in depth advice and discoveries.