ThoughtWorks is hiring...

Thoughtworks is hiring in US right now. If you want to work with cool and smart people, check it out: http://www.thoughtworks.com/jobs/United-States-Job-Openings.html

How to display an image within a JSP from Database

I'm using Spring/Struts2/Hibernate in my current project. We have a requirement to upload an image into database, then display that image on the website within a jsp page. We wrote a servlet to stream out the image from database, but there is no way to test the code outside of the web container.

Then I tried to find a way to inject the Spring beans into the Servlet. Fortunately, Spring provides FrameworkServlet: Base servlet for servlets within the web framework. Allows integration with an application context, in a JavaBean-based overall solution. By extending FrameworkServlet, I could load Spring WebApplicationContext by setting "contextConfigLocation" parameter in web.xml.

This above solution made my code much simpler. Unfortunately, I still could not test the code outside of the web container, since it's so difficult to setup WebApplicationContext from a unit test. In the end, I had to do some tradeoff, by overwriting the initFrameworkServlet() method in FrameworkServlet, I could unit test the rest of the code but this method.

public class ImageStreamServlet extends FrameworkServlet {

private MyService myService;

protected void setMySerivce(MySerivce myService) {
this.myService= myService;
}

@Override
protected void doService(HttpServletRequest request,
HttpServletResponse response) throws Exception {

String id = request.getParameter("id");
MyObject myObject = MyService.findById(Long.parseLong(id));
if (myObject != null) {
response.reset();
response.setContentType(myObject.getImageType());
IOUtils.write(myObject .getImageData(), response
.getOutputStream());

}

/**
* This method is not covered by test...
*/
protected void initFrameworkServlet() throws ServletException {
super.initFrameworkServlet();
myService = (MyService ) getWebApplicationContext()
.getBean("myService ");
}

}


Basically, MyService can be mocked out in my test now:)