How do I get Spring's Bean from a servlet?

Category: javax.servlet, viewed: 13766 time(s).

I've created a servlet based web application and I want to used Spring beans in it. So how do I do this in my servlet. Well it simple enough to do this. First of all of course I have to obtain the Spring's WebApplicationContext, from where I can grab the required bean by my servlet.

Let's see some lines of code on how to do it, here we go:

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

    ServletContext context = getServletContext();
    WebApplicationContext applicationContext =
            WebApplicationContextUtils
            .getWebApplicationContext(context);

    Long userId = Long.valueOf(request.getParameter("user_id"));
    UserDao dao = (UserDao) applicationContext.getBean("userDao");
    User user = dao.getUser(userId);

    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.print("User Details: " + user.toString());
    pw.flush();
}

Inside the Java Servlet doGet() method above I get the ServletContext, next the WebApplicationContextUtils help me to get Spring WebApplicationContext. With this object in my hand I can get my UserDao implementation and do a query from database.

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats