springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

项目开发环境

1.Eclipse

2.tomcat7.0

3.MySQL

项目的整体架构

所用到的jar包

数据库表

数据库表就不用教大家了,一张表,很简单的,下面是我建好的表

下面是web.xml的详情信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee" 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:spring/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <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: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>*.do</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>
  <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>

下面是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:aop="http://www.springframework.org/schema/aop"
  xmlns:cache="http://www.springframework.org/schema/cache"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:jms="http://www.springframework.org/schema/jms"
  xmlns:lang="http://www.springframework.org/schema/lang"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xmlns:task="http://www.springframework.org/schema/task"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!--扫描映射  -->
	<context:component-scan base-package="ssh"/>

	<!-- 引入property配置文件 -->
	<context:property-placeholder location="classpath:prop/jdbc.properties"/>

	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property>
		<property name="url" value="${jdbc.mysql.url}"></property>
		<property name="username" value="${jdbc.mysql.username}"></property>
		<property name="password" value="${jdbc.mysql.password}"></property>
		<!-- 初始化连接大小
		<property name="initialSize" value="${jdbc.initialSize}"></property> -->
		<!-- 连接池最大数量
		<property name="maxActive" value="${jdbc.maxActive}"></property>-->
		<!-- 连接池最大空闲 -->
		<!-- <property name="maxIdle" value="${maxIdle}"></property> -->
		<!-- 连接池最小空闲
		<property name="minIdle" value="${jdbc.minIdle}"></property>-->
		<!-- 获取连接最大等待时间
		<property name="maxWait" value="${jdbc.maxWait}"></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">${jdbc.mysql.dialect}</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!--是否显示sql语句 我在这里是显示的  -->
				<prop key="hibernate.show_sql">true</prop>
				<!--格式化显示sql语句  -->
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 自动扫描制定位置下的实体进行映射  -->
    	<property name="packagesToScan" value="ssh.entity"/>
	</bean>

	<!-- 配置一个事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

	<!-- 应该是开启事物 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

下面是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: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="ssh" />

	<!-- 开启注解 -->
	<mvc:annotation-driven />		

	<!-- 定义视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

Hibernate用于连接数据库的小配置文件jdbc.properties的详情信息

# JDBC
# 设置连接池连接时的数量
jdbc.initialSize=1
jdbc.filters=stat
# 连接池中存在的最小连接数目。连接池中连接数目可以变很少,如果使用了maxAge属性,有些空闲的连接会被关闭因为离它最近一次连接的时间过去太久了。但是,我们看到的打开的连接不会少于minIdle。
jdbc.minIdle=1
# 连接数据库的最大连接数。这个属性用来限制连接池中能够打开连接的数量,可以方便数据库做连接容量规划。
jdbc.maxActive=99
jdbc.maxWait=1000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.poolPreparedStatements=true
jdbc.maxPoolPreparedStatementPerConnectionSize=50
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.validationQuery=select 1 from dual

jdbc.removeAbandonedTimeout=150
jdbc.logAbandoned=true
jdbc.removeAbandoned=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false

#ORACLE 数据库连接方式
#jdbc.oracle.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.oracle.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
#jdbc.oracle.username=wrg
#jdbc.oracle.password=wrg
#jdbc.oracle.dialect=org.hibernate.dialect.Oracle10gDialect

# MYSQL 数据库连接方式
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3806/springmvc?characterEncoding=UTF-8
jdbc.mysql.username=root
jdbc.mysql.password=HZIMS_GP
jdbc.mysql.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

#HIBERNATE
jdbc.show_sql=false
jdbc.format_sql=false

下面是log4j.properties日志文件的详情信息

#console log
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n

#logger
log4j.logger.org.springframework=DEBUG,CONSOLE
log4j.logger.org.hibernate=INFO,CONSOLE
log4j.logger.org.apache=INFO,CONSOLE

log4j.rootLogger=DEBUG,CONSOLE

创建Entity类User实体

package ssh.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="TUSER")
public class User{
	@Id
	@GeneratedValue(generator="id")
	@GenericGenerator(name = "id",strategy="identity")
	private Integer id;
	private String name;
	private String password;
	@Column(name="LOGIN_DATE")
	private String loginDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer 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 String getLoginDate() {
		return loginDate;
	}
	public void setLoginDate(String loginDate) {
		this.loginDate = loginDate;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", loginDate=" + loginDate + "]";
	}

}

创建Dao层接口

package ssh.dao;
import java.util.List;
import ssh.entity.User;
public interface UserDao {
	//登录
	User selectUser(User user) throws Exception;
	//查询所有
	List<User> getAllUsers() throws Exception;
	//添加用户
	void addUser(User user) throws Exception;
	//删除用户
	void delUser(Integer id) throws Exception;
	//修改用户
	void updateUser(User user) throws Exception;
	//单个查询
	User getUser(Integer id) throws Exception ;
}

Dao层接口的实现

package ssh.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ssh.entity.User;
@Repository
@SuppressWarnings("unchecked")
public class UserDaoImpl implements UserDao {
	@Autowired
	private SessionFactory sessionFactory;
	//登录
	public User selectUser(User user) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name=? and u.password=?");
		query.setString(0, user.getName());
		query.setString(1, user.getPassword());
		List<User> list = query.list();
		if(list==null||list.size()==0){
			throw new RuntimeException("查询失败");
		}
		return list.get(0);
	}

	//查询所有
	public List<User> getAllUsers() throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from User");
		List<User> list = query.list();
		return list;
	}

	//单个查询
	public User getUser(Integer id) throws Exception {
		return (User) sessionFactory.getCurrentSession().createQuery("from User u where u.id ="+id).uniqueResult();
	}

	//添加用户
	public void addUser(User user) throws Exception {
		System.out.println("11111111111111111"+user.getName());
		sessionFactory.getCurrentSession().save(user);
	}

	//删除用户
	public void delUser(Integer id) throws Exception {
		sessionFactory.getCurrentSession().createQuery("delete User u where u.id="+id).executeUpdate();	   	

	}

	//修改用户
	public void updateUser(User user) throws Exception {
		 Session session = sessionFactory.getCurrentSession();
		 session.beginTransaction();
		 String hql = ("update User u set u.name = ?,u.password = ?,u.loginDate = ? where u.id = ?");
		 Query query = session.createQuery(hql);
		 query.setParameter(0, user.getName());
		 query.setParameter(1, user.getPassword());
		 query.setParameter(2, user.getLoginDate());
		 query.setParameter(3, user.getId());
		 query.executeUpdate();
		 session.getTransaction().commit();
	}
}

创建Service层的接口

package ssh.service;
import java.util.List;
import ssh.entity.User;
public interface UserService {
	//登录
	User selectUser(User user ) throws Exception;
	//查询所有
	List<User> getAllUsers() throws Exception;
	//添加用户
	void addUser(User user) throws Exception;
	//删除用户
	void delUser(Integer id) throws Exception;
	//修改用户
	void updateUser(User user) throws Exception;
	//单个查询
	User getUser(Integer id) throws Exception;
}

Service层的接口的实现

package ssh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssh.dao.UserDao;
import ssh.entity.User;
@Service("userService")
public class UserServiceImpl implements UserService{
	@Autowired
	private UserDao userDao;
	//登录
	public User selectUser(User user) throws Exception {
		return userDao.selectUser(user);
	}

	//单个查询
	public User getUser(Integer id) throws Exception {
		return userDao.getUser(id);
	}
	//查询所有
	public List<User> getAllUsers() throws Exception {
		List<User> users = userDao.getAllUsers();
		return users;
	}

	//添加用户
	public void addUser(User user) throws Exception {
		userDao.addUser(user);
	}
	//删除用户

	public void delUser(Integer id) throws Exception {
		userDao.delUser(id);
	}
	//修改用户
	public void updateUser(User user) throws Exception {
		userDao.updateUser(user);
	}
}

控制层Action层的代码如下

package ssh.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ssh.entity.User;
import ssh.path.Path;
import ssh.service.UserService;
@Controller
@RequestMapping(value=Path.USER)
public class UserAction {
	@Autowired
	private UserService userService;
	@RequestMapping(value=Path.LOGIN_INDEX)
	public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return Path.LOGIN_INDEX;
	}

	@RequestMapping(value=Path.LOGIN_OK,method=RequestMethod.POST)
	public String loginCheck(User user,HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setContentType("text/html;charset=utf-8");
		User u = userService.selectUser(user);
		System.out.println("user is ------------------------ "+u);
		request.setAttribute("user", u);
		return "redirect:/user/index.do";
		}

	//单个查询
	@RequestMapping(value=Path.GET_USER)
	public String getUser(Integer id,HttpServletRequest request) throws Exception{
	    request.setAttribute("user", userService.getUser(id));
	    return Path.UPDATE_USER;
	} 

	//查询所有
	@RequestMapping(value=Path.INDEX)
	public String getAllUsers(HttpServletRequest request) throws Exception{
		request.setAttribute("userList", userService.getAllUsers());
		return Path.INDEX;
	}
	//添加跳转方法
	@RequestMapping(value=Path.TO_ADDUSER)
	public String toAddUser(){
	    return Path.ADD_USER;
	}
	//添加用户
	@RequestMapping(value=Path.ADD_USER)
	public String addUser(User user,HttpServletRequest request) throws Exception{
		System.out.println("用户名:======"+user.getName());
		userService.addUser(user);
		return "redirect:/user/index.do";
	}

	//删除用户
	@RequestMapping(value=Path.DEL_USER)
	public String delUser(Integer id,HttpServletResponse response) throws Exception{
	    userService.delUser(id);
	    return "redirect:/user/index.do";
	}  

	//更新用户
	@RequestMapping(value=Path.UPDATE_USER)
	public String  updateUser(User user,HttpServletRequest request) throws Exception{

		userService.updateUser(user);
		user = userService .getUser(user.getId());
		request.setAttribute("user", user);
		return "redirect:/user/index.do";

	}
}

全局路径Path的代码

package ssh.path;
public class Path {
	public static final String USER = "/user";
	/**
	 * 登陆
	 */
	public static final String LOGIN_INDEX = "/login";
	/**
	 * 登陆成功
	 */
	public static final String LOGIN_OK = "/loginok";

	/**
	 * 查询所有
	 */
	public static final String INDEX = "/index";
	/**
	 * 添加用户
	 */
	public static final String ADD_USER = "/addUser";

	/**
	 * 跳转添加用户
	 */
	public static final String TO_ADDUSER = "/toaddUser";

	/**
	 * 删除用户
	 */
	public static final String DEL_USER = "/delUser";

	/**
	 * 更新用户
	 */
	public static final String UPDATE_USER = "/updateUser";

	/**
	 * 跳转更新用户
	 */
	public static final String GET_USER = "/getUser";
}

测试类Test的代码

package ssh.test;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import ssh.dao.UserDao;
import ssh.entity.User;
import ssh.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-common.xml")
@Transactional
/**
 *
 * @author hello
 *	说明:在这里 所有实例化的注解我都使用 @Autowrited (spring通用的)
 *						      也可以使用 @Resource   (J2EE通用的)
 *						      两者区别百度
 */
public class TestAll {
	@Autowired
	private SessionFactory sessionFactory;
	/**
	 * 测试sessionfactory
	 * 测试时 spring-common 不能存在 事物bean
	 * 					      不能存在 事物管理器 bean
	 * 					      不能存在dao
	 * 					      不能存在service
	 * 					      不能存在action
	 * 只是为了防止当其他内容写错时 sessionfactory也开启不了 除非是其他的bean没有错
	 */
	@Test
	public void testSf(){
		System.out.println("测试开启");
		System.out.println("   sessionfactory = "+sessionFactory);
		System.out.println("测试完成");
	}
	/**
	 * 测试UserDao
	 */
	@Autowired
	private UserDao userDao;
	@Test
	public void testUserDao() throws Exception{
		User u = new User();
		u.setName("admin");
		u.setPassword("12345678");
		User user  = userDao.selectUser(u);
		System.out.println("user is "+user);
		userDao.addUser(u);
	}
	/**
	 * 测试UserService
	 */
	@Autowired
	private UserService userService;
	@Test
	public void testUserService() throws Exception{
		User u = new User();
		u.setName("admin");
		u.setPassword("12345678");
		User user = userService.selectUser(u);
		System.out.println("user is "+user);
	}
}

登录界面login.jsp的代码

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" 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>
  <script type="text/javascript" src="../js/jquery-1.8.3.js"></script>
<style>
body{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
</style>
  <body>
  <div class="div">
  <h1>用户登录</h1>
    <form action="/spring_springmvc_hibernate/user/index.do" method="post">
    	用户名:<input  type="text" name="name" >
    	密码:<input  type="password" name="password">
    	<input type="submit" value="提交" >
    </form>
    </div>
  </body>
</html>

查询所有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>
<%
    String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path%>/js/jquery-1.9.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
body{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
.t{ margin:0 auto; width:600px; height:300px; border:1px solid #F00} 

</style> 

</head>
<body>
<div class="div">
    <h1><a href="/spring_springmvc_hibernate/user/toaddUser.do">添加用户</a></h1>
    <table border="1" class="t">
        <tbody>
        <tr>
            <th>姓名</th>
            <th>密码</th>
            <th>登录时间</th>
            <th>操作</th>
        </tr>
        <c:if test="${!empty userList }">
            <c:forEach items="${userList}" var="user">
                <tr>
                	<td>${user.name }</td>
                    <td>${user.password }</td>
                    <td>${user.loginDate }</td>
                    <td>
                        <a href="/spring_springmvc_hibernate/user/getUser.do?id=${user.id }">编辑</a>
                        <a href="/spring_springmvc_hibernate/user/delUser.do?id=${user.id }">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </c:if>
    </tbody>
   </div>
</table>
</body>
</html>  

添加用户addUser.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
body{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
</style>
<script type="text/javascript">
function addUser(){
    var form = document.forms[0];
    form.action = "/spring_springmvc_hibernate/user/addUser.do";
    form.method="post";
    form.submit();
}
</script>
</head>
<body>
<div class="div">
<h1>添加用户</h1>
<form action="" name="userForm"> 

    姓名:<input type="text" name="name">
    密码:<input type="text" name="password">
    时间:<input type="text" name="loginDate">
    <input type="button" value="添加" onclick="addUser()">
</form>
</div>
</body>
</html>  

更新数据updateUser.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>
<%
String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
body{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
</style>
</head>
<body>
<div class="div">
<h1>编辑用户</h1>
<form action="/spring_springmvc_hibernate/user/updateUser.do" name="userForm" method="post">
  <input type="hidden" name="id" value="${user.id }">
    姓名:<input type="text" name="name" value="${user.name }">
    密码:<input type="text" name="password" value="${user.password }">
    时间:<input type="text" name="loginDate" value="${user.loginDate }">
    <input type="submit" value="编辑" >
</form>
</div>
</body>
</html> 

用户登录界面

查询所有界面

编辑用户页面

添加用户页面

删除就不说了,点击删除自动回到查询所有的界面

以上就是所有关于三大框架整合的所有代码

项目源码下载

http://download.csdn.net/detail/qq_34413570/9516697导入就可以运行

时间: 2024-10-07 22:59:12

springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能的相关文章

Mybatis简单的入门之增删改查

一般的步骤如下 1.添加Mybatis所需要的包,和连接数据库所需的包 2.配置mybatis-config.xml文件 3.配置与pojo对应的映射文件 mybatis-config,xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http:/

SpringMVC+Spring3+Hibernate4框架搭建

MVC已经是现代Web开发中的一个很重要的部分,下面介绍一下SpringMVC+Spring3+Hibernate4的开发环境搭建 先大致看一下项目结构: 具体的代码不再演示,主要是走了一个很平常的路线,mvc-servcie-dao-hibernate的结构,源码可以下载,主要看一下配置文件.解释见注释 web.xml [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?>

Struts2+Spring+Hibernate实现员工管理增删改查功能(一)之ssh框架整合

前言        转载请标明出处:http://www.cnblogs.com/smfx1314/p/7795837.html 本项目是我写的一个练习,目的是回顾ssh框架的整合以及使用.项目介绍:此项目主要有前台管理员通过登录进入员工管理系统页面,之后可以对员工列表进行常规的增删改查.以及部门列表的增删改查.IDE使用的是eclipse,个人感觉比较好用,不过最近我正在研究idea,数据库是mysql,前台主要以bootstrap为主. 这点是直接摘抄的 struts 控制用的 hibern

springboot整合mybatis, 增删改查

这篇文章是介绍 Spring Boot整合mybatis的,一个简单的增删改查. 建表DROP TABLE IF EXISTS tbl_user; CREATE TABLE tbl_user ( id int(11) NOT NULL AUTO_INCREMENT, user_name varchar(255) NOT NULL, password varchar(255) NOT NULL, age int(11) DEFAULT NULL, PRIMARY KEY (id)) ENGINE=

SSM框架+thymeleaf实现基本的增删改查

前言 本文使用了SSM框架.thymeleaf和jquery实现了基本的增删改查. 名词解释 SSM框架:springMVC.spring.mybatis thymeleaf:一个与Velocity.FreeMarker类似的模板引擎 jquery:一个快速.简洁的JavaScript框架 程序结构 本程序框架是用maven建出来的,具体如图: 程序源码 pom.xml <?xml version="1.0" encoding="UTF-8"?> <

上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。

1.引入依赖 <!--springboot的web起步依赖--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> <!-- Mybatis起步依赖 --> <dependency> <groupId>o

基于MVC和Bootstrap的权限框架解决方案 二.添加增删改查按钮

上一期我们已经搭建了框架并且加入了列表的显示, 本期我们来加入增删改查按钮 整体效果如下 HTML部分,在HTML中找到中意的按钮按查看元素,复制HTML代码放入工程中 <a class="btn btn-small element" data-original-title="新增" href="/Customer/Add" data-toggle="tooltip" data-placement="top&q

CI框架之简单demo 新闻条目增删改查

从CI官网下载CI源码,在Netbeans里面新建一个项目,并把CI源码添加到htdocs目录里面,修改Apache的http—conf文件. 1.加载静态内容 在控制器里面新建一个pages.php页面,添加如下代码: <?php class Pages extends CI_Controller{ public function view($page='home'){ } } 在view视图目录下面创建一个templates 目录,里面存放页面模板 一个是页头文件header.php <h

简单的JDBC的增删改查操作-&gt;抽取了基类,附源码

1.主程序 1 package com.xyyz.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 8 import com.xyyz.utils.JDBCUtils; 9 10 public class JDBCDemo { 11 12 public static vo