springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能
项目开发环境
1.Eclipse
2.tomcat7.0
3.MySQL
项目的整体架构
所用到的jar包
数据库表
数据库表就不用教大家了,一张表,很简单的,下面是我建好的表
下面是web.xml的详情信息
json_test
login.jsp
contextConfigLocation
classpath:spring/spring-*.xml
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/spring-mvc.xml
1
springMVC
*.do
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
openSession
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
openSession
/*
下面是spring-common.xml的详情信息
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">
${jdbc.mysql.dialect}
update
true
true
下面是spring-mvc.xml的详情信息
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">
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 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 list = query.list();
if(list==null||list.size()==0){
throw new RuntimeException("查询失败");
}
return list.get(0);
}
//查询所有
public List getAllUsers() throws Exception {
Query query = sessionFactory.getCurrentSession().createQuery("from User");
List 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 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 getAllUsers() throws Exception {
List 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的代码
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
body{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
用户登录
用户名:
密码:
查询所有index.jsp页面的代码
pageEncoding="UTF-8"%>
String path = request.getContextPath();
%>
Insert title herebody{ 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}
添加用户
姓名 | 密码 | 登录时间 | 操作 |
---|---|---|---|
${user.name } | ${user.password } | ${user.loginDate } |
添加用户addUser.jsp的页面代码
pageEncoding="UTF-8"%>
Insert title herebody{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
function addUser(){
var form = document.forms[0];
form.action = "/spring_springmvc_hibernate/user/addUser.do";
form.method="post";
form.submit();
}
添加用户
姓名:
密码:
时间:
更新数据updateUser.jsp的页面代码
pageEncoding="UTF-8"%>
String path = request.getContextPath();
%>
Insert title herebody{ text-align:center}
.div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}
/* css注释:为了观察效果设置宽度 边框 高度等样式 */
编辑用户
姓名:
密码:
时间:
用户登录界面
查询所有界面
编辑用户页面
添加用户页面
删除就不说了,点击删除自动回到查询所有的界面
以上就是所有关于三大框架整合的所有代码
项目源码下载:http://download.csdn.net/detail/qq_34413570/9516908