码迷,mamicode.com
首页 > 编程语言 > 详细

Spring4+SpringMVC+Hibernate4整合入门与实例

时间:2015-08-11 14:13:56      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:hibernate   spring   spring mvc   

配置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整合入门与实例

标签:hibernate   spring   spring mvc   

原文地址:http://blog.csdn.net/csujiangyu/article/details/47418553

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!