[Liu Yang Java]_spring integration servlet "Supplement" _ 14th

Source: Internet
Author: User

In this article we'll show you how the spring framework integrates the servlet. It's not much of a challenge to see the surface phenomenon, but it's not as easy as it is in the integration process.

Since it is introduced in a complementary way, we will go directly to the previous case to illustrate the steps of integration implementation

1. Case Requirements

    • Through the spring frame annotation way to get through the control layer, the business logic layer, the data access layer between the dependency relationship
    • The control layer uses the servlet to complete the user request and the corresponding processing
    • Then rely on the @autowired approach to inject the business logic layer in the servlet
    • The business logic layer also relies on the @autowired approach to inject the data access layer
    • The data access layer uses spring for JDBC support to get data, edit data, and so on

2. Technical difficulties

    • How to let Servlets be managed by the spring framework
    • How to get the Tomcat server to load the spring framework (that is, how to load the spring configuration file)
    • Once the servlet is managed by the spring framework, but the @autowired annotation is not automatically dependent on the injected object in the business logic layer, how can this be resolved

3. Implementation of the Tomcat server load spring configuration file

    • Import Spring-web.jar Package
    • Adding <listener.../> Listening tags to the Web. xml file
    • Use the Spring Framework's contextloaderlistener to load the spring configuration file
<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"ID= "webapp_id"version= "3.1">  <Display-name>Spring</Display-name>  <welcome-file-list>    <Welcome-file>Index.html</Welcome-file>    <Welcome-file>Index.htm</Welcome-file>    <Welcome-file>index.jsp</Welcome-file>    <Welcome-file>Default.html</Welcome-file>    <Welcome-file>Default.htm</Welcome-file>    <Welcome-file>default.jsp</Welcome-file>  </welcome-file-list>    <Context-param>      <Param-name>Contextconfiglocation</Param-name>      <Param-value>Classpath:com/gxa/spring/day02/spring-controller.xml</Param-value>  </Context-param>    <Listener>      <Listener-class>Org.springframework.web.context.ContextLoaderListener</Listener-class>  </Listener></Web-app>

4. Use <context:componet-scan .../> in the spring configuration file to scan the annotation class

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " >    <Context:component-scanBase-package= "Com.gxa.spring.day02"></Context:component-scan>        </Beans> 

5. Create Userservlet to test whether Userservlet is managed by the spring framework by overriding the Init method in HttpServlet. because @autowired is invalidated in the servlet, we need to add autowirecapablebeanfactory to the spring framework to make @autowired work. This is a very important step .

 Packagecom.gxa.spring.day02;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.beans.factory.config.AutowireCapableBeanFactory;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.web.context.WebApplicationContext;Importorg.springframework.web.context.support.WebApplicationContextUtils, @Controller @webservlet ("/user.do") Public classUserservletextendsHttpServlet {/*** servlet and Spring Framework integration time, the servlet itself is not automatically dependent injection * Solution: * 1. The Spring framework provides the interface, Autowirecapablebeanfactory * 2. You can complete the automatic assembly of dependent objects in the servlet*/@AutowiredPrivateUserService UserService; @Override Public voidInit ()throwsservletexception {/*** Use the Init method to invoke the spring container beanfactory * see if Userservlet can get the object from the spring container*/Webapplicationcontext WC= Webapplicationcontextutils.getrequiredwebapplicationcontext (Getservletcontext ());//to get Beanfactory objects through a web containerAutowirecapablebeanfactory autowirecapablebeanfactory =wc.getautowirecapablebeanfactory (); Autowirecapablebeanfactory.autowirebean ( This); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {} @Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {userservice.getuser (); }}

6. Create a business logic layer interface and implementation class

    • Note: Since this article is a supplement to the spring integrated servlet, I do not have a sub-package for MVC. So the business layer code and the DAO layer created later are in the same package as the controller.
    • The business logic layer implements the bean ID name of the annotation to be defined in the class so that the child servlet can find the dependent bean through @autowired. Or there will be nosuchdefinitionexception.
 package   com.gxa.spring.day02;  public  interface   UserService { public  void   GetUser ();}  
 package   com.gxa.spring.day02;  import   org.springframework.beans.factory.annotation.Autowired;  import   Org.springframework.stereotype.Service; @Service ( "UserService" "  public  class  Userserviceimpl implements   UserService {@Autowir    Ed  private   Userdao Userdao; @Override  public  void   GetUser () {userdao.getuser (); }}

7. Create the DAO layer interface and its implementation class. Because I want the DAO layer to get the data in the database, we use JdbcTemplate to solve the data query.

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " >    <Context:component-scanBase-package= "Com.gxa.spring.day02"></Context:component-scan>    <Context:property-placeholder Location= "Classpath:com/gxa/spring/day02/jdbc.properties"/>        <BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">        < Propertyname= "Driverclassname"value= "${mysql.driver}"></ Property>        < Propertyname= "url"value= "${mysql.url}"></ Property>        < Propertyname= "username"value= "${mysql.username}"></ Property>        < Propertyname= "Password"value= "${mysql.password}"></ Property>    </Bean>        <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate">        < Propertyname= "DataSource"ref= "DataSource"></ Property>    </Bean>        </Beans> 
 Package com.gxa.spring.day02;  Public Interface Userdao {    publicvoid  getUser ();}
 Packagecom.gxa.spring.day02;Importjava.util.List;ImportJava.util.Map;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.jdbc.core.JdbcTemplate;Importorg.springframework.stereotype.Repository; @Repository ("Userdao") Public classUserdaoimplImplementsUserdao {@AutowiredPrivateJdbcTemplate JdbcTemplate; @Override Public voidGetUser () {String SQL= "SELECT * FROM Student"; List<Map<String,Object>> list =jdbctemplate.queryforlist (SQL);    SYSTEM.OUT.PRINTLN (list); }}

[Liu Yang Java]_spring integration servlet "Supplement" _ 14th

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.