我已经创建了一个基于servlet的Web应用程序,并且我想在其中使用Spring Bean。那么我该如何在servlet中做到这一点。好吧,这样做很简单。首先,我必须获得Spring的WebApplicationContext,从那里我的servlet可以获取所需的bean。
让我们来看一些有关如何执行此操作的代码,下面我们开始:
package org.nhooo.example.servlet;
import org.nhooo.example.servlet.dao.UserDao;
import org.nhooo.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();
}
}在上面的 Java Servlet doGet ()方法中,我得到了 ServletContext,然后 WebApplicationContextUtils 帮助我得到 Spring 的 WebApplicationContext。有了这个对象,我就可以获得 UserDao 实现并从数据库中进行查询。