SpringMVC+Hibernate4

发布时间:2019-09-13 09:31:32编辑:auto阅读(1529)

    • 开发环境

      1,项目用到的框架有:Spring3.2.14.RELEASE、Hibernate4.2.20.Final、Bootstrap3

      2,开发工具eclipse、maven

      3,数据库Mysql5.6.24

    • 正文

    1.数据库表

    CREATE TABLE `user` (
      `ID` int(11) NOT NULL AUTO_INCREMENT,
      `USER_NAME` varchar(100) DEFAULT NULL,
      `PASSWD` varchar(100) DEFAULT NULL,
      `STATE` tinyint(4) DEFAULT NULL,
      `CREATE_TIME` date DEFAULT NULL,
      `UPDATE_TIME` date DEFAULT NULL,
      `DECRIBE` varchar(200) DEFAULT NULL,
      PRIMARY KEY (`ID`)
    )

    2.配置文件

     1) web.xml

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    <web-app>
    	<display-name>Archetype Created Web Application</display-name>
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:applicationContext.xml</param-value>
    	</context-param>
    
    	<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>
    	</filter>
    
    	<filter-mapping>
    		<filter-name>encodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    
    	<servlet>
    		<servlet-name>dispatcherServlet</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>classpath:SpringMVC.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    
    	<servlet-mapping>
    		<servlet-name>dispatcherServlet</servlet-name>
    		<url-pattern>*.htm</url-pattern>
    	</servlet-mapping>
    
    	<welcome-file-list>
    		<welcome-file>view/user/index.jsp</welcome-file>
    	</welcome-file-list>
    </web-app>

     2) db_info.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/zws001
    jdbc.username=root
    jdbc.password=root

     3) log4j.properties

    log4j.rootCategory = info,stdout
    
    log4j.appender.stdout = org.apache.log4j.ConsoleAppender\t\t		
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH\:mm\:ss}|%p|%C|%M|%L|%m%n

     4) 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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans
    						http://www.springframework.org/schema/beans/spring-beans-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/context
    				   		http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    	<context:property-placeholder location="classpath:db_info.properties"/>
    	<!-- 只扫描被@Service @Repository注解标记的类 -->
    	<context:component-scan base-package="com.zws" use-default-filters="false">
    	  	<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> 
    	    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> 
    	</context:component-scan>	
    	<!-- 激活spring事务注解,即@Transactional注解 -->
    	<tx:annotation-driven transaction-manager="transactionManager" />
    	
    	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    		<property name="driverClass" value="${jdbc.driverClassName}"></property>
    		<property name="jdbcUrl" value="${jdbc.url}"></property>
    		<property name="user" value="${jdbc.username}"></property>
    		<property name="password" value="${jdbc.password}"></property>
    		<property name="checkoutTimeout" value="5000"></property>
    		<property name="acquireIncrement" value="3"></property>
    		<property name="maxIdleTime" value="60"></property>
    		<property name="maxPoolSize" value="15"></property>
    	</bean> 
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    	    <property name="dataSource" ref="dataSource"></property>
    		<property name="hibernateProperties">
    			<props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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="packagesToScan">
    			<list>
    				<value>com.zws.user.beans</value>
    			</list>
    		</property>
    	</bean>
    
    	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    </beans>

     5) SpringMVC.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"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans
    						http://www.springframework.org/schema/beans/spring-beans-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/context
    				   		http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    	<!-- 只扫描被@Controller注解标记的类,子容器一定不要扫描有事务控制的Service层,否则会出现一个很蛋疼的org.hibernate.HibernateException: No Session found for current thread异常,切记切记啊!!!-->
    	<context:component-scan base-package="com.zws" use-default-filters="false">
    	  	<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    	</context:component-scan>
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	    <property name="prefix" value="/view/"></property>
    	    <property name="suffix" value=".jsp"></property>
    	</bean>
    </beans>

    3.实体Bean

    package com.zws.user.beans;
    
    import java.util.Date;
    
    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="USER")
    public class User {
    
    	@Id
    	@Column(name="ID")
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	private Long id;
    	
    	@Column(name="USER_NAME")
    	private String userName;
    	
    	@Column(name="PASSWD")
    	private String passwd;
    	
    	@Column(name="STATE")
    	private Integer state;
    	
    	@Column(name="CREATE_TIME")
    	private Date createTime;
    	
    	@Column(name="UPDATE_TIME")
    	private Date updateTime;
    	
    	@Column(name="DECRIBE")
    	private String describe;
    
    	public Long getId() {
    		return id;
    	}
    
    	public void setId(Long id) {
    		this.id = id;
    	}
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public String getPasswd() {
    		return passwd;
    	}
    
    	public void setPasswd(String passwd) {
    		this.passwd = passwd;
    	}
    
    	public Integer getState() {
    		return state;
    	}
    
    	public void setState(Integer state) {
    		this.state = state;
    	}
    
    	public Date getCreateTime() {
    		return createTime;
    	}
    
    	public void setCreateTime(Date createTime) {
    		this.createTime = createTime;
    	}
    
    	public Date getUpdateTime() {
    		return updateTime;
    	}
    
    	public void setUpdateTime(Date updateTime) {
    		this.updateTime = updateTime;
    	}
    
    	public String getDescribe() {
    		return describe;
    	}
    
    	public void setDescribe(String describe) {
    		this.describe = describe;
    	}
    
    	@Override
    	public String toString() {
    		return "User [id=" + id + ", userName=" + userName + ", passwd="
    				+ passwd + ", state=" + state + ", createTime=" + createTime
    				+ ", updateTime=" + updateTime + ", describe=" + describe + "]";
    	}
    }

    4.持久层

     1) BaseDao.java

    package com.zws.user.dao;
    
    import java.math.BigInteger;
    import java.util.List;
    
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.criterion.Restrictions;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import com.zws.user.beans.User;
    
    public class BaseDao<T> {
    	@Autowired
    	private SessionFactory sessionFactory;
    	
    	public void save(T entity) {
    		getSession().save(entity);
    	}
    	
    	public Session getSession() {
    		return sessionFactory.getCurrentSession();
    	}
    
    	@SuppressWarnings("unchecked")
    	public List<T> queryList(String hql) {
    		return getSession().createQuery(hql).list();	
    	}
    	
    	@SuppressWarnings("unchecked")
    	public List<T> querySQList(String sql, Class<T> clz) {
    		return getSession().createSQLQuery(sql).addEntity(clz).list();	
    	}
    	
    	@SuppressWarnings("unchecked")
    	public List<T> querySQList(String sql,Class<T> clz, String... vals) {
    		SQLQuery query = getSession().createSQLQuery(sql).addEntity(clz);
    		if (vals != null && vals.length > 0) 
    			for (int i = 0; i < vals.length; i++) {
    				query.setParameter(i, vals[i]);
    			}
    		return query.list();
    	}
    	
    	public Integer getCount(String sql) {
    		return ((BigInteger) getSession().createSQLQuery(sql).uniqueResult()).intValue();
    	}
    	
    	public void self() {
    		getSession().createCriteria(User.class).add(Restrictions.eq("userName", ""));
    	}
    	
    }

     2) UserDao.java

    package com.zws.user.dao;
    
    import java.util.List;
    
    import com.zws.user.beans.User;
    
    public interface UserDao {
    
    	void save(User user);
    	
    	List<User> queryUsers(User user);
    	
    	Integer querySize(User user);
    }

     3) UserDaoImpl.java

    package com.zws.user.dao.impl;
    
    import java.util.List;
    
    import org.springframework.stereotype.Repository;
    
    import com.zws.user.beans.User;
    import com.zws.user.dao.BaseDao;
    import com.zws.user.dao.UserDao;
    @Repository
    public class UserDaoImpl extends BaseDao<User> implements UserDao {
    
    	public void save(User user) {
    		super.save(user);
    	}
    
    	public List<User> queryUsers(User user) {
    		String hql = "FROM User WHERE state = " + user.getState();
    		return queryList(hql);
    	}
    
    	public Integer querySize(User user) {
    		String sql = "SELECT COUNT(*) FROM USER WHERE STATE = " + user.getState();
    		return getCount(sql);
    	}
    
    }

    5.服务层

     1) UserService.java

    package com.zws.user.service;
    
    import java.util.List;
    
    import com.zws.user.beans.User;
    
    public interface UserService {
    
    	void save(User user);
    	
    	List<User> queryUsers(User user);
    	
    	Integer querySize(User user);
    }

     2) UserServiceImpl.java

    package com.zws.user.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.zws.user.beans.User;
    import com.zws.user.dao.UserDao;
    import com.zws.user.service.UserService;
    @Service
    @Transactional
    public class UserServiceImpl implements UserService{
    	@Autowired
    	@Qualifier("userDaoImpl")
    	private UserDao userDao;
    
    	public void save(User user) {
    		userDao.save(user);
    	}
    	public List<User> queryUsers(User user) {
    		return userDao.queryUsers(user);
    	}
    
    	public Integer querySize(User user) {
    		return userDao.querySize(user);
    	}
    
    }

    6.视图控制层

     1) UserController.java

    package com.zws.user.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.zws.user.beans.User;
    import com.zws.user.service.UserService;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
    	@Autowired
    	@Qualifier("userServiceImpl")
    	private UserService service;
    	
    	@RequestMapping(value="/login.htm")
    	public ModelAndView login(User user) {
    		System.out.println(user);
    		user.setState(1);
    		List<User> users = service.queryUsers(user);
    		ModelAndView view = new ModelAndView("user/jsp/home");
    		view.addObject("users", users);
    		return view;
    	}
    }

    7.视图

     1) /SpringMVCHibernate4/src/main/webapp/view/index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="zh-cn">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css">
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/bootstrap.min.js"></script>
    <title>login please</title>
    <script type="text/javascript">
    	
    </script>
    </head>
    <body>
    	<div class="container">
    		<div class="row col-md-4 col-md-offset-4 jumbotron">
    
    			<form action="<c:url value="/user/login.htm" />" method="post">
    				<div class="form-group">
    					<label for="exampleInputEmail1">Email address</label> 
    					<input name="userName" type="text" class="form-control" 
    						id="exampleInputEmail1" placeholder="Email">
    				</div>
    				<div class="form-group">
    					<label for="exampleInputPassword1">Password</label> 
    					<input name="passwd" type="password" class="form-control" 
    							id="exampleInputPassword1" placeholder="Password">
    				</div>
    				<button type="submit" class="btn btn-lg btn-primary">Login</button>
    			</form>
    		</div>
    	</div>
    
    </body>
    </html>

     2)  /SpringMVCHibernate4/src/main/webapp/view/user/jsp/home.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ page isELIgnored="false" %> 
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="zh-cn">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css">
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/bootstrap.min.js"></script>
    <title>login please</title>
    <script type="text/javascript">
    	
    </script>
    </head>
    <body>
    	<div class="container " style="margin-top: 20px;">
        	<div class="row col-md-8 col-md-offset-2 jumbotron">
        		<table class="table table-bordered table-hover">
        			 <thead>
    				    <tr>
    				      <th>用户名</th>
    				      <th>密码</th>
    				      <th>状态</th>
    				    </tr>
    				  </thead>
    				  <tbody>
    		    		<c:forEach items="${users }" var="user">
    		    			<tr>
    		    				<td>${user.userName }</td>
    		    				<td>${user.passwd }</td>
    		    				<td>${user.state }</td>
    		    			</tr>
    		    		</c:forEach>
    	    		</tbody>
        		</table>
        	</div>
     	</div>
    </body>
    </html>

    8. pom.mxl

    <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.zws</groupId>
    	<artifactId>SpringMVCHibernate4</artifactId>
    	<packaging>war</packaging>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>spriHibnt Maven Webapp</name>
    	<url>http://maven.apache.org</url>
    	<properties>
        	<spring-version>3.2.14.RELEASE</spring-version>
        	<hibernate-version>4.2.20.Final</hibernate-version>
    	</properties>
    	<dependencies>
    		<dependency> 
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.5</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>javax.servlet-api</artifactId>
    			<version>3.0.1</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>log4j</groupId>
    			<artifactId>log4j</artifactId>
    			<version>1.2.17</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>cglib</groupId>
    			<artifactId>cglib</artifactId>
    			<version>2.2.2</version>
    		</dependency>
    		<dependency>
    			<groupId>org.aspectj</groupId>
    			<artifactId>aspectjrt</artifactId>
    			<version>1.7.4</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>aspectj</groupId>
    			<artifactId>aspectjweaver</artifactId>
    			<version>1.5.4</version>
    		</dependency>
    
    		<!-- spring begin -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency> 
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-beans</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-aop</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-web</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-jdbc</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-test</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-orm</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    		<!-- spring end -->
    
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>5.1.36</version>
    		</dependency>
    
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>jstl</artifactId>
    			<version>1.2</version>
    		</dependency>
    		<!-- hibernate 4.2 -->
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-c3p0</artifactId>
    			<version>${hibernate-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-core</artifactId>
    			<version>${hibernate-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-validator</artifactId>
    			<version>4.2.0.Final</version>
    		</dependency>
    		<!-- EL表达式支持 -->
    		<dependency>
    			<groupId>javax.el</groupId>
    			<artifactId>el-api</artifactId>
    			<version>2.2</version>
    		</dependency>
    	</dependencies>
    	<build>
    		<finalName>SpringMVCHibernate4</finalName>
    	</build>
    </project>

    9. 项目目录结构及效果截图

     1) 项目目录结构截图

    wKioL1YTRiPS639PAAGKlqhjJdg798.jpg

    wKioL1YTRnyA7kbdAADnzd6MNg4149.jpg

    2)效果截图

    wKiom1YTRuDQv11kAADgLFZCOiE325.jpg

    wKioL1YTRvXRCUf4AAEcWSz5RkE067.jpg


关键字