欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC_3.x_入门指南_4 博客分类: SpringMVC SpringMVC连接Hibernate框架整合 

程序员文章站 2024-03-24 10:21:16
...

SpringMVC 3.x

博文目录

  1. 数据库及表的建立
  2. pom.xml
  3. springmvc-servlet.xml
  4. web.xml
  5. applicationContext.xml
  6. jdbc.properties
  7. src/main/java中的代码
  8. jsp文件

SpringMVC与Hibernate整合

先不说为什么,一口气达到实现对数据库CURD的操作!!!

BaseDao算是一个帮助类,你可以使用你喜欢的任何样式的JDBC!


SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
 
SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
 
SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
 
SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
 
SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
 

使用MySQL建立数据库:

CREATE DATABASE `log`;

CREATE TABLE t_user( 
id INT AUTO_INCREMENT PRIMARY KEY, 
username VARCHAR(255), 
`password` VARCHAR(512));

 

Maven项目:pom.xml

<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.hyx</groupId>
  <artifactId>springmvc</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- SpringMVC核心jar -->
    <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>3.2.4.RELEASE</version>
	</dependency>
    <!-- springmvc连接数据库需要的jar -->
    <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>3.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-orm</artifactId>
		<version>3.2.4.RELEASE</version>
	</dependency>
	<!-- ************************************ -->
    <!-- Hibernate相关jar -->
    <dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-core</artifactId>
		<version>4.2.5.Final</version>
	</dependency>
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-ehcache</artifactId>
		<version>4.2.5.Final</version>
	</dependency>
	<dependency>
		<groupId>net.sf.ehcache</groupId>
		<artifactId>ehcache</artifactId>
		<version>2.7.2</version>
	</dependency>
	<dependency>
		<groupId>commons-dbcp</groupId>
		<artifactId>commons-dbcp</artifactId>
		<version>1.4</version>
	</dependency>
    <dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.26</version>
	</dependency>
	<!-- javax提供的annotation -->
	<dependency>
		<groupId>javax.inject</groupId>
		<artifactId>javax.inject</artifactId>
		<version>1</version>
	</dependency>        
	<!-- **************************** -->
    <!-- 用于对@ResponseBody注解的支持 -->
    <dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>        
    <!-- 提供对c标签的支持 -->
    <dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<!-- servlet api -->
	<dependency>
	  <groupId>javax.servlet</groupId>
	  <artifactId>servlet-api</artifactId>
	  <version>2.5</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>springmvc</finalName>
    <!-- maven的jetty服务器插件 -->
    <plugins>
    	<plugin>
		  <groupId>org.mortbay.jetty</groupId>
		  <artifactId>jetty-maven-plugin</artifactId>
		  <configuration>
		    <scanIntervalSeconds>10</scanIntervalSeconds>
		    <webApp>
		      <contextPath>/</contextPath>
		    </webApp>
		    <!-- 修改jetty的默认端口 -->
		    <connectors>
		       <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
		          <port>80</port>
		          <maxIdleTime>60000</maxIdleTime>
		       </connector>
		    </connectors>
		  </configuration>
		</plugin>
    </plugins>
  </build>
</project>

 

 webapp/WEB-INF/springmvc-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"
	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.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
	<context:component-scan base-package="com.cn.controller">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	
	<mvc:annotation-driven/>
	
	<!-- 静态资源 -->
	<mvc:resources location="/static/" mapping="/static/**"/>
	
	<!-- 视图控制器 -->
	<mvc:view-controller path="/" view-name="user/user"/>
	
	<!-- 视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

 

 webapp/WEB-INF/web.xml:

<?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>Archetype Created Web Application</display-name>
  
  <!-- spring-orm-hibernate4的OpenSessionInViewFilter -->
  <filter>
  	<filter-name>opensessioninview</filter-name>
  	<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>opensessioninview</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置springmvc servlet -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<!-- / 表示所有的请求都要经过此serlvet -->
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- spring的监听器 -->
  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  
</web-app>

 

 src/main/resources下的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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 自动扫描并管理类 -->
	<context:component-scan base-package="com.cn">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

	<!-- 加载classpath中的jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<!-- 基于Hibernate的事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 开启基于注解的事务管理器 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<!-- 实体类pojo所在包-->
		<property name="packagesToScan" value="com.cn.pojo"/>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
			</props>
		</property>
	</bean>
	
</beans>

 

 src/main/resources下的数据库连接配置文件:jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///log
jdbc.username=root
jdbc.password=root

 

 webapp/static/img/下的图片:1.jpg

 

 User:

package com.cn.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_user")
public class User {

	private Integer id;
	private String username;
	private String password;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	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;
	}
	
	
}

 

 BaseDao:

package com.cn.core.orm;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.inject.Inject;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.ResultTransformer;

@SuppressWarnings({"unchecked","unused"})
public class BaseDao<T,PK extends Serializable> {

	private Class<?> clazz;
	
	public BaseDao() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] types = type.getActualTypeArguments();
		clazz = (Class<?>) types[0];
	}
	
	private SessionFactory sessionFactory;
	
	@Inject
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public void save(T pojo) {
		getSession().saveOrUpdate(pojo);
	}
	
	public T findById(PK id) {
		return (T) getSession().get(clazz, id);
	}
	
	
	public T findByProperty(String propertyName,Object value) {
		Criteria c = getSession().createCriteria(clazz);
		c.add(Restrictions.eq(propertyName, value));
		return (T) c.uniqueResult();
	}
	
	public List<T> findListByProperty(String propertyName,Object value) {
		Criteria c = getSession().createCriteria(clazz);
		c.add(Restrictions.eq(propertyName, value));
		return c.list();
	}
	
	public void del(PK id) {
		getSession().delete(findById(id));
	}
	
	public List<T> findAll() {
		Criteria c = getSession().createCriteria(clazz);
		return c.list();
	}

}

 

 UserDao:

package com.cn.dao;

import javax.inject.Named;

import com.cn.core.orm.BaseDao;
import com.cn.pojo.User;

@Named
public class UserDao extends BaseDao<User, Integer>{

}

 

 UserService:

package com.cn.service;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.transaction.annotation.Transactional;

import com.cn.dao.UserDao;
import com.cn.pojo.User;

@Named
@Transactional
public class UserService {

	@Inject
	private UserDao userDao;

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

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

	public User findById(Integer id) {
		return userDao.findById(id);
	}

	public void del(Integer id) {
		userDao.del(id);
	}
}

 

 UserController:

package com.cn.controller;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cn.pojo.User;
import com.cn.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Inject
	private UserService userService;
	
	@RequestMapping
	public String show(Model model){
		List<User> userList=userService.findAll();
		model.addAttribute("userList", userList);
		return "user/user";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String addForm(){
		return "user/add";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(User user){
		userService.save(user);
		return "redirect:/user";
	}
	
	@RequestMapping(value="/edit/{id}",method=RequestMethod.GET)
	public String editForm(@PathVariable Integer id,Model model){
		System.out.println(id);
		User user=userService.findById(id);
		model.addAttribute("user", user);
		return "user/edit";
	}
	
	@RequestMapping(value="/del/{id}")
	public String del(@PathVariable Integer id){
		userService.del(id);
		return "redirect:/user";
	}
}

 

 webapp/WEB-INF/views/user/下的三个JSP文件:

 user.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户列表</title>
  </head>
  <body>
    <h1>用户列表---<a href="/user/add">添加用户</a></h1>
    <ul>
    	<c:forEach items="${userList }" var="user">
    		<li>用户名:${user.username }----密码:${user.password }----<a href="/user/edit/${user.id}">修改用户</a>----<a href="/user/del/${user.id }">删除用户</a></li>
    	</c:forEach>
    </ul>
    <img alt="" src="/static/img/1.jpg">
  </body>
</html>

 

 add.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>添加用户</title>
  </head>
  <body>
    <h1>添加用户</h1>
    <form action="/user/add" method="post">
    	用户名:<input type="text" name="username"/> <br/>
    	密 &nbsp;码:<input type="text" name="password"/> <br/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>

 

 edit.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>添加用户</title>
  </head>
  <body>
    <h1>添加用户</h1>
    <form action="/user/add" method="post">
    	<input type="hidden" name="id" value="${user.id }"/>
    	用户名:<input type="text" name="username" value="${user.username }"/> <br/>
    	密 &nbsp;码:<input type="text" name="password" value="${user.password }"/> <br/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>

 

 

  • SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
  • 大小: 16.1 KB
  • SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
  • 大小: 12.7 KB
  • SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
  • 大小: 208.4 KB
  • SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
  • 大小: 3.5 KB
  • SpringMVC_3.x_入门指南_4
            
    
    博客分类: SpringMVC SpringMVC连接Hibernate框架整合 
  • 大小: 101.7 KB

上一篇: 接口测试

下一篇: 接口测试