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

配置web.xml


<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>mywebdisplay-name>
    <welcome-file-list>
        <welcome-file>/WEB-INF/jsp/register.jspwelcome-file>
        <welcome-file>/WEB-INF/jsp/login.jspwelcome-file>
    welcome-file-list>
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath*:config/spring-*.xmlparam-value>
    context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/url-pattern>

        
    <filter>
        <filter-name>openSessionfilter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
        <init-param>
            <param-name>singleSessionparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>flushModeparam-name>
            <param-value>AUTOparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>openSessionfilter-name>
        <url-pattern>/url-pattern>
    filter-mapping>

    
    <servlet>
        <description>mywebdescription>
        <display-name>mywebdisplay-name>
        <servlet-name>springMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath*:config/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app> 

SpringMVC中Bean的配置spring-mvc.xml


<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">
    
    <mvc:annotation-driven />
    
    <mvc:resources location="/resources" mapping="/resources/**" />
    
    <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" />
    
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        
        <property name="configLocation" value="classpath:config/hibernate.cfg.xml" />
        <property name="packagesToScan" value="com.myweb.entity" />
    bean>
    
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    bean>
    
    
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    bean>
    
    <aop:config>
        
        
        <aop:pointcut id="allMethods" expression="execution(* com.myweb.service.*.*(..))" />
        
        <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 />
    
    <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



<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">falseproperty>
        
        <property name="hbm2ddl.auto">updateproperty>
        <property name="show_sql">trueproperty>
        <property name="format_sql">trueproperty>
        <property name="jdbc.fetch_size">50property>
        <property name="jdbc.batch_size">30property>
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProviderproperty>
        <property name="hibernate.c3p0.acquireRetryAttempts">30property>
        <property name="hibernate.c3p0.acquireIncrement">2property>
        <property name="hibernate.c3p0.checkoutTimeout">30000property>
        <property name="hibernate.c3p0.idleConnectionTestPeriod">120property>
        <property name="hibernate.c3p0.maxIdleTime">180property>
        <property name="hibernate.c3p0.initialPoolSize">3property>
        <property name="hibernate.c3p0.maxPoolSize">50property>
        <property name="hibernate.c3p0.minPoolSize">1property>
        <property name="hibernate.c3p0.maxStatements">0property>
        
        
        
    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"%>

<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"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>个人中心title>
head>
<body>欢迎你!!! ${user.username}
body>
html> 

你可能感兴趣的:(hibernate,Spring,SpringMVC)