Spring4+SpringMVC+Hibernate4整合入門與實例
阿新 • • 發佈:2017-07-22
type 解析 .class -m .config ise pri generated driver
配置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"
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">
<display-name>myweb</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/register.jsp</welcome-file>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
<!-- 載入全部的配置文件 -->
<context-param >
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>
<!-- 配置Spring監聽 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class >
</listener>
<!-- 配置字符集 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
<!-- 配置Session -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<description>myweb</description>
<display-name>myweb</display-name>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC中Bean的配置spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" 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.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-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 開啟Spring MVC註解 -->
<mvc:annotation-driven />
<!-- 處理靜態資源 -->
<mvc:resources location="/resources" mapping="/resources/**" />
<!-- 打開Spring的Annotation支持 -->
<context:annotation-config />
<!-- 註解掃描包 -->
<context:component-scan base-package="com.myweb.controller" />
<context:component-scan base-package="com.myweb.dao.imp" />
<context:component-scan base-package="com.myweb.service.imp" />
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="configLocation" value="classpath:config/hibernate.cfg.xml" />
<property name="packagesToScan" value="com.myweb.entity" />
</bean>
<!-- 配置Dao要註入的hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置Spring的事務處理 -->
<!-- 創建事務管理器 -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置AOP。Spring是通過AOP來進行事務管理的 -->
<aop:config>
<!-- 設置pointCut表示哪些方法要增加事務處理 -->
<!-- 下面的事務是聲明在DAO中,可是通常都會在Service來處理多個業務對象邏輯的關系,註入刪除,更新等,此時假設在運行了一個步驟之後拋出異常
就會導致數據不完整,所以事務不應該在DAO層處理,而應該在service。這也就是Spring所提供的一個很方便的工具。聲明式事務 -->
<aop:pointcut id="allMethods" expression="execution(* com.myweb.service.*.*(..))" />
<!-- 通過advisor來確定詳細要增加事務控制的方法 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" />
</aop:config>
<!-- 配置哪些方法要增加事務控制 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 讓全部的方法都增加事務管理,為了提高效率。能夠把一些查詢之類的方法設置為僅僅讀的事務 -->
<tx:method name="*" propagation="REQUIRED" read-only="true" />
<!-- 下面方法都是可能設計改動的方法。就無法設置為僅僅讀 -->
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 開啟事務註解 -->
<tx:annotation-driven />
<!-- 默認的視圖解析器ViewResolver -->
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Hibernate的配置hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?
>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost/myweb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
jiangyu
</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<!-- ddl語句自己主動建表 -->
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="jdbc.fetch_size">50</property>
<property name="jdbc.batch_size">30</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquireRetryAttempts">30</property>
<property name="hibernate.c3p0.acquireIncrement">2</property>
<property name="hibernate.c3p0.checkoutTimeout">30000</property>
<property name="hibernate.c3p0.idleConnectionTestPeriod">120</property>
<property name="hibernate.c3p0.maxIdleTime">180</property>
<property name="hibernate.c3p0.initialPoolSize">3</property>
<property name="hibernate.c3p0.maxPoolSize">50</property>
<property name="hibernate.c3p0.minPoolSize">1</property>
<property name="hibernate.c3p0.maxStatements">0</property>
<!-- XML配置映射關系 <mapping resource="Employee.hbm.xml" /> -->
<!-- 註冊ORM映射文件 -->
<!-- spring不起作用 <mapping package="com.myweb.entity"/> -->
</session-factory>
</hibernate-configuration>
實體層
package com.myweb.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "w_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 50)
private String username;
@Column(length = 20)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
數據訪問層(DAO層)
接口:
package com.myweb.dao;
import com.myweb.entity.User;
public interface UserDao {
User save(User user);
}
實現:
package com.myweb.dao.imp;
import javax.inject.Inject;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.myweb.dao.UserDao;
import com.myweb.entity.User;
@Repository
public class UserDaoImp implements UserDao {
@Inject
private HibernateTemplate template;
@Override
public User save(User user) {
// TODO Auto-generated method stub
template.save(user);
return template.load(User.class, user.getId());
}
}
服務層(Service層)
接口:
package com.myweb.service;
import com.myweb.entity.User;
public interface UserService {
User save(User user);
}
實現:
package com.myweb.service.imp;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.myweb.dao.UserDao;
import com.myweb.entity.User;
import com.myweb.service.UserService;
@Service
public class UserServiceImp implements UserService {
@Inject
private UserDao userDao;
@Override
public User save(User user) {
// TODO Auto-generated method stub
return userDao.save(user);
}
}
控制層(Controller層)
package com.myweb.controller;
import javax.inject.Inject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.myweb.entity.User;
import com.myweb.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Inject
private UserService userService;
@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String register(User user) {
userService.save(user);
return "login";
}
@RequestMapping(value = "/login.do", method = RequestMethod.POST)
public String login(@ModelAttribute("user") User user) {
return "self";
}
}
視圖成(View層)
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>註冊</title>
</head>
<body>
<form action="/myweb/user/register.do" method="post">
用戶名:<input type="text" name="username" /><br /> 密碼:<input
type="password" name="password"><br /> <input type="submit"
value="提交">
</form>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>登錄</title>
</head>
<body>
<form action="/myweb/user/login.do" method="post">
用戶名:<input type="text" name="username"><br /> 密碼:<input
type="password" name="password"><br /> <input type="submit"
value="登錄">
</form>
</body>
</html>
self.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>個人中心</title>
</head>
<body>歡迎你!。! ${user.username}
</body>
</html>
Spring4+SpringMVC+Hibernate4整合入門與實例