springmvc、spring、hibernate整合示例

在mysql数据库中建立一个user表,已对user的增删改查为例,整合springmvc、spring、hibernate。

1.web.xml中的配置:①spring监听器;②spring mvc的servlet;③字符编码过滤器。

<!-- spring 监听器的配置 -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:beans.xml</param-value>
</context-param>
  
<!-- springMVC 配置 -->
<servlet>
  <servlet-name>springmvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:user-servlet.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>

<!-- 字符编码过滤器 -->
<filter>
	<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
	<url-pattern>/* </url-pattern>
</filter-mapping>

2.spring mvc配置文件 user-servlet.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"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<!-- 	<context:component-scan base-package="com.yawn.controller"></context:component-scan>	 -->
	
 	<context:component-scan base-package="com.yawn.*" use-default-filters="false">
 		<context:include-filter type="annotation" 
 			expression="org.springframework.stereotype.Controller"/>
 	</context:component-scan>
	
	<mvc:annotation-driven/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

</beans>

3.spring的配置文件beans.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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:component-scan base-package="com.yawn.*">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>


	<context:property-placeholder location="classpath:db.properties"/>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置dataSource数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 
			引入hibernate配置文件 
			<property name="configLocation" value="classpath:hibernate.cfg.xml" />
		-->
		<!-- 使用此配置就可以不再引入hibernate配置文件 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
<!-- 				<prop key="hibernate.mappings">com.yawm.entity.User</prop> -->
			</props>
		</property>
		<!-- 使用此配置代替以前hibernate中使用的mappingLocations配置 -->
 		<property name="annotatedClasses">
 			<list>
 				<value>com.yawn.entity.User</value>
 			</list>
 		</property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>


	<tx:annotation-driven transaction-manager="transactionManager" />
	<aop:aspectj-autoproxy />

</beans>

3.1.db.properties数据库属性配置文件:

######################################
##	configuration of database		##
######################################

jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/volunteer?useUnicode\=true&characterEncoding\=utf8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.initialPoolSize=20
jdbc.maxPoolSize=50

4.controller的设计:

package com.yawn.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yawn.entity.User;
import com.yawn.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;

	public UserController() {
	}
	
	@RequestMapping("getAll")
	private List<User> getAll() {
		return userService.getAll();
	}
	
	@RequestMapping(value="updateUser/{id}", method={RequestMethod.GET})
	private String updateUser(@PathVariable int id, Map<String,User> map){
		
		map.put("user", userService.getUserById(id));
		
		return "updateUser";
	}
	
	@RequestMapping(value="updateUser", method={RequestMethod.POST})
	private String updateUser(User user){
		
		userService.updateUser(user);
		
		return "redirect:getAll.do";
	}
	
	@RequestMapping(value="deleteUser/{id}", method={RequestMethod.GET})
	private String deleteUser(@PathVariable int id){
		
		userService.deleteUser(id);
		
		return "redirect:/getAll.do";
	}
	
	@RequestMapping(value="addUser", method={RequestMethod.GET})
	private void addUser(){
		// 或者使用静态资源都可以跳转到addUser.jsp页面
	}
	@RequestMapping(value="addUser", method={RequestMethod.POST})
	private String addUser(User user, BindingResult result){
		
		System.out.println(result);
		
		userService.addUser(user);
		
		return "redirect:/getAll.do";
	}
	
}

5.service的设计:

package com.yawn.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yawn.dao.UserDao;
import com.yawn.entity.User;

@Service
public class UserService {
	
	@Autowired
	private UserDao userDao;

	public UserService() {
	}
	
	public List<User> getAll(){
		
		return userDao.getAll();
	}
	
	public boolean updateUser(User user){
		return userDao.updateUser(user);
	}
	
	public User getUserById(int id){
		return userDao.getUserById(id);
	}
	
	public boolean deleteUser(int id) {
		return userDao.deleteUser(id);
	}
	
	public boolean addUser(User user) {
		return userDao.addUser(user);
	}
}

6.dao的设计:

package com.yawn.dao;

import java.util.List;

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

import com.yawn.entity.User;

@Repository
public class UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public UserDao() {
	}

	@SuppressWarnings("unchecked")
	public List<User> getAll() {

		Session session = getSession();

		String hql = "from User";

		Query query = session.createQuery(hql);

		return query.list();
	}

	public boolean updateUser(User user) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
		return true;
	}

	public User getUserById(int id) {
		return (User) getSession().get(User.class, id);
	}

	public boolean deleteUser(int id) {

		User user = new User();
		user.setId(id);

		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.delete(user);
		tx.commit();
		session.close();
		return true;
	}

	public boolean addUser(User user) {

		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
		return true;
	}

	private Session getSession() {
		return sessionFactory.openSession();
	}
}

7.entity的设计:

package com.yawn.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name="user")
public class User {
	
	/*
	 * @Id 定义数据表的主键
	 * @GeneratedValue 定义主键(列)的生成策略
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	@Column(length=24, unique=true, nullable=false)
//	@Length(max=24, min=3, message="name的长度在3~24之间")
	private String name;
	@Column(length=24, nullable=false)
	private String password;
	@Column
//	@Max(value=88, message="age不能大于88")
	private int age;
	
	public User() {
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", age=" + age + "]";
	}

}

8.页面设计:

-----------------addUser.jsp---------------------
<form action="/user2/addUser.do" method="post">
	name:<input name="name"><br>
	password:<input name="password"><br>
	age:<input name="age"><br>
	<input type="submit" value="添加">
</form>

-----------------getAll.jsp----------------------
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="u" items="${userList }">
	<h3>${u.id } | ${u.name } | ${u.password } | ${u.age } |
		<a href="deleteUser/${u.id }.do">删除</a>
		<a href="updateUser/${u.id }.do">修改</a>
	</h3>
</c:forEach>

---------------updateUser.jsp--------------------
<form action="/user2/updateUser.do" method="post">
	<input name="id" type="hidden" value="${user.id }">
	name:<input name="name" value="${user.name }"><br>
	password:<input name="password" value="${user.password }"><br>
	age:<input name="age" value="${user.age }"><br>
	<input type="submit" value="确定修改">
</form>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区