使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)
简述:
结合Spring和Hibernate进行开发
使用@Autowired实现依赖注入, 实现一个学生注册的功能,做一个技术原型
从DAO(Repository) -> Service -> Controller
目录结构:
使用Maven做本地包管理,
pom.xml
- <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">
- <modelVersion>4.0.0</modelVersion>
- <groupId>WebProject</groupId>
- <artifactId>StudentManagementWeb</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>war</packaging>
- <name>StudentManagementWeb</name>
- <url>http://maven.apache.org</url>
- <properties>
- <org.springframework.version>3.0.2.RELEASE</org.springframework.version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <!-- Project Requirements -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.4.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-entitymanager</artifactId>
- <version>3.4.0.GA</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-envers</artifactId>
- <version>3.5.6-Final</version>
- </dependency>
- <dependency>
- <groupId>taglibs</groupId>
- <artifactId>standard</artifactId>
- <version>1.1.2</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.1.2</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.10</version>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>20030825.184428</version>
- </dependency>
- <dependency>
- <groupId>commons-pool</groupId>
- <artifactId>commons-pool</artifactId>
- <version>20030825.183949</version>
- </dependency>
- <dependency>
- <groupId>cglib</groupId>
- <artifactId>cglib</artifactId>
- <version>2.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.6.12</version>
- </dependency>
- </dependencies>
- </project>
各文件如下:
Web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <display-name>StudentManagementWeb</display-name>
- <welcome-file-list>
- <welcome-file>StudentRegistration.jsp</welcome-file>
- </welcome-file-list>
- <resource-ref>
- <description>DB Connection</description>
- <res-ref-name>jdbc/smw</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <res-auth>Container</res-auth>
- </resource-ref>
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>/WEB-INF/log4j.properties</param-value>
- </context-param>
- <!-- Define LOG4J Listener -->
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
- <servlet>
- <!-- define the name of Servlet -->
- <servlet-name>dispatcherServlet</servlet-name>
- <!-- Servlet implementation class -->
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- initialize the context -->
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <!-- load configuration -->
- <param-value>/WEB-INF/applicationContext.xml</param-value>
- </init-param>
- <!-- set loading priority -->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>dispatcherServlet</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
- </web-app>
applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- <property name="configLocation">
- <value>classpath:hibernate.cfg.xml</value>
- </property>
- </bean>
- <!-- make spring look up annotation -->
- <context:annotation-config/>
- <context:component-scan base-package="smw.*"/>
- <!-- configure the transaction management -->
- <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory">
- <ref bean="sessionFactory" />
- </property>
- </bean>
- <tx:annotation-driven transaction-manager="txManager" />
- </beans>
hibernate.cfg.xml
- <?xml version='1.0' encoding='UTF-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="connection.datasource">java:comp/env/jdbc/smw</property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="show_sql">true</property><!-- show sql statement -->
- <!-- mapping files -->
- <mapping resource="smw/model/Student.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
由于使用了Tomcat的数据源,所以还需要在Tomcat的Context.xml中添加数据库连接配置
context.xml(Tomcat server中文件,eclispe中在workspace中的server project中)
context.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- --><!-- The contents of this file will be loaded for each web application --><Context>
- <!-- Default set of monitored resources -->
- <WatchedResource>WEB-INF/web.xml</WatchedResource>
- <!-- Uncomment this to disable session persistence across Tomcat restarts -->
- <!--
- <Manager pathname="" />
- -->
- <!-- Uncomment this to enable Comet connection tacking (provides events
- on session expiration as well as webapp lifecycle) -->
- <!--
- <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
- -->
- <Resource name="jdbc/smw" auth="Container" type="javax.sql.DataSource"
- maxActive="100" maxIdle="30" maxWait="10000"
- username="root" password="sql" driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/smw"/>
- </Context>
Student.java
- package smw.model;
- public class Student {
- private int sid;
- private String name;
- private String password;
- private String college;
- public int getSid() {
- return sid;
- }
- public void setSid(int sid) {
- this.sid = sid;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getCollege() {
- return college;
- }
- public void setCollege(String college) {
- this.college = college;
- }
- }
Student.hbm.xml (学生表的映射)
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="smw.model.Student" table="tb_student" catalog="smw">
- <id name="sid" column="sid" type="int">
- <generator class="increment"/>
- </id>
- <property name="name" type="java.lang.String">
- <column name="name" not-null="true" length="20">
- <comment>student's name</comment>
- </column>
- </property>
- <property name="password" type="java.lang.String">
- <column name="password" not-null="false" length="10">
- <comment>student's password</comment>
- </column>
- </property>
- <property name="college" type="java.lang.String">
- <column name="college" not-null="false" length="20">
- <comment>student's college</comment>
- </column>
- </property>
- </class>
- </hibernate-mapping>
IStudentDAO.java
- package smw.dao;
- import smw.model.Student;
- public interface IStudentDAO {
- /**
- * Save Student into database
- * @param student
- */
- public void saveStudent(Student student);
- }
StudentDAOImpl.java
- package smw.dao.impl;
- import javax.annotation.Resource;
- import org.hibernate.SessionFactory;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.springframework.stereotype.Repository;
- import org.springframework.transaction.annotation.Transactional;
- import smw.dao.IStudentDAO;
- import smw.model.Student;
- @SuppressWarnings("restriction")
- @Repository("studentDAO")
- @Transactional
- public class StudentDAOImpl extends HibernateDaoSupport implements IStudentDAO{
- @Resource(name="sessionFactory")
- public void setSuperSessionFactory(SessionFactory sessionFactory){
- super.setSessionFactory(sessionFactory);
- }
- public void saveStudent(Student student){
- getHibernateTemplate().save(student);
- }
- }
IStudentManagementService.java
- package smw.service;
- import smw.model.Student;
- public interface IStudentManagementService {
- public void addStudent(Student student);
- }
StudentManagementServiceImpl.java
- package smw.service.impl;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import smw.dao.IStudentDAO;
- import smw.model.Student;
- import smw.service.IStudentManagementService;
- @Service
- public class StudentManagementServiceImpl implements IStudentManagementService {
- @Autowired
- private IStudentDAO studentDAO;
- @Transactional(propagation=Propagation.REQUIRED)
- public void addStudent(Student student) {
- studentDAO.saveStudent(student);
- }
- }
StudentAction.java
- package smw.action;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
- import smw.model.Student;
- import smw.service.IStudentManagementService;
- @Controller
- @RequestMapping("StudentAction.do")
- public class StudentAction extends MultiActionController{
- @Autowired
- private IStudentManagementService studentManagementService;
- @RequestMapping(params = "method=HandleStudentRegistrationFormSubmit")
- protected ModelAndView HandleStudentRegistrationFormSubmit(HttpServletRequest request
- , HttpServletResponse response) {
- Student student = new Student();
- String name = request.getParameter("name");
- String password = request.getParameter("password");
- String college = request.getParameter("college");
- student.setName(name);
- student.setPassword(password);
- student.setCollege(college);
- studentManagementService.addStudent(student);
- return new ModelAndView("StudentRegistered.jsp");
- }
- }
StudentRegistration.jsp
- <%@ page language="java" contentType="text/html; charset=GBK"
- pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>User Registration</title>
- </head>
- <body>
- <h1 align="center">Student Registration Page</h1>
- <form method="post" action="StudentAction.do?method=HandleStudentRegistrationFormSubmit" class="form">
- <table width="280" border="0" align="center">
- <tr>
- <td width="87" align="center" valign="middle" >
- <div align="right">name:</div>
- </td>
- <td width="183">
- <label>
- <input name="name" type="text" id="name" maxlength="10" />
- </label>
- <td>
- </tr>
- <tr>
- <td height="37" align="center" valign="middle">
- <div align="right">password: </div>
- </td>
- <td>
- <label>
- <input name="password" type="password" id="password" maxlength="20" />
- </label>
- </td>
- </tr>
- <tr>
- <td height="37" align="center" valign="middle">
- <div align="right">college: </div>
- </td>
- <td>
- <label>
- <input name="college" type="text" id="college" maxlength="20" />
- </label>
- </td>
- </tr>
- <tr>
- <td align="center" valign="middle">
- <input type="submit" name="Submit" value="submit" />
- </td>
- <td>
- <input name="reset" type="reset" id="reset" value="reset" />
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
StudentRegistered.jsp
- <%@ page language="java" contentType="text/html; charset=GBK"
- pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GBK">
- <title>User Registered</title>
- </head>
- <body>
- <center>
- <span class="STYLE2">Student Registered</span>
- </center>
- <br>
- <table align="center" border="1">
- <tr>
- <td height="100"><span class="STYLE2">user name:</span></td>
- <td height="100"><span class="STYLE2">${param.name }</span></td>
- </tr>
- <tr>
- <td height="100"><span class="STYLE2">password:</span></td>
- <td height="100"><span class="STYLE2">${param.password }</span></td>
- </tr>
- <tr>
- <td height="100"><span class="STYLE2">college:</span></td>
- <td height="100"><span class="STYLE2">${param.college }</span></td>
- </tr>
- <tr>
- <td height="100" colspan="2" align="center"><a href="StudentRegistration.jsp" class="STYLE2">return to registration</a></td>
- </tr>
- </table>
- </body>
- </html>
结果:
跳转后,
数据库中新增记录,
http://blog.csdn.net/anialy/article/details/8251506
使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)的更多相关文章
- 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)
package com.flong.codegenerator; import java.sql.Connection; import java.sql.DatabaseMetaData; impor ...
- SprinfJdbcTemplate+SpringMVC 代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)
代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件) 原文地址: http://jilongliang.iteye.com/blog/2262070 p ...
- 【springmvc+mybatis项目实战】杰信商贸-5.生产厂家DAO+SERVICE+CONTROLLER+JSP+配置文件
上一篇我们创建了工程和一个Factory的po对象(javaBean),我们也写好了Mapper的映射文件,接下来我们来完成生产厂家的DAO与SERVICE,以及CONTROLLER,还有做显示的JS ...
- Spring boot @Autowired注解在非Controller中注入为null
参考链接:https://blog.csdn.net/qq_35056292/article/details/78430777
- 048医疗项目-模块四:采购单模块—采购单受理(Dao,Service,Action三层)
需求: 我们之前把采购单交给监督单位审核了,审通过的采购单就要受理.供货商决定采购单发不发货. 说明: 我们要查的就是登录的供货商的要提供的采购药品,我们查看的是采购单详细表,至于查询条件我们用的是就 ...
- 047医疗项目-模块四:采购单模块—采购单审核提交(Dao,Service,Action三层)
我们之前把采购单都审核了,这篇文章说的就是审核之后提交. 其实就是改变(update)采购单的审核状态. 需求: 用户要先查看采购单的内容. 查看采购单页面:页面布局同采购单修改页面. 选择审核结果. ...
- 046医疗项目-模块四:采购单模块—采购单审核(Dao,Service,Action三层)
当医院把采购单提交之后,由监管单位进行采购单审核,由卫生院及卫生局进行审核.卫生局可以审核所有医院创建的采购单,卫生院只审核本辖区医院创建的采购单. 操作流程: 点击"采购单审核" ...
- 045医疗项目-模块四:采购单模块—采购单提交(Dao,Service,Action三层)
我们之前做的就是采购单的编辑,在采购单里面添加了药品,然后我们这篇文章要做的就是说提交这个采购单. 当我们创建完成采购单,确定采购单不再修改,需要提交采购单,由监管单位进行审核. 我们在提交这个采购单 ...
- 043医疗项目-模块四:采购单模块—采购单明细查询(Dao,Service,Action三层)
前一篇文章我们做的是在医院的角度上添加在采购单里面添加药品.这一篇文章是查看我们添加的采购单信息. 我们先看一下要实现的效果:当: 按下确认添加时,会在这里 显示出刚才添加的数据. 好,我们就来做这个 ...
随机推荐
- Delphi的类型转换 good
Delphi是一种强类型转换的语言.在VC中,赋值符用″=″,例如x=1;到了Delphi赋值符就变成了″:=″,例如x:=1. 从赋值时用符号″:=″而不用″=″,就隐约可见Delphi对类型匹配要 ...
- URL加随机数的作用
原文:URL加随机数的作用 大家在系统开发中都可能会在js中用到ajax或者dwr,因为IE的缓存,使得我们在填入相同的值的时候总是使用IE缓存,为了解决这个问题一般可以用一下方法: 1 ...
- efwplus框架
此框架得到博客园大神@张善友的关注,建议我写一篇此框架的最新介绍,好在@dotNet跨平台公众号上推荐给大家,得到大神的指示当然激动,马不停蹄的赶出此文,供大家参考! 一.使用efwplus框架的 ...
- RBAC用户角色权限设计方案
RBAC(Role-Based Access Control,基于角色的访问控制),就是用户通过角色与权限进行关联.简单地说,一个用户拥有若干角色,每一个角色拥有若干权限.这样,就构造成“用 户-角色 ...
- gant
http://gant.github.io/ http://gant.codehaus.org/
- POJ2112_Optimal Milking(网洛流最大流Dinic+最短路Flody+二分)
解题报告 农场有k个挤奶机和c头牛,每头牛到每一台挤奶机距离不一样,每台挤奶机每天最多挤m头牛的奶. 寻找一个方案,安排每头牛到某一挤奶机挤奶,使得c头牛须要走的全部路程中的最大路程的最小值. 要使每 ...
- Android架构设计和软硬整合完整训练
Android架构设计和软硬整合完整训练 Android架构设计和软硬整合完整训练:HAL&Framework&Native Service&Android Service&a ...
- Embedded Linux Primer----嵌入式Linux基础教程--前言
APractical,Real-WorldApproach ChristopherHallinan 计算机无处不在. 事实上,当然了,对于那些大约在过去25年期间没有生活在洞穴中的人来说没有什么惊奇的 ...
- margin 等高布局
<div id="main"> <div id="left"> 我是左边的内容的啦啦啦啦... .<br> 我是左边的内容的 ...
- linux下查看日志基本命令
1.cat命令: 功能:1)显示整个文件. 演示样例: $ cat fileName 2)把文件串连接后传到基本输出,如将几个文件合并为一个文件或输出到屏幕. 演示样例: $ cat file1 fi ...