Strusts2+Spring+Hibernate虽然是主流的WEB开发框架,但是SpringMVC有越来越多的人使用了,确实也非常好用,用得爽!
这里实现了一个SpringMVC+Spring+Hibernate的小例子。注释都在代码里面。
项目各包的结构如下图:
1, 首先是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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.miquan</groupId> <artifactId>springmvc_spring_hibernate</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springmvc_spring_hibernate Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- expectj --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.0.4.RELEASE</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.ws</groupId> <artifactId>spring-ws-core</artifactId> <version>2.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.1.1.RELEASE</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.6.Final</version> </dependency> <!-- dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> </dependencies> <build> <finalName>springmvc_spring_hibernate</finalName> </build> </project>
2, web.xml配置好SpringMVC和Spring
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- Spring配置。(必须配,要不会找不到bean) --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring mvc (系统在启动的时候会根据springmvc-servlet中的配置找到所有的controller并初始化)--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern><!-- 这里不能加* --> </servlet-mapping> </web-app>
3, SpringMVC的配置——springmvc-servlet.xml(注意命名,对应servlet中的springmvc)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" > <!-- 存在controller的包。注意这里写的是包名,不是类名 --> <context:component-scan base-package="com.miquan.controller"/> <mvc:annotation-driven /> <!-- 静态文件 --> <mvc:resources location="/res/" mapping="/res/**"></mvc:resources> <!-- 跳转文件的前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
4, spring的配置——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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自动扫面注解包 --> <context:annotation-config /> <context:component-scan base-package="com.miquan.*" /> <!-- 数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssh" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.miquan.model" /><!-- 实体类的包 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <!-- 会自动创表,但是不会自动创建数据库,所以要先创建数据库。 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <!-- 用于注入到GeneralDao中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 开启事务管理注解 --> <aop:aspectj-autoproxy /> <tx:annotation-driven /> </beans>
5, 实体类。
package com.miquan.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class User { private int id; private String username; private String password; public User() { super(); } public User(int id, String username, String password) { super(); this.id = id; this.username = username; this.password = password; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
6, controller层。
package com.miquan.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.miquan.model.User; import com.miquan.service.IUserService; @Controller @RequestMapping(value="/user") public class UserController { /** * 注入userService。 * 如果userService继承了某个接口, * 这里类型必须是接口IUserService, * 不能是类UserService,不知道为什么。 */ @Autowired private IUserService userService; @RequestMapping(value="/registe", method=RequestMethod.GET) public String registe() { User user = new User(0, "梁国俏", "999"); userService.registe(user); return "index"; } }
7, service层。
package com.miquan.service; import com.miquan.model.User; public interface IUserService { public boolean registe(User user); }
package com.miquan.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.miquan.dao.IGeneralDao; import com.miquan.model.User; @Service public class UserService implements IUserService { @Autowired private IGeneralDao generalDao; /* * 这里要有事务注解,默认readOnly=true,不设置的话会报错。 * insert和update操作都要。 */ @Transactional(readOnly=false) public boolean registe(User user) { generalDao.save(user); return false; } }
8, dao层。
package com.miquan.dao; import java.io.Serializable; import java.util.List; public interface IGeneralDao { public <T> T findById(Class<T> type, Serializable id); public <T> List<T> findAll(Class<T> type); public void save(Object... entities); public void update(Object... entities); public void saveOrUpdate(Object entity); public void delete(Object... entities); public void deleteById(Class<?> type, Serializable id); public void refresh(Object... entities); public void flush(); }
package com.miquan.dao; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.stereotype.Repository; /** * 这个类将dao成封装成了一个操作类,从网上复制过来的。 */ @Repository public class GeneralDao implements IGeneralDao { /** * 这个bean里面需要注入sessionFactory,所以把这个bean写在了配置中。 */ @Autowired private HibernateTemplate hibernateTemplate; public <T> T findById(Class<T> type, Serializable id) { return hibernateTemplate.get(type, id); } public <T> List<T> findAll(Class<T> type) { return hibernateTemplate.loadAll(type); } public void save(Object... entities) { for (Object entity : entities) { hibernateTemplate.save(entity); } } public void saveOrUpdate(Object entity) { hibernateTemplate.saveOrUpdate(entity); } public void update(Object... entities) { for (Object entity : entities) { hibernateTemplate.update(entity); } } public void delete(Object... entities) { for (Object entity : entities) { if (entity != null) { hibernateTemplate.delete(entity); } } } public void deleteById(Class<?> type, Serializable id) { if (id == null) { return; } Object entity = findById(type, id); if (entity == null) { return; } delete(entity); } public void refresh(Object... entities) { for (Object entity : entities) { hibernateTemplate.refresh(entity); } } public void flush() { hibernateTemplate.flush(); } }
9, 测试。
package com.miquan.service; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.miquan.controller.UserController; public class UserServiceTest { @Test public void test() { ApplicationContext ctx = new FileSystemXmlApplicationContext( "src/main/webapp/WEB-INF/applicationContext.xml"); UserController controller = ctx.getBean(UserController.class); controller.registe(); } }
或者部署在tomcat上,在浏览器访问http://localhost:8080/xx项目/user/registe。
时间: 2024-10-12 20:35:41