springMVC +spring +hibrnate集成

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/45038301

项目结构:

  springMVC +spring +hibrnate集成

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">
	
	<!-- tomcat对里面的加载顺序:Context-Param—->Listener—->filter—->servlet -->
	<!-- 加载所有的配置文件 -->
	<context-param>
	      <param-name>contextConfigLocation</param-name>
	      <param-value>classpath*:config/spring-*.xml</param-value>
	</context-param>
	
	<!-- 配置Spring监听器 -->
	<listener>
	      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 配置字符集 -->
	<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>
	
	<!-- 配置Session -->
	  <filter>
	      <filter-name>openSession</filter-name>
	      <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
	      <init-param>
	          <param-name>sessionFactoryBeanName</param-name>
	          <param-value>sessionFactory</param-value>
	      </init-param>
	  </filter>
	
	<filter-mapping>
	    <filter-name>openSession</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 配置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*:config/spring-mvc.xml</param-value>
	     </init-param>
	</servlet>
	<servlet-mapping>
	   <servlet-name>springMVC</servlet-name>
	   <url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	
	<!-- 引用js,如果无此配置,则无法对js进行加载 -->
		<servlet-mapping>
		    <servlet-name>default</servlet-name>
		    <url-pattern>*.js</url-pattern>
		</servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
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: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">  

<bean id="userDao" class="com.springmvc.dao.UserDaoImpl">
   <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
   <bean id="userManagerBase" class="com.springmvc.service.UserManagerImpl">
       <property name="userDao" ref="userDao"></property>
   </bean>
   <bean name="userManager" parent="transactionProxy">
       <property name="target" ref="userManagerBase"></property>
   </bean>


</beans>
集成hibernate的配置文件spring-common.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">



<!-- 配置数据源 -->
<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/mydata"></property>
     <property name="username" value="root"></property>
     <property name="password" value="123456"></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">update</prop>
                   <prop key="hibernate.show_sql">true</prop>
                   <prop key="hibernate.format_sql">true</prop>
              </props>
           </property>
          
          <!-- 注解扫描的包 -->
          <property name="annotatedClasses">
              <list>
                  <value>com.springmvc.entity.User</value>
              </list>
          </property>             
      </bean>
      
        <!-- 配置一个事务管理 -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
           <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
      <!-- 配置事务,使用代理的方式 -->
      <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
        <property name="transactionManager" ref="transactionManager"></property>
        <property name="transactionAttributes">
           <props>
                  <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                  <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
                  <prop key="del*">PROPAGATION_REQUIRED</prop>
                  <prop key="*">PROPAGATION_REQUIRED</prop>
           </props>
        </property>
      </bean>
       
</beans>

springmvc的配置文件spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" 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">
                    
      <!-- 注解扫描包 -->              
                    <context:component-scan base-package="com.springmvc.*"></context:component-scan>
         <!-- 开启注解 -->
                    <mvc:annotation-driven/>
          <!-- 静态资源的访问 -->
         
       <!-- <mvc:resource location="/js/" mapping="/js/**"></mvc:resource>-->
          
          <!-- 定义视图解析器 -->
          <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/jsp/"></property>
              <property name="suffix" value=".jsp"></property>
          </bean>
          
 </beans>
实体类:

package com.springmvc.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 org.hibernate.annotations.GenericGenerator;


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

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="id")
	private Integer id;
	
	public Integer getId() {
		return id;
	}

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

	private String userName;
	
	private String age;
	
	
	

	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.springmvc.dao;

import java.util.List;

import com.springmvc.entity.User;

public interface  UserDao {
      public User getUser(Integer id);
      public List<User> getAllUser();
      public void addUser(User user);
      public boolean delUser(Integer id);
      public boolean updateUser(User user);
}

dao实现类:
package com.springmvc.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.springmvc.entity.User;

public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

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

	/**
	 * 根据用户id删除用户
	 */
	public boolean delUser(Integer id) {
		String hql="delete User u where u.id=?";
	    Query query=sessionFactory.getCurrentSession().createQuery(hql);
	   // query.setString(0,id);
	    query.setInteger(0,id);
		return (query.executeUpdate()>0);
	}

	/**
	 * 查询所有用户
	 */
	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		String hql="from User";
	    Query quesy=sessionFactory.getCurrentSession().createQuery(hql);
		return quesy.list();
	}

	
	/**
	 * 根据用户id查询s
	 */
	public User getUser(Integer id) {
		String hql="from User u where u.id=?";
	    Query query=sessionFactory.getCurrentSession().createQuery(hql);
	    //query.setString(0, id);
	    query.setInteger(0,id);
		return (User)query.uniqueResult();
	}

	/**
	 * 编辑用户
	 */
	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.setInteger(2, user.getId());
	    //query.setString(2, user.getId());
	   return (query.executeUpdate()>0);
	}

}
service业务层接口:

package com.springmvc.service;

import java.util.List;

import com.springmvc.entity.User;

public interface UserManager {
      public User getUser(Integer id);
      public List<User> getAllUser();
      public void addUser(User user);
      public boolean delUser(Integer id);
      public boolean updateUser(User user);
}

service层实现类:

package com.springmvc.service;

import java.util.List;

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

public class UserManagerImpl implements UserManager {

	private UserDao userDao;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

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

	@Override
	public boolean delUser(Integer id) {
		
		return userDao.delUser(id);
	}

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

	@Override
	public User getUser(Integer id) {
		return userDao.getUser(id);
	}

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

}

controller控制层:
package com.springmvc.controller;

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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springmvc.entity.User;
import com.springmvc.service.UserManager;


@Controller
@RequestMapping("/user")
public class UserController {
   
	@Resource(name="userManager")
	private UserManager userManager;   
	
	
	@RequestMapping("/login.do")
	public String toLogin(){
		return "Login";
	}
	
	@RequestMapping("/getAllUser.do")
	public String getAllUser(Model model){
		 model.addAttribute("userList", userManager.getAllUser());
		return "/Index";
	}
	
	@RequestMapping("/getUser.do")
	public String getUser(int id,HttpServletRequest request){
		request.setAttribute("user",userManager.getUser(id));
		return "editUser";
	}
	
	@RequestMapping("/toAddUser.do")
	public String toAddUser(){
	    return "/addUser";	
	}
	
	@RequestMapping("/addUser")
	public String addUser(User user,HttpServletRequest request){
		System.out.println("用户名:"+user.getUserName());
		userManager.addUser(user);
		return "redirect:/user/getAllUser.do";
	}
	
	@RequestMapping("/delUser.do")
	public void delUser(int id,HttpServletResponse response){
		String result="{\"result\":\"error\"}";
		if(userManager.delUser(id)){
			result="{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
	   try {
		  PrintWriter out=response.getWriter();
		   out.write(result);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	  
	}
	
	@RequestMapping("/updateUser.do")
	public String updateUser(User user,HttpServletRequest request){
		if(userManager.updateUser(user)){
		    user=userManager.getUser(user.getId());
		    request.setAttribute("user",user);
		    return "redirect:/user/getAllUser.do";
		}else{
			return "/error";
		}
		
	}
	
}

视图页面:login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
     <h4><a href="<%=request.getContextPath()%>/user/getAllUser.do">点击进入用户管理页面</a></h4>
  </body>
</html>
列表页面:

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Index.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript">
            function del(id){
                      if(confirm("你确定要删除吗?")){
                          $.get(
                             "user/delUser.do?id="+id,
                              function(data){
                                  if("success"==data.result){
                                      alert("删除成功");
                                       window.location.reload();
                                  }else{
                                      alert("删除失败");
                                  }
                              }
                          );
                           
                      }
              
               
            }
    </script>
  </head>
  
  <body>
     <h5><a href="user/toAddUser.do">添加用户</a></h5>
     <table border="1" cellpadding="0" cellspacing="0">
            <thead>用户信息列表</thead>
            <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="user/getUser.do?id=${user.id}">编辑</a>
                                   <a href="javascript:del('${user.id }')">删除</a>
                               </td>
                           </tr>
                      </c:forEach>
                </c:if>
            </tbody>
     </table>
     
     
  </body>
</html>
增加页面addUser.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'addUser.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <form action="user/addUser.do" method="post">
        姓名:<input type="text" name="userName"/><br/>
        年龄:<input type="text" name="age"/><br/>
        <input type="submit" value="添加"/>
    </form>
  </body>
</html>
编辑页面editUser.jsp:

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'editUser.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
      <h2>编辑用户</h2>
      <form action="user/updateUser.do" method="post">
        <input type="hidden" name="id" value="${user.id}"/>
         姓名:<input type="text" name="userName" value="${user.userName }"/><br/>
        年龄:<input type="text" name="age" value="${user.age }"/>
        <input type="submit" value="编辑"/>
      </form>
  </body>
</html>

js和jsp文件:

springMVC +spring +hibrnate集成


各种包图:

springMVC +spring +hibrnate集成


上一篇:开放API接口 笑话、天气、新闻


下一篇:Spring配置中transactionAttributes的使用方法和作用