I have 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 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:
package org.kodejava.example.servlet;
import org.kodejava.example.servlet.dao.UserDao;
import org.kodejava.example.servlet.model.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SpringBeanServletExample extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletContext context = getServletContext();
WebApplicationContext ctx =
WebApplicationContextUtils
.getWebApplicationContext(context);
UserDao dao = ctx.getBean("userDao", UserDao.class);
Long userId = Long.valueOf(req.getParameter("user_id"));
User user = dao.getUser(userId);
res.setContentType("text/html");
PrintWriter pw = res.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’s WebApplicationContext
. With this object in my hand I can get my UserDao
implementation and do a query from database.
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
Hi Wayan, did you define your servlet within xml bean configuration or this is just enough?
Hi Edgardo,
You don’t need to configure the servlet in the xml bean configuration. This configuration only for the spring beans that will be use by the application. The complete code can be seen in the GitHub repository.