springMVC +spring +hibrnate集成

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

项目结构:

 

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文件:


各种包图:


相关文章
|
1月前
|
Java Maven Docker
gitlab-ci 集成 k3s 部署spring boot 应用
gitlab-ci 集成 k3s 部署spring boot 应用
|
3月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
定时任务在企业应用中至关重要,常用于异步数据处理、自动化运维等场景。在单体应用中,利用Java的`java.util.Timer`或Spring的`@Scheduled`即可轻松实现。然而,进入微服务架构后,任务可能因多节点并发执行而重复。Spring Cloud Alibaba为此发布了Scheduling模块,提供轻量级、高可用的分布式定时任务解决方案,支持防重复执行、分片运行等功能,并可通过`spring-cloud-starter-alibaba-schedulerx`快速集成。用户可选择基于阿里云SchedulerX托管服务或采用本地开源方案(如ShedLock)
111 1
|
26天前
|
前端开发 Java 程序员
springboot 学习十五:Spring Boot 优雅的集成Swagger2、Knife4j
这篇文章是关于如何在Spring Boot项目中集成Swagger2和Knife4j来生成和美化API接口文档的详细教程。
47 1
|
27天前
|
JSON 前端开发 Java
SSM:SpringMVC
本文介绍了SpringMVC的依赖配置、请求参数处理、注解开发、JSON处理、拦截器、文件上传下载以及相关注意事项。首先,需要在`pom.xml`中添加必要的依赖,包括Servlet、JSTL、Spring Web MVC等。接着,在`web.xml`中配置DispatcherServlet,并设置Spring MVC的相关配置,如组件扫描、默认Servlet处理器等。然后,通过`@RequestMapping`等注解处理请求参数,使用`@ResponseBody`返回JSON数据。此外,还介绍了如何创建和配置拦截器、文件上传下载的功能,并强调了JSP文件的放置位置,避免404错误。
|
1月前
|
前端开发 Java 应用服务中间件
【Spring】Spring MVC的项目准备和连接建立
【Spring】Spring MVC的项目准备和连接建立
52 2
|
1月前
|
存储 前端开发 Java
Spring Boot 集成 MinIO 与 KKFile 实现文件预览功能
本文详细介绍如何在Spring Boot项目中集成MinIO对象存储系统与KKFileView文件预览工具,实现文件上传及在线预览功能。首先搭建MinIO服务器,并在Spring Boot中配置MinIO SDK进行文件管理;接着通过KKFileView提供文件预览服务,最终实现文档管理系统的高效文件处理能力。
221 11
|
2月前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
1月前
|
XML 前端开发 Java
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
本文阐述了Spring、Spring Boot和Spring MVC的关系与区别,指出Spring是一个轻量级、一站式、模块化的应用程序开发框架,Spring MVC是Spring的一个子框架,专注于Web应用和网络接口开发,而Spring Boot则是对Spring的封装,用于简化Spring应用的开发。
93 0
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
|
2月前
|
XML 缓存 前端开发
springMVC02,restful风格,请求转发和重定向
文章介绍了RESTful风格的基本概念和特点,并展示了如何使用SpringMVC实现RESTful风格的请求处理。同时,文章还讨论了SpringMVC中的请求转发和重定向的实现方式,并通过具体代码示例进行了说明。
springMVC02,restful风格,请求转发和重定向
|
26天前
|
Java Spring
springboot 学习十一:Spring Boot 优雅的集成 Lombok
这篇文章是关于如何在Spring Boot项目中集成Lombok,以简化JavaBean的编写,避免冗余代码,并提供了相关的配置步骤和常用注解的介绍。
75 0

热门文章

最新文章