Spring+SpringMVC+Hibernate简单整合(转)
SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,下面同样做一个简单的应用实例,介绍SpringMVC的基本用法,接下来的博客也将梳理一下Struts2和SpringMVC的一些异同,通过梳理和旧知识的联系,让学习的成本变低,花很短的时间就可以了解一门貌似新的技术,其实本质没变。
原文http://langgufu.iteye.com/blog/2088355
下面开始实例,这个实例的需求是对用户信息进行增删改查。首先创建一个web项目test_ssh,目录结构及需要的Jar包如下图:
创建一个User实体类,放在Entity包下,采用注解的方式:
- package com.tgb.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;
- @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(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;
- }
- }
本篇关于SpringMVC基本都会采用注解的方式,首先配置好数据源以及事务spring-common.xml,放在config.spring包下:
- <?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/test_ssh"></property>
- <property name="username" value="root"></property>
- <property name="password" value="1"></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.tgb.entity.User</value>
- </list>
- </property>
- </bean>
- <!-- 配置一个事务管理器 -->
- <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"/>
- </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放在config.spring包下:
- <?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-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
- <!-- 注解扫描包 -->
- <context:component-scan base-package="com.tgb" />
- <!-- 开启注解 -->
- <mvc:annotation-driven />
- <!-- 静态资源(js/image)的访问 -->
- <mvc:resources location="/js/" mapping="/js/**"/>
- <!-- 定义视图解析器 -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
- </beans>
完成这些共用的配置之后,来配置web项目起点web.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>json_test</display-name>
- <welcome-file-list>
- <welcome-file>login.jsp</welcome-file>
- </welcome-file-list>
- <!-- 加载所有的配置文件 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath*:config/spring/spring-*.xml</param-value>
- </context-param>
- <!-- 配置Spring监听 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 配置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/spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 配置字符集 -->
- <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>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</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>
- </filter>
- <filter-mapping>
- <filter-name>openSession</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
读者需自行下载jquery包,放到webContent文件夹下的js包下。然后创建几个测试页面,分别如下:
Login.jsp,项目的入口界面。
- <h5><a href="/test_ssh/user/getAllUser">进入用户管理页</a></h5>
Index.jsp,用户管理的主界面
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <!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="../js/jquery-1.7.1.js"></script>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript">
- function del(id){
- $.get("/test_ssh/user/delUser?id=" + id,function(data){
- if("success" == data.result){
- alert("删除成功");
- window.location.reload();
- }else{
- alert("删除失败");
- }
- });
- }
- </script>
- </head>
- <body>
- <h6><a href="/test_ssh/user/toAddUser">添加用户</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="/test_ssh/user/getUser?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" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!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>Insert title here</title>
- <script type="text/javascript">
- function addUser(){
- var form = document.forms[0];
- form.action = "/test_ssh/user/addUser";
- form.method="post";
- form.submit();
- }
- </script>
- </head>
- <body>
- <h1>添加用户</h1>
- <form action="" name="userForm">
- 姓名:<input type="text" name="userName">
- 年龄:<input type="text" name="age">
- <input type="button" value="添加" onclick="addUser()">
- </form>
- </body>
- </html>
editUser.jsp,修改用户信息界面。
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <!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="../js/jquery-1.7.1.js"></script>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h1>编辑用户</h1>
- <form action="/test_ssh/user/updateUser" name="userForm" method="post">
- <input type="hidden" name="id" value="${user.id }">
- 姓名:<input type="text" name="userName" value="${user.userName }">
- 年龄:<input type="text" name="age" value="${user.age }">
- <input type="submit" value="编辑" >
- </form>
- </body>
- </html>
还有success.jsp和error.jsp页面,无代码,就不再展示。
框架越来越多,越来越好用,但随之而来的繁杂的、各成体系的配置怎么办?项目大了感觉注解靠谱些。
这篇接着上篇,把没贴完的代码写完,上篇主要完成了一些公共配置和界面的东西,这篇把后台的代码完成。
首先是web包下属于的control层的类UserController,这相当于Struts中的Action,是重要的类:
- package com.tgb.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.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.tgb.entity.User;
- import com.tgb.manager.UserManager;
- @Controller
- @RequestMapping("/user")
- public class UserController {
- @Resource(name="userManager")
- private UserManager userManager;
- @RequestMapping("/getAllUser")
- public String getAllUser(HttpServletRequest request){
- request.setAttribute("userList", userManager.getAllUser());
- return "/index";
- }
- @RequestMapping("/getUser")
- public String getUser(String id,HttpServletRequest request){
- request.setAttribute("user", userManager.getUser(id));
- return "/editUser";
- }
- @RequestMapping("/toAddUser")
- public String toAddUser(){
- return "/addUser";
- }
- @RequestMapping("/addUser")
- public String addUser(User user,HttpServletRequest request){
- userManager.addUser(user);
- return "redirect:/user/getAllUser";
- }
- @RequestMapping("/delUser")
- public void delUser(String 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")
- public String updateUser(User user,HttpServletRequest request){
- if(userManager.updateUser(user)){
- user = userManager.getUser(user.getId());
- request.setAttribute("user", user);
- return "redirect:/user/getAllUser";
- }else{
- return "/error";
- }
- }
- }
然后是属于manager包下的业务逻辑类,接口UserManager:
- package com.tgb.manager;
- import java.util.List;
- import com.tgb.entity.User;
- public interface UserManager {
- public User getUser(String id);
- public List<User> getAllUser();
- public void addUser(User user);
- public boolean delUser(String id);
- public boolean updateUser(User user);
- }
实现类UserManagerImpl:
- package com.tgb.manager;
- import java.util.List;
- import com.tgb.dao.UserDao;
- import com.tgb.entity.User;
- public class UserManagerImpl implements UserManager {
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- @Override
- public User getUser(String id) {
- return userDao.getUser(id);
- }
- @Override
- public List<User> getAllUser() {
- return userDao.getAllUser();
- }
- @Override
- public void addUser(User user) {
- userDao.addUser(user);
- }
- @Override
- public boolean delUser(String id) {
- return userDao.delUser(id);
- }
- @Override
- public boolean updateUser(User user) {
- return userDao.updateUser(user);
- }
- }
最后是属于dao包底下的DAO层,主要由Hibernate完成。接口UserDao:
- package com.tgb.dao;
- import java.util.List;
- import com.tgb.entity.User;
- public interface UserDao {
- public User getUser(String id);
- public List<User> getAllUser();
- public void addUser(User user);
- public boolean delUser(String id);
- public boolean updateUser(User user);
- }
实现类UserDaoImpl:
- package com.tgb.dao;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.SessionFactory;
- import com.tgb.entity.User;
- public class UserDaoImpl implements UserDao {
- private SessionFactory sessionFactory;
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- @Override
- 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();
- }
- @Override
- public List<User> getAllUser() {
- String hql = "from User";
- Query query = sessionFactory.getCurrentSession().createQuery(hql);
- return query.list();
- }
- @Override
- public void addUser(User user) {
- sessionFactory.getCurrentSession().save(user);
- }
- @Override
- public boolean delUser(String id) {
- String hql = "delete User u where u.id = ?";
- Query query = sessionFactory.getCurrentSession().createQuery(hql);
- query.setString(0, id);
- return (query.executeUpdate() > 0);
- }
- @Override
- 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);
- }
- }
最后外加一个配置spring-beans.xml,放在config.spring包下,负责为各层依赖注入需要的对象:
- <?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.tgb.dao.UserDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- <bean id="userManagerBase" class="com.tgb.manager.UserManagerImpl">
- <property name="userDao" ref="userDao"></property>
- </bean>
- <!-- 此处为代理 -->
- <bean name="userManager" parent="transactionProxy">
- <property name="target" ref="userManagerBase"></property>
- </bean>
- </beans>
到此为止,所有的配置和代码完成,部署—运行,运行结果如下图:
Spring+SpringMVC+Hibernate简单整合(转)的更多相关文章
- spring+springMVC+mybatis简单整合
spring+springMVC+mybatis简单整合, springMVC框架是spring的子项目,所以框架的整合方式为,spring+Mybatis或springMVC+mybatis. 三大 ...
- SSH(Spring SpringMVC Hibernate)框架整合
项目说明: 使用SSH(Spring SpringMVC Hibernate)框架整合添加部门功能 项目结构 1.导入依赖jar包 <!--单测--> <dependency&g ...
- Spring+SpringMvc+Hibernate整合记录
Spring+SpringMvc+Hibernate+Maven整合各大配置文件记录 1.Idea新建的Maven架构 2.Maven的对象模型的内容 <project xmlns=" ...
- 框架篇:Spring+SpringMVC+hibernate整合开发
前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...
- Spring+SpringMVC+Hibernate 与 shiro 整合步骤
目录 1. 业务需求分析 2. 创建数据库 3. 创建 maven webapp 工程 4. 创建实体类(POJO) 5. 配置 Hibernate 和 Mapping 5.1 Hibernate 主 ...
- springmvc框架(Spring SpringMVC, Hibernate整合)
直接干货 model 考虑给用户展示什么.关注支撑业务的信息构成.构建成模型. control 调用业务逻辑产生合适的数据以及传递数据给视图用于呈献: view怎样对数据进行布局,以一种优美的方式展示 ...
- spring+springmvc+hibernate 整合
三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高.最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来. 工具:Eclipse(jdk 1.7) spring和hibernate版 ...
- Spring MVC基础知识整理➣Spring+SpringMVC+Hibernate整合操作数据库
概述 Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据.Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD.Hibern ...
- spring+springmvc+hibernate整合遇到的问题
spring+springmvc+hibernate整合遇到的问题2016年10月20日 23:24:03 守望dfdfdf 阅读数:702 标签: ssh学习经历的异常exception异常框架更多 ...
随机推荐
- 记录一次bug解决过程:数据迁移
一 总结 不擅长语言表达,勤于沟通,多锻炼 调试MyBatis中SQL语法:foreach 问题:缺少关键字VALUES.很遗憾:它的错误报的让人找不着北. 二 BUG描述:MyBatis中批量插入数 ...
- JavaScript学习笔记(一)——延迟对象、跨域、模板引擎、弹出层、AJAX示例
一.AJAX示例 AJAX全称为“Asynchronous JavaScript And XML”(异步JavaScript和XML) 是指一种创建交互式网页应用的开发技术.改善用户体验,实现无刷新效 ...
- NPM如何更新到最新版
参考文章--npm更新到最新版本的方法 其实我们可以这样,随便新建一个文件夹例如:F:\test.按着"shift"键,右键该文件夹,选择"在此处打开命令窗口(W)&qu ...
- Android中Activity处理返回结果的实现方式
大家在网上购物时都有这样一个体验,在确认订单选择收货人以及地址时,会跳转页面到我们存入网站内的所有收货信息(包含收货地址,收货人)的界面供我们选择,一旦我们点击其中某一条信息,则会自动跳转到订单提交界 ...
- django 学习第一天搭建环境
目前django版本是1.10,我学习的基础教材是 Web Development with Django Cookbook, Second Edition 搭建好配置环境 ssh免认证登录 修改一下 ...
- MySQL常用命令
数据库登陆命令: mysql -uroot -p 2.提示输入密码: 3.登陆成功: 4.数据库修改相关命令: 修改数据库的编码格式: 语法格式为:ALTER {DATABASE|SCHEMA} [ ...
- MongoDB学习笔记六—查询下
查询内嵌文档 数据准备 > db.blog.find().pretty() { "_id" : ObjectId("585694e4c5b0525a48a441b5 ...
- CentOS 7 修改主机名
今天在阿里云上买了一个centos7的服务器,连接上以后,发现一个很长很长的主机名,看着让人很是不爽,就想着怎样将其改成一个有个性的名字. 这里我想说的是,在centos7 版本的linux系统上和c ...
- 类型转换器(InitBinder 初始化绑定器)
单日期格式 导入jar包 创建FirstController.java @Controller public class FirstController { /** * @param binder * ...
- 在Ubuntu13.04中配置Jexus+Mono3.2运行Asp.Net Mvc 4站点 (一)
这篇文章打算分两部分来写,第一部分介绍在Ubuntu中安装和配置.Net Framework4.5环境,第二部分介绍如何部署Asp.Net Mvc 4站点并确保Mvc4的几个重要特性都能正常工作. 一 ...