spring(springmvc,springboot)-hibernate(jpa,mybtis)-jsp整合
spring5整合hibernate5与JSP
说到整合Spring和Hibernate首先要搞清楚,整合什么?
1、使用Spring的IOC容器来生产Hibernate的SessionFactory对象实例
2、让Hibernate使用Spring的声明式事务
整合步骤:
1、先加入Hibernate
2、在加入Spring,整合
构建maven web项目,如下图示
项目爆红,处理办法如下图:IDEA没这个问题。
1.导包
1.server的包
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope> <!--不能为默认的,--></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.2</version></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-spec</artifactId><version>1.2.5</version><!--不要这个bundle项--></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-impl</artifactId><version>1.2.5</version><!--不要这个bundle项--></dependency>
2.hibernate的包
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.2.17.Final</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-c3p0</artifactId><version>5.3.0.Final</version></dependency>
3.mysql驱动包
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency>
4.日志包
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-nop</artifactId><version>1.7.35</version><scope>test</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging-api</artifactId><version>1.1</version></dependency>
5.spring包
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.6.RELEASE</version></dependency>
2.spring配置文件:applicationContext.xml,web.xml配置web服务器启动时,初始化IOC容器,放到全局域(ServletContext)中
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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- 注解:配bean所需要扫描的地方 --><context:component-scan base-package="cn.ybzy.shweb"></context:component-scan><!-- 数据源配置 --><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="jdbcUrl" value="${jdbc.url}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property><property name="acquireIncrement" value="${jbc.acquireIncrement}"></property><property name="minPoolSize" value="${jdbc.minPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property><property name="maxStatements" value="${jdbc.maxStatements}"></property><property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}"></property></bean><!-- 整合hibernate,配sessionFactory的bean --><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!--<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>--><!-- 如下用这个配置,hibernate.cfg.xml都可以不要了--><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><property name="mappingLocations" value="classpath:cn/ybzy/shweb/model/*.hbm.xml"></property></bean><!-- 配置声明式事务 ,前面讲的是spring事务,这里我们要配hibernate事务--><!-- 事务管理 --><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property> <!-- sessionFactory bean中已配数据源了 --></bean><!-- 事务属性,get,find,select,load等开头的方法这种查询的方法都是只读 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="get*" read-only="true"/><tx:method name="find*" read-only="true"/><tx:method name="load*" read-only="true"/><tx:method name="select*" read-only="true"/></tx:attributes></tx:advice><!-- 切入点的配置 --><aop:config><aop:pointcut expression="execution(* cn.ybzy.shweb.service.*.*(..))" id="txPointcut"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/></aop:config>
</beans>
hibernate.cfg.xml----该文件可以不要,都可以在applicationContext.xml中配置
<hibernate-configuration><session-factory><!-- 数据库连接信息模块-可交由spring --><!-- 数据库连接池模块 -可交由spring--><!-- hibernate自身配置模块 --><property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><property name="hibernate.show_sql">true</property><property name="hibernate.format_sql">true</property><property name="hibernate.hbm2ddl.auto">update</property><!-- 缓存模块 --><!-- 引入映射配置文件-可交由spring --></session-factory>
</hibernate-configuration>
initSpringIocListener.java----web层,监听器,启动web服务器时,同时初始化spring IOC
public class initSpringIocListener implements ServletContextListener{public initSpringIocListener() {}/*** web应用服务器启动的时候执行的方法,初始化spring IOC容器*/public void contextInitialized(ServletContextEvent event) {ServletContext context =event.getServletContext();String cfglocation = context.getInitParameter("configLocation");ApplicationContext ct =new FileSystemXmlApplicationContext(cfglocation);context.setAttribute("applicationContext",ct); //ioc容器放在全局域空间中了,在整个web任何地方都可访问之}public void contextDestroyed(ServletContextEvent event) {}}
web.xml----配置监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><!-- spring的配置文件的位置 --><context-param><param-name>configLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!-- spring IOC容器在web启动时与服务启动一起初始化,不同于以前讲jar工程中的测试类获取容器 --><listener><listener-class>cn.ybzy.shweb.web.initSpringIocListener</listener-class></listener>
</web-app>
3.模型层User.java
public class User {private int id;private String username;private double balance; //余额//get,set,toString(),无参构造方法
}
4.dao,service,sessionFactory由spring容器创建
-----------------------------------------------------UserDao-------------------------------------------------
public interface UserDao {public List<User> getAll();}
-----------------------------------------------UserDaoImpl-----------------------------------------------------------------
@Repository("userDao")
public class UserDaoImpl implements UserDao{@Autowiredprivate SessionFactory sessionFactory;@Overridepublic List<User> getAll() {String hql= "from User";Session session=sessionFactory.getCurrentSession();Query<User> query=session.createQuery(hql);return query.list();}}----------------------------------------------UserService------------------------------------------------------------------
public interface UserService {public List<User> getAll();}----------------------------------------------UserServiceImpl-------------------------------------------------------------
@Service("userService")
public class UserServiceImpl implements UserService{@Autowiredprivate UserDao userDao; //自动装配,因为在Dao层实现类中用了@Repository("userDao"),创建了对象@Overridepublic List<User> getAll() {return userDao.getAll();}}
5.控制层
@WebServlet(urlPatterns= {"*.udo"})
public class UserController extends HttpServlet{private static final long serialVersionUID = 1L;//@Autowired//private UserService userService; //自动装配,因为在service层实现类中用了@Service("userService"),创建了对象@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");System.out.println("这里是post请示的处理方法"+req.getContextPath());String mn=req.getServletPath(); //返回提交请求的地址名 如: /query.udomn=mn.substring(1); // 去掉反斜杠mn=mn.substring(0,mn.length()-4); //去掉 .udotry {Method method=this.getClass().getDeclaredMethod(mn,HttpServletRequest.class,HttpServletResponse.class);method.invoke(this, req,resp);} catch (Exception e) { //捕获总异常即可,后面的捕获异常可去掉e.printStackTrace();}}private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("访问到这了index");ServletContext servletContext = req.getServletContext();ApplicationContext context =(ApplicationContext) servletContext.getAttribute("applicationContext"); //spring配置文件在监听器中,启动web服务器时,自动初始化了,并保存在全局上下文域中。UserService userService = (UserService)context.getBean("userService"); //因index.udo这页面是运行时生成的,不能用@Autowired自动装配userServiceList<User> users=userService.getAll();req.setAttribute("users", users);req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp);}}
6.测试:浏览器地址栏中:localhost:8081/shweb/index.html回车,会通javascript代码功能自动转到index.udo(控制类中的方法)生成页面,再转发到index.jsp中,显示用户记录
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body><script type="text/javascript">window.location.href="index.udo"</script><!-- <a href="index.udo">进入index页</a> --> <!-- 这个要点一下 -->
</body>
</html>
/WEB-INF/jsp/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>javaWeb,spring,hibernate整合的获取到User</title>
</head>
<body><table><tr><td>用户id</td><td>用户名</td><td>余额</td></tr><c:forEach var="user" items="${users}"><tr><td>${user.id}</td><td>${user.username}</td><td>${user.balance}</td></tr></c:forEach> </table>
</body>
</html>