简述:

结合Spring和Hibernate进行开发

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

从DAO(Repository) -> Service -> Controller

目录结构:

使用Maven做本地包管理,

pom.xml

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

各文件如下:

Web.xml

  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. <resource-ref>
  8. <description>DB Connection</description>
  9. <res-ref-name>jdbc/smw</res-ref-name>
  10. <res-type>javax.sql.DataSource</res-type>
  11. <res-auth>Container</res-auth>
  12. </resource-ref>
  13. <context-param>
  14. <param-name>log4jConfigLocation</param-name>
  15. <param-value>/WEB-INF/log4j.properties</param-value>
  16. </context-param>
  17. <!-- Define LOG4J Listener -->
  18. <listener>
  19. <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  20. </listener>
  21. <servlet>
  22. <!-- define the name of Servlet -->
  23. <servlet-name>dispatcherServlet</servlet-name>
  24. <!-- Servlet implementation class -->
  25. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  26. <!-- initialize the context -->
  27. <init-param>
  28. <param-name>contextConfigLocation</param-name>
  29. <!-- load configuration -->
  30. <param-value>/WEB-INF/applicationContext.xml</param-value>
  31. </init-param>
  32. <!-- set loading priority -->
  33. <load-on-startup>1</load-on-startup>
  34. </servlet>
  35. <servlet-mapping>
  36. <servlet-name>dispatcherServlet</servlet-name>
  37. <url-pattern>*.do</url-pattern>
  38. </servlet-mapping>
  39. </web-app>

applicationContext.xml

  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. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
  13. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  14. <property name="configLocation">
  15. <value>classpath:hibernate.cfg.xml</value>
  16. </property>
  17. </bean>
  18. <!-- make spring look up annotation -->
  19. <context:annotation-config/>
  20. <context:component-scan base-package="smw.*"/>
  21. <!-- configure the transaction management -->
  22. <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  23. <property name="sessionFactory">
  24. <ref bean="sessionFactory" />
  25. </property>
  26. </bean>
  27. <tx:annotation-driven transaction-manager="txManager" />
  28. </beans>

hibernate.cfg.xml

  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. <hibernate-configuration>
  6. <session-factory>
  7. <property name="connection.datasource">java:comp/env/jdbc/smw</property>
  8. <property name="dialect">
  9. org.hibernate.dialect.MySQLDialect
  10. </property>
  11. <property name="show_sql">true</property><!-- show sql statement -->
  12. <!-- mapping files -->
  13. <mapping resource="smw/model/Student.hbm.xml"/>
  14. </session-factory>
  15. </hibernate-configuration>

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

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

context.xml

  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. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. --><!-- The contents of this file will be loaded for each web application --><Context>
  16. <!-- Default set of monitored resources -->
  17. <WatchedResource>WEB-INF/web.xml</WatchedResource>
  18. <!-- Uncomment this to disable session persistence across Tomcat restarts -->
  19. <!--
  20. <Manager pathname="" />
  21. -->
  22. <!-- Uncomment this to enable Comet connection tacking (provides events
  23. on session expiration as well as webapp lifecycle) -->
  24. <!--
  25. <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
  26. -->
  27. <Resource name="jdbc/smw" auth="Container" type="javax.sql.DataSource"
  28. maxActive="100" maxIdle="30" maxWait="10000"
  29. username="root" password="sql" driverClassName="com.mysql.jdbc.Driver"
  30. url="jdbc:mysql://localhost:3306/smw"/>
  31. </Context>

Student.java

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

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

  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 

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

StudentDAOImpl.java

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

IStudentManagementService.java

  1. package smw.service;
  2. import smw.model.Student;
  3. public interface IStudentManagementService {
  4. public void addStudent(Student student);
  5. }

StudentManagementServiceImpl.java

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

StudentAction.java

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

StudentRegistration.jsp

  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

  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"><a 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

使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)的更多相关文章

  1. 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)

    package com.flong.codegenerator; import java.sql.Connection; import java.sql.DatabaseMetaData; impor ...

  2. SprinfJdbcTemplate+SpringMVC 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)

    代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件) 原文地址: http://jilongliang.iteye.com/blog/2262070 p ...

  3. 【springmvc+mybatis项目实战】杰信商贸-5.生产厂家DAO+SERVICE+CONTROLLER+JSP+配置文件

    上一篇我们创建了工程和一个Factory的po对象(javaBean),我们也写好了Mapper的映射文件,接下来我们来完成生产厂家的DAO与SERVICE,以及CONTROLLER,还有做显示的JS ...

  4. Spring boot @Autowired注解在非Controller中注入为null

    参考链接:https://blog.csdn.net/qq_35056292/article/details/78430777

  5. 048医疗项目-模块四:采购单模块—采购单受理(Dao,Service,Action三层)

    需求: 我们之前把采购单交给监督单位审核了,审通过的采购单就要受理.供货商决定采购单发不发货. 说明: 我们要查的就是登录的供货商的要提供的采购药品,我们查看的是采购单详细表,至于查询条件我们用的是就 ...

  6. 047医疗项目-模块四:采购单模块—采购单审核提交(Dao,Service,Action三层)

    我们之前把采购单都审核了,这篇文章说的就是审核之后提交. 其实就是改变(update)采购单的审核状态. 需求: 用户要先查看采购单的内容. 查看采购单页面:页面布局同采购单修改页面. 选择审核结果. ...

  7. 046医疗项目-模块四:采购单模块—采购单审核(Dao,Service,Action三层)

    当医院把采购单提交之后,由监管单位进行采购单审核,由卫生院及卫生局进行审核.卫生局可以审核所有医院创建的采购单,卫生院只审核本辖区医院创建的采购单. 操作流程: 点击"采购单审核" ...

  8. 045医疗项目-模块四:采购单模块—采购单提交(Dao,Service,Action三层)

    我们之前做的就是采购单的编辑,在采购单里面添加了药品,然后我们这篇文章要做的就是说提交这个采购单. 当我们创建完成采购单,确定采购单不再修改,需要提交采购单,由监管单位进行审核. 我们在提交这个采购单 ...

  9. 043医疗项目-模块四:采购单模块—采购单明细查询(Dao,Service,Action三层)

    前一篇文章我们做的是在医院的角度上添加在采购单里面添加药品.这一篇文章是查看我们添加的采购单信息. 我们先看一下要实现的效果:当: 按下确认添加时,会在这里 显示出刚才添加的数据. 好,我们就来做这个 ...

随机推荐

  1. Delphi的类型转换 good

    Delphi是一种强类型转换的语言.在VC中,赋值符用″=″,例如x=1;到了Delphi赋值符就变成了″:=″,例如x:=1. 从赋值时用符号″:=″而不用″=″,就隐约可见Delphi对类型匹配要 ...

  2. URL加随机数的作用

    原文:URL加随机数的作用 大家在系统开发中都可能会在js中用到ajax或者dwr,因为IE的缓存,使得我们在填入相同的值的时候总是使用IE缓存,为了解决这个问题一般可以用一下方法:        1 ...

  3. efwplus框架

    此框架得到博客园大神@张善友的关注,建议我写一篇此框架的最新介绍,好在@dotNet跨平台公众号上推荐给大家,得到大神的指示当然激动,马不停蹄的赶出此文,供大家参考!   一.使用efwplus框架的 ...

  4. RBAC用户角色权限设计方案

    RBAC(Role-Based Access Control,基于角色的访问控制),就是用户通过角色与权限进行关联.简单地说,一个用户拥有若干角色,每一个角色拥有若干权限.这样,就构造成“用 户-角色 ...

  5. gant

    http://gant.github.io/ http://gant.codehaus.org/

  6. POJ2112_Optimal Milking(网洛流最大流Dinic+最短路Flody+二分)

    解题报告 农场有k个挤奶机和c头牛,每头牛到每一台挤奶机距离不一样,每台挤奶机每天最多挤m头牛的奶. 寻找一个方案,安排每头牛到某一挤奶机挤奶,使得c头牛须要走的全部路程中的最大路程的最小值. 要使每 ...

  7. Android架构设计和软硬整合完整训练

    Android架构设计和软硬整合完整训练 Android架构设计和软硬整合完整训练:HAL&Framework&Native Service&Android Service&a ...

  8. Embedded Linux Primer----嵌入式Linux基础教程--前言

    APractical,Real-WorldApproach ChristopherHallinan 计算机无处不在. 事实上,当然了,对于那些大约在过去25年期间没有生活在洞穴中的人来说没有什么惊奇的 ...

  9. margin 等高布局

    <div id="main"> <div id="left"> 我是左边的内容的啦啦啦啦... .<br> 我是左边的内容的 ...

  10. linux下查看日志基本命令

    1.cat命令: 功能:1)显示整个文件. 演示样例: $ cat fileName 2)把文件串连接后传到基本输出,如将几个文件合并为一个文件或输出到屏幕. 演示样例: $ cat file1 fi ...