使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)

 

简述:

结合Spring和Hibernate进行开发

使用@Autowired实现依赖注入, 实现一个学生注册的功能,做一个技术原型

从DAO(Repository) -> Service -> Controller

 

目录结构:

使用Maven做本地包管理,

pom.xml

 

[java]  view plaincopy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  2.   <modelVersion>4.0.0</modelVersion>  
  3.   <groupId>WebProject</groupId>  
  4.   <artifactId>StudentManagementWeb</artifactId>  
  5.   <version>0.0.1-SNAPSHOT</version>  
  6.   <packaging>war</packaging>  
  7.     
  8.    <name>StudentManagementWeb</name>  
  9.   <url>http://maven.apache.org</url>  
  10.   
  11.   <properties>  
  12.       <org.springframework.version>3.0.2.RELEASE</org.springframework.version>  
  13.       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  14.   </properties>  
  15.   
  16.   
  17.   <dependencies>  
  18.     <dependency>  
  19.         <groupId>junit</groupId>  
  20.         <artifactId>junit</artifactId>  
  21.         <version>3.8.1</version>  
  22.         <scope>test</scope>  
  23.     </dependency>  
  24.     <!-- Project Requirements -->  
  25.     <dependency>  
  26.         <groupId>javax.servlet</groupId>  
  27.         <artifactId>servlet-api</artifactId>  
  28.         <version>2.5</version>  
  29.     </dependency>  
  30.     <dependency>  
  31.         <groupId>org.slf4j</groupId>  
  32.         <artifactId>slf4j-log4j12</artifactId>  
  33.         <version>1.4.2</version>  
  34.         </dependency>  
  35.     <dependency>  
  36.         <groupId>org.springframework</groupId>  
  37.         <artifactId>spring-beans</artifactId>  
  38.         <version>${org.springframework.version}</version>  
  39.     </dependency>  
  40.     <dependency>  
  41.         <groupId>org.springframework</groupId>  
  42.         <artifactId>spring-jdbc</artifactId>  
  43.         <version>${org.springframework.version}</version>  
  44.         </dependency>  
  45.     <dependency>  
  46.         <groupId>org.springframework</groupId>  
  47.         <artifactId>spring-web</artifactId>  
  48.         <version>${org.springframework.version}</version>  
  49.     </dependency>  
  50.     <dependency>  
  51.         <groupId>org.springframework</groupId>  
  52.         <artifactId>spring-webmvc</artifactId>  
  53.         <version>${org.springframework.version}</version>  
  54.     </dependency>  
  55.     <dependency>  
  56.         <groupId>org.springframework</groupId>  
  57.         <artifactId>spring-orm</artifactId>  
  58.         <version>${org.springframework.version}</version>  
  59.     </dependency>  
  60.     <dependency>  
  61.         <groupId>org.hibernate</groupId>  
  62.         <artifactId>hibernate-entitymanager</artifactId>  
  63.         <version>3.4.0.GA</version>  
  64.     </dependency>  
  65.     <dependency>  
  66.         <groupId>org.hibernate</groupId>  
  67.         <artifactId>hibernate-envers</artifactId>  
  68.         <version>3.5.6-Final</version>  
  69.     </dependency>  
  70.     <dependency>  
  71.         <groupId>taglibs</groupId>  
  72.         <artifactId>standard</artifactId>  
  73.         <version>1.1.2</version>  
  74.     </dependency>  
  75.     <dependency>  
  76.         <groupId>javax.servlet</groupId>  
  77.         <artifactId>jstl</artifactId>  
  78.         <version>1.1.2</version>  
  79.     </dependency>  
  80.     <dependency>  
  81.         <groupId>mysql</groupId>  
  82.         <artifactId>mysql-connector-java</artifactId>  
  83.         <version>5.1.10</version>  
  84.     </dependency>  
  85.     <dependency>  
  86.         <groupId>commons-dbcp</groupId>  
  87.         <artifactId>commons-dbcp</artifactId>  
  88.         <version>20030825.184428</version>  
  89.     </dependency>  
  90.     <dependency>  
  91.         <groupId>commons-pool</groupId>  
  92.         <artifactId>commons-pool</artifactId>  
  93.         <version>20030825.183949</version>  
  94.     </dependency>  
  95.     <dependency>  
  96.         <groupId>cglib</groupId>  
  97.         <artifactId>cglib</artifactId>  
  98.         <version>2.2.2</version>  
  99.     </dependency>  
  100.     <dependency>  
  101.         <groupId>org.aspectj</groupId>  
  102.         <artifactId>aspectjweaver</artifactId>  
  103.         <version>1.6.12</version>  
  104.     </dependency>  
  105.   </dependencies>    
  106. </project>  



 

各文件如下:

Web.xml

 

[java]  view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>StudentManagementWeb</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>StudentRegistration.jsp</welcome-file>  
  6.   </welcome-file-list>  
  7.     
  8.   <resource-ref>  
  9.     <description>DB Connection</description>  
  10.     <res-ref-name>jdbc/smw</res-ref-name>  
  11.     <res-type>javax.sql.DataSource</res-type>  
  12.     <res-auth>Container</res-auth>  
  13.   </resource-ref>  
  14.     
  15.   <context-param>   
  16.     <param-name>log4jConfigLocation</param-name>   
  17.     <param-value>/WEB-INF/log4j.properties</param-value>   
  18.   </context-param>   
  19.     
  20.   <!-- Define LOG4J Listener -->   
  21.   <listener>   
  22.    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
  23.   </listener>   
  24.     
  25.   <servlet>  
  26.   <!-- define the name of Servlet -->  
  27.   <servlet-name>dispatcherServlet</servlet-name>  
  28.   <!-- Servlet implementation class -->  
  29.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  30.   <!-- initialize the context -->  
  31.   <init-param>  
  32.   <param-name>contextConfigLocation</param-name>  
  33.   <!-- load configuration -->  
  34.   <param-value>/WEB-INF/applicationContext.xml</param-value>  
  35.   </init-param>  
  36.   <!-- set loading priority -->  
  37.   <load-on-startup>1</load-on-startup>  
  38.   </servlet>  
  39.   <servlet-mapping>  
  40.   <servlet-name>dispatcherServlet</servlet-name>  
  41.   <url-pattern>*.do</url-pattern>  
  42.   </servlet-mapping>  
  43.     
  44. </web-app>  


applicationContext.xml

 

 

[html]  view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"       
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        
  4.        xmlns:context="http://www.springframework.org/schema/context"       
  5.        xmlns:aop="http://www.springframework.org/schema/aop"       
  6.        xmlns:tx="http://www.springframework.org/schema/tx"       
  7.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  8.        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd               
  9.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  10.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd               
  11.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  12.   
  13.       
  14.      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
  15.       
  16.      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  17.         <property name="configLocation">  
  18.             <value>classpath:hibernate.cfg.xml</value>  
  19.         </property>  
  20.     </bean>  
  21.        
  22.      <!-- make spring look up annotation -->  
  23.      <context:annotation-config/>  
  24.       
  25.      <context:component-scan base-package="smw.*"/>  
  26.        
  27.      <!-- configure the transaction management -->  
  28.      <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">           
  29.         <property name="sessionFactory">               
  30.             <ref bean="sessionFactory" />           
  31.         </property>       
  32.      </bean>  
  33.        
  34.      <tx:annotation-driven transaction-manager="txManager" />  
  35.   
  36. </beans>  

 

 

hibernate.cfg.xml

 

[java]  view plaincopy
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.         <property name="connection.datasource">java:comp/env/jdbc/smw</property>  
  10.         <property name="dialect">  
  11.             org.hibernate.dialect.MySQLDialect  
  12.         </property>  
  13.         <property name="show_sql">true</property><!-- show sql statement -->  
  14.         <!-- mapping files -->  
  15.         <mapping resource="smw/model/Student.hbm.xml"/>  
  16.     </session-factory>  
  17.   
  18. </hibernate-configuration>  

由于使用了Tomcat的数据源,所以还需要在Tomcat的Context.xml中添加数据库连接配置

 

context.xml(Tomcat server中文件,eclispe中在workspace中的server project中)

context.xml

 

[html]  view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!--  
  3.   Licensed to the Apache Software Foundation (ASF) under one or more  
  4.   contributor license agreements.  See the NOTICE file distributed with  
  5.   this work for additional information regarding copyright ownership.  
  6.   The ASF licenses this file to You under the Apache License, Version 2.0  
  7.   (the "License"); you may not use this file except in compliance with  
  8.   the License.  You may obtain a copy of the License at  
  9.   
  10.       http://www.apache.org/licenses/LICENSE-2.0  
  11.   
  12.   Unless required by applicable law or agreed to in writing, software  
  13.   distributed under the License is distributed on an "AS IS" BASIS,  
  14.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  15.   See the License for the specific language governing permissions and  
  16.   limitations under the License.  
  17. --><!-- The contents of this file will be loaded for each web application --><Context>  
  18.   
  19.     <!-- Default set of monitored resources -->  
  20.     <WatchedResource>WEB-INF/web.xml</WatchedResource>  
  21.       
  22.     <!-- Uncomment this to disable session persistence across Tomcat restarts -->  
  23.     <!-- 
  24.     <Manager pathname="" /> 
  25.     -->  
  26.   
  27.     <!-- Uncomment this to enable Comet connection tacking (provides events  
  28.          on session expiration as well as webapp lifecycle) -->  
  29.     <!-- 
  30.     <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> 
  31.     -->  
  32.     <Resource name="jdbc/smw" auth="Container" type="javax.sql.DataSource"  
  33.         maxActive="100" maxIdle="30" maxWait="10000"  
  34.         username="root" password="sql" driverClassName="com.mysql.jdbc.Driver"  
  35.         url="jdbc:mysql://localhost:3306/smw"/>  
  36.   
  37. </Context>  

 

 

Student.java

 

[java]  view plaincopy
  1. package smw.model;  
  2.   
  3.   
  4. public class Student {  
  5.     private int sid;  
  6.     private String name;  
  7.     private String password;  
  8.     private String college;  
  9.     public int getSid() {  
  10.         return sid;  
  11.     }  
  12.     public void setSid(int sid) {  
  13.         this.sid = sid;  
  14.     }  
  15.     public String getName() {  
  16.         return name;  
  17.     }  
  18.     public void setName(String name) {  
  19.         this.name = name;  
  20.     }  
  21.     public String getPassword() {  
  22.         return password;  
  23.     }  
  24.     public void setPassword(String password) {  
  25.         this.password = password;  
  26.     }  
  27.     public String getCollege() {  
  28.         return college;  
  29.     }  
  30.     public void setCollege(String college) {  
  31.         this.college = college;  
  32.     }  
  33. }  


Student.hbm.xml (学生表的映射)

 

 

[java]  view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="smw.model.Student" table="tb_student" catalog="smw">  
  6.         <id name="sid" column="sid" type="int">  
  7.             <generator class="increment"/>  
  8.         </id>  
  9.         <property name="name" type="java.lang.String">  
  10.             <column name="name"  not-null="true" length="20">  
  11.                 <comment>student's name</comment>  
  12.             </column>  
  13.         </property>  
  14.         <property name="password" type="java.lang.String">  
  15.             <column name="password"  not-null="false" length="10">  
  16.                 <comment>student's password</comment>  
  17.             </column>  
  18.         </property>  
  19.         <property name="college" type="java.lang.String">  
  20.             <column name="college"  not-null="false" length="20">  
  21.                 <comment>student's college</comment>  
  22.             </column>  
  23.         </property>  
  24.     </class>  
  25. </hibernate-mapping>  

 

 

IStudentDAO.java 

 

[java]  view plaincopy
  1. package smw.dao;  
  2.   
  3. import smw.model.Student;  
  4.   
  5. public interface IStudentDAO {  
  6.     /** 
  7.      * Save Student into database 
  8.      * @param student 
  9.      */  
  10.     public void saveStudent(Student student);  
  11.       
  12. }  

 

 

StudentDAOImpl.java

 

[java]  view plaincopy
  1. package smw.dao.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  7. import org.springframework.stereotype.Repository;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import smw.dao.IStudentDAO;  
  11. import smw.model.Student;  
  12.   
  13. @SuppressWarnings("restriction")  
  14. @Repository("studentDAO")  
  15. @Transactional  
  16. public class StudentDAOImpl extends HibernateDaoSupport implements IStudentDAO{  
  17.       
  18.     @Resource(name="sessionFactory")  
  19.      public void setSuperSessionFactory(SessionFactory sessionFactory){       
  20.         super.setSessionFactory(sessionFactory);  
  21.     }  
  22.   
  23.     public void saveStudent(Student student){  
  24.         getHibernateTemplate().save(student);  
  25.     }  
  26.   
  27. }  


IStudentManagementService.java

 

 

[java]  view plaincopy
  1. package smw.service;  
  2.   
  3. import smw.model.Student;  
  4.   
  5. public interface IStudentManagementService {  
  6.     public void addStudent(Student student);  
  7. }  

 

 

StudentManagementServiceImpl.java

 

[java]  view plaincopy
  1. package smw.service.impl;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5. import org.springframework.transaction.annotation.Propagation;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8. import smw.dao.IStudentDAO;  
  9. import smw.model.Student;  
  10. import smw.service.IStudentManagementService;  
  11.   
  12. @Service  
  13. public class StudentManagementServiceImpl implements IStudentManagementService {  
  14.     @Autowired  
  15.     private IStudentDAO studentDAO;  
  16.       
  17.     @Transactional(propagation=Propagation.REQUIRED)  
  18.     public void addStudent(Student student) {  
  19.         studentDAO.saveStudent(student);  
  20.     }  
  21. }  

 

 

StudentAction.java

 

[java]  view plaincopy
  1. package smw.action;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.servlet.ModelAndView;  
  9. import org.springframework.web.servlet.mvc.multiaction.MultiActionController;  
  10.   
  11. import smw.model.Student;  
  12. import smw.service.IStudentManagementService;  
  13.   
  14. @Controller  
  15. @RequestMapping("StudentAction.do")  
  16. public class StudentAction extends MultiActionController{  
  17.     @Autowired  
  18.     private IStudentManagementService studentManagementService;  
  19.       
  20.     @RequestMapping(params = "method=HandleStudentRegistrationFormSubmit")  
  21.     protected ModelAndView HandleStudentRegistrationFormSubmit(HttpServletRequest request  
  22.             , HttpServletResponse response) {     
  23.         Student student = new Student();  
  24.         String name = request.getParameter("name");  
  25.         String password = request.getParameter("password");  
  26.         String college = request.getParameter("college");  
  27.           
  28.         student.setName(name);  
  29.         student.setPassword(password);  
  30.         student.setCollege(college);  
  31.   
  32.         studentManagementService.addStudent(student);  
  33.         return new ModelAndView("StudentRegistered.jsp");  
  34.     }  
  35. }  

StudentRegistration.jsp

 

 

[java]  view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=GBK"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  7. <title>User Registration</title>  
  8. </head>  
  9. <body>  
  10.     <h1 align="center">Student Registration Page</h1>  
  11.     <form method="post" action="StudentAction.do?method=HandleStudentRegistrationFormSubmit" class="form">  
  12.         <table width="280" border="0" align="center">  
  13.             <tr>  
  14.                 <td width="87" align="center" valign="middle" >  
  15.                         <div align="right">name:</div>  
  16.                 </td>  
  17.                 <td width="183">  
  18.                   <label>  
  19.                     <input name="name" type="text" id="name" maxlength="10" />  
  20.                   </label>  
  21.                 <td>  
  22.             </tr>  
  23.             <tr>  
  24.                 <td height="37" align="center" valign="middle">  
  25.                   <div align="right">password: </div>  
  26.                 </td>  
  27.                 <td>  
  28.                     <label>   
  29.                         <input name="password" type="password" id="password" maxlength="20" />   
  30.                     </label>  
  31.                 </td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td height="37" align="center" valign="middle">  
  35.                   <div align="right">college: </div>  
  36.                 </td>  
  37.                 <td>  
  38.                     <label>   
  39.                         <input name="college" type="text" id="college" maxlength="20" />   
  40.                     </label>  
  41.                 </td>  
  42.             </tr>  
  43.             <tr>  
  44.                 <td align="center" valign="middle">  
  45.                     <input type="submit" name="Submit" value="submit" />  
  46.                 </td>  
  47.                 <td>   
  48.                     <input name="reset" type="reset" id="reset" value="reset" />  
  49.                 </td>  
  50.             </tr>  
  51.         </table>  
  52.     </form>  
  53. </body>  
  54. </html>  

StudentRegistered.jsp

 

 

[html]  view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=GBK"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=GBK">  
  7. <title>User Registered</title>  
  8. </head>  
  9.   <body>  
  10.     <center>  
  11.       <span class="STYLE2">Student Registered</span>  
  12.     </center>  
  13.     <br>  
  14.     <table align="center" border="1">  
  15.         <tr>  
  16.             <td height="100"><span class="STYLE2">user name:</span></td>  
  17.             <td height="100"><span class="STYLE2">${param.name }</span></td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td height="100"><span class="STYLE2">password:</span></td>  
  21.             <td height="100"><span class="STYLE2">${param.password }</span></td>  
  22.         </tr>  
  23.                 <tr>  
  24.             <td height="100"><span class="STYLE2">college:</span></td>  
  25.             <td height="100"><span class="STYLE2">${param.college }</span></td>  
  26.         </tr>  
  27.         <tr>  
  28.             <td height="100" colspan="2" align="center"><href="StudentRegistration.jsp" class="STYLE2">return to registration</a></td>  
  29.         </tr>  
  30.   </table>  
  31.   </body>  
  32. </html>  


结果:

 

 

 

跳转后,

数据库中新增记录,

 

http://blog.csdn.net/anialy/article/details/8251506

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值