How do I get Spring AplicationContext from a servlet?
Category: javax.servlet, viewed: 1889 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.
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I get servlet request header information?
- How do I get servlet request URL information?
- How do I read servlet context initilization parameters?
- How do I know session last access time?
- How do I get a notification when session attribute was changed?
- How do I capture session creation and removal events?
- How do I invalidate user's session?
- How do I get client IP and hostname in Servlet?
- How do I set the maximum age of a cookie?
- How do I send a response status in servlet?
- How do I read servlet init parameter?
- How do I read cookie in Servlet?
- How do I send a cookie in Servlet?
- How do I read text file in Servlet?
- How do I share object or data between users in web application?
- How do I get my web application real path?
- How do I check if parameter is exists in servlet request?
- How do I get parameter names from servlet request?
- How do I read request parameter from servlet?
- How do I create a hit counter Servlet?
Most Viewed Examples
Latest Code Examples
Categories
100 Top & Latest
Latest Jobs
Blog Entries
Forums Entries
- Google Chrome
- Re: Importing and scanning the text
- Re: What Java books have you read?
- Re: How to create exe file
- How to create exe file
- Re: What Java books have you read?
- Infix expression
- Importing and scanning the text
- Re: I want to reduce the size of a JPG image
- MOVED: I want to reduce the size of a JPG image
