JSP development servlet calls dao, servletspring injected with spring Management

Source: Internet
Author: User

JSP development servlet calls dao, servletspring injected with spring Management

JSPs call and inject the dao managed by spring in servlet

We can use spring dependency injection to inject dao into the action, and then we can directly call the method in dao, but the servlet is not managed by the spring container, therefore, the dao class cannot be injected into the servlet, And the dao method cannot be used.

The implementation method is as follows:

Private UserDao userDao; public void init () throws ServletException {super. init (); ServletContext servletContext = this. getServletContext (); WebApplicationContext ctx = WebApplicationContextUtils. getWebApplicationContext (servletContext); userDao = (UserDao) ctx. getBean ("userDao ");}

Add the private variable UserDao to the servlet and initialize it in the init () method of the servlet.

Public UserDao getUserDao () {return userDao;} public void setUserDao (UserDao userDao) {this. userDao = userDao ;}

Add the get set Method (this is not tested)

You can call dao in servlet at will later, yeah!

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.