springmvc,spring,hibernate整合

1. 创建一个maven web工程

先在eclipse中创建一个标准的maven web工程,如果不知道怎么创建可以参照我的这篇博客:在eclipse中用maven创建web项目。

2. 在pom.xml文件增加相关包的依赖

在pom.xml文件中增加spingmvc,spring,hibernate相关的依赖包,内容比较多不一一贴出了,具体可从我的githib地址下载完整的项目代码

3. 配置web.xml文件

配置web.xml文件,主要是增加springmvn和spring的配置,具体如下

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>ssh-integration</display-name>
  
  <!-- 加载所有的配置文件 -->
  <context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:spring-*.xml</param-value>
  </context-param>
  
  <!-- 配置Spring监听 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 配置字符集 -->
  <filter>
	  <description>字符集过滤器</description>
	  <filter-name>encodingFilter</filter-name>
	  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	  <init-param>
		<description>字符集编码</description>
		<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>
  
  <!-- 配置SpringMVC -->
  <servlet>
	  <description>spring mvc servlet</description>
	  <servlet-name>springMvc</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <init-param>
		  <description>spring mvc 配置文件</description>
		  <param-name>contextConfigLocation</param-name>
		  <param-value>classpath:spring-mvc.xml</param-value>
	  </init-param>
	  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
	  <servlet-name>springMvc</servlet-name>
	  <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

4. 配置spring,springmvc, hibernate文件

这些文件都放在src/main/resources下

先来spring-mvc.xml文件,主要配置自动扫描哪个包下的类以及默认的视图解析器等,如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" 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/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
	<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
	<!-- 加载controller的时候,不加载service,因为此时事物并未生效,若此时加载了service,那么事物无法对service进行拦截 -->
	<context:component-scan base-package="com.jason.sshIntegration.*">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
	</context:component-scan>
	
	<!-- 开启注解 -->
	<mvc:annotation-driven />
	<!-- 默认的视图解析器  -->
	<bean id="defaultViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:order="3">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="contentType" value="text/html" />
		<property name="prefix" value="/webpage/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

接着是配置spring和hibernate整合的文件叫spring-hibernate.xml,主要配置hibernate的sessionFactory及对应的datasource等,如下

<?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:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
	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
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
	default-autowire="byName" default-lazy-init="false">
	<!-- 自动扫描dao和service包(自动注入) 
	<context:component-scan base-package="com.jason.sshIntegration.dao.*" />
	<context:component-scan base-package="com.jason.sshIntegration.service.*" />
    -->
	<!-- 加载service,此时要排除要controller,因为controller已经spring-mvc中加载过了 -->
	<context:component-scan base-package="com.jason.sshIntegration.*">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!-- 配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost/ssh?useUnicode=true&amp;characterEncoding=UTF-8"></property>
		<property name="username" value="ssh"></property>
		<property name="password" value="ssh"></property>
	</bean>

	<!-- 配置SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">none</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 注解扫描的包 -->
		<property name="annotatedClasses">
			<list>
				<value>com.jason.sshIntegration.entity.User</value>
			</list>
		</property>
	</bean>

	<!-- 配置事物管理器,在*ServiceImpl里写@Transactional就可以启用事物管理 -->
	<bean name="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

4. 简单的增删改查的代码

先在数据库中创建库,用户,表结构等,具体的sql文件如下

CREATE DATABASE ssh DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
grant all privileges on ssh.* to ssh@localhost identified by 'ssh';
use ssh;
CREATE TABLE `T_USER` (
`id`  varchar(32) NULL ,
`user_name`  varchar(32) NULL ,
`age`  varchar(32) NULL ,
PRIMARY KEY (`id`)
)
;


接着是相关的代码,包括entity,dao,service,controller,jsp,具体如下

entity:

/**
 * 
 */
package com.jason.sshIntegration.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;

/**
 * 
 * @author jasonzhang
 *
 */
@Entity
@Table(name = "T_USER")
public class User {

	@Id
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid")
	@Column(length = 32)
	private String id;

	@Column(name="user_name", length = 32)
	private String userName;

	@Column(length = 32)
	private String age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}
}

dao

/**
 * 
 */
package com.jason.sshIntegration.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.jason.sshIntegration.entity.User;

/**
 * @author jasonzhang
 *
 */
@Repository("userDao")
public class UserDao {

	/**
	 * 自动注入sessionFactory
	 * **/
	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * 根据用户id查询用户
	 */
	public User getUser(String id) {

		String hql = "from User u where u.id=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);

		return (User) query.uniqueResult();
	}

	/**
	 * 查询所有用户
	 */
	public List<User> getAllUser() {

		String hql = "from User";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);

		return query.list();
	}

	/**
	 * 添加用户
	 */
	public void saveUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	/**
	 * 根据id删除用户
	 */
	public boolean delUser(String id) {

		String hql = "delete User u where u.id = ?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);
		query.executeUpdate();
		//return (query.executeUpdate() > 0);
		return true;
	}

	/**
	 *编辑用户
	 */
	public boolean updateUser(User user) {

		String hql = "update User u set u.userName = ?,u.age=? where u.id = ?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, user.getUserName());
		query.setString(1, user.getAge());
		query.setString(2, user.getId());

		return (query.executeUpdate() > 0);
	}
}

service

/**
 * 
 */
package com.jason.sshIntegration.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jason.sshIntegration.dao.UserDao;
import com.jason.sshIntegration.entity.User;

/**
 * @author jasonzhang
 *
 */
@Service("userService")
@Transactional
public class UserService {

	@Resource
	private UserDao userDao;  

	public User getUser(String id) {  
	    return userDao.getUser(id);  
	}  

	public List<User> getAllUser() {  
	    return userDao.getAllUser();  
	}  

	public void saveUser(User user) {  
	    userDao.saveUser(user);  
	}  

	public boolean delUser(String id) {  

	    return userDao.delUser(id);  
	}  

	public boolean updateUser(User user) {  
	    return userDao.updateUser(user);  
	}
}

controller

/**
 * 
 */
package com.jason.sshIntegration.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jason.sshIntegration.entity.User;
import com.jason.sshIntegration.service.UserService;

/**
 * @author jasonzhang
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("userController")
public class UserController {

	@Resource
	private UserService userService;

	@RequestMapping("userList")
	public String userList(HttpServletRequest request) {
		request.setAttribute("userList", userService.getAllUser());
		return "/com/jason/sshIntegration/userList";
	}

	@RequestMapping("addorupdate")
	public String addorupdate(User user, HttpServletRequest request) {
		if (user.getId() != null) {
			user = userService.getUser(user.getId());
			request.setAttribute("userPage", user);
		}
		return "/com/jason/sshIntegration/user";
	}

	@RequestMapping("save")
	public String save(User user, HttpServletRequest request) {
		System.out.println("用户名是======" + user.getUserName());
		if (user.getId() != null && !user.getId().equals("")) {
			this.userService.updateUser(user);
		} else {
			userService.saveUser(user);
		}
		return "redirect:userList.do";
	}

	@RequestMapping("delUser")
	public void delUser(String id, HttpServletResponse response) {
		String result = "{\"result\":\"error\"}";
		if (userService.delUser(id)) {
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");  
	    try {  
	        PrintWriter out = response.getWriter();  
	        out.write(result);  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } 
	}
}

最后是两个jsp页面,列表及新增和修改的jsp代码

userList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
	src="<%=basePath%>/plug-in/jquery/1.9.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
<script type="text/javascript">
	function del(id) {
		$.get("delUser.do?id=" + id, function(data) {
			alert(data.result);
			if ("success" == data.result) {
				alert("删除成功");
				window.location.reload();
			} else {
				alert("删除失败");
			}
		});
	}
</script>
</head>
<body>
	<h6>
		<a href="addorupdate.do">添加用户</a>
	</h6>
	<table border="1">
		<tbody>
			<tr>
				<th>姓名</th>
				<th>年龄</th>
				<th>操作</th>
			</tr>
			<c:if test="${!empty userList }">
				<c:forEach items="${userList }" var="user">
					<tr>
						<td>${user.userName }</td>
						<td>${user.age }</td>
						<td><a
							href="addorupdate.do?id=${user.id }">编辑</a>
							<a href="javascript:del('${user.id }')">删除</a></td>
					</tr>
				</c:forEach>
			</c:if>
		</tbody>
	</table>
</body>
</html>

user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!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>
<script type="text/javascript"
	src="<%=basePath%>/plug-in/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">  
function addUser(){  
    var form = document.forms[0];  
    form.action = "save.do";  
    form.method="post";  
    form.submit();  
}  
</script>  
</head>  
<body>  
<h1>添加用户</h1>
<form action="" name="userForm">
<input type="hidden" name="id" value="${userPage.id }">  
    姓名:<input type="text" name="userName" value="${userPage.userName }">
    年龄:<input type="text" name="age" value="${userPage.age }">  
    <input type="button" value="确定" onclick="addUser()">  
</form>  
</body>  
</html>

4. 其它

项目的github地址为:https://github.com/zjordon/ssh-integration

本项目通过内嵌的jetty来运行,在构建完工程后可以通过src/main/java/test包下的StartJetty类来运行工程。



你可能感兴趣的:(spring,Hibernate,springMVC)