使用maven搭建spring+springMVC+hibernate框架

上一篇是使用maven搭建web项目接下来整合spring、springMVC以及hiebrnate,其中主要就是配置文件的问题,pom文件等。
本篇是使用spring-version为4.3.3.RELEASE,hibernate-version为4.2.21.Final
这里直接贴上pom文件,包括spring,springMVC,hibernate,mysql等完整配置,并且包括EntityManage(接下来会使用的)
第一步:添加spring和springMVC以及hibernate的配置文件
1、配置spring,hibernate,添加application.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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.mvn" />
    <!-- 配置自动aop -->
    <aop:aspectj-autoproxy />
    
    <!-- 自动读取配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">

        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- 配置sessionFactory-->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- hibernate自动扫描 实体类-->
        <property name="annotatedClasses">
            <list>
                <value>com.mvn.entity.User</value>
            </list>
        </property>
        <!-- hibernate属性 -->
        <property name="hibernateProperties">
             <props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
        </property>
        
    </bean>
    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
  

</beans>

2、配置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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 自动扫描 com.mvn.controller的文件,初始化处理器-->
    <context:component-scan base-package="com.mvn.controller" />
    
    <!-- 配置试图解析器(渲染器) -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
	
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

3、这里贴上完整的web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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_3_0.xsd">

	<display-name>test-ssh</display-name>
	<welcome-file-list>
		<welcome-file>success.jsp</welcome-file>
	</welcome-file-list>
	
	<!-- 配置spring context需要读取的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring listener 以便在web容器启动的时候能自动初始化spring -->
    <listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
    
    <!-- 配置spring mvc 分发器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 初始化spring mvc 配置文件的位置 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- web容器启动的时候就加载springmvc -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
</web-app>

4、以及jdbc.properties配置文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=utf8
jdbc.username=root
jdbc.password=1234

jdbc.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
jdbc.hibernate.show_sql=true
jdbc.hibernate.hbm2ddl.auto=update

这里连接数据库需要改成自己的。

第二步:编写java和jsp代码
1、实体类,com.mvn.entity,User.java

package com.mvn.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

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

    private Integer id;
    private String name;
    private String password;
    
    @Id
    @GeneratedValue
    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;
    }
    
}

2、dao接口,com.mvn.dao,UserDao.java

package com.mvn.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.mvn.entity.User;

@Repository
public interface UserDao {

 public void save(User user);
 
 public User find(int id);
 
 public void del(int id);
 
 public User update(User user);
 
 public List<User> getAll();
}

3、dao的实现类,com.mvn.dao.impl,UserDaoImpl.java

package com.mvn.dao.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class UserDaoImpl implements UserDao{

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public void save(User user) {
		Session session = sessionFactory.openSession();
		session.save(user);
		session.close();
	}
	
	@Override
	public User find(int id) {
		Session session = sessionFactory.openSession();
		SQLQuery query = session.createSQLQuery("select * from t_user where id ="+id).addEntity(User.class);
		@SuppressWarnings("unchecked")
		List<User> uuList = query.list();
		User user = new User();
		for (int i = 0; i < uuList.size(); i++) {
			user = uuList.get(i);
		}
		return user;
	}

	@Override
	public void del(int id) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		User user = find(id);
		session.delete(user);
		tx.commit();
		session.close();
	}

	@Override
	public User update(User user) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
		return user;
	}

	@Override
	public List<User> getAll() {
		Session session = sessionFactory.openSession();
		SQLQuery query = session.createSQLQuery("select * from t_user").addEntity(User.class);
		@SuppressWarnings("unchecked")
		List<User> uuList = query.list();
		return uuList;
	}

}

4、service接口,com.mvn.service,UserService.java

package com.mvn.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.mvn.entity.User;

@Service
public interface UserService {

	public void save(User user);
	
	public User find(int id);
	
	public void del(int id);
	 
	public User update(User user);
	 
	public List<User> getAll();
}

5、service接口实现类,com.mvn.service.impl,UserServiceImpl.java

package com.mvn.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mvn.dao.impl.UserDaoImpl;
import com.mvn.entity.User;
import com.mvn.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService{

	@Autowired
	private UserDaoImpl userDaoImpl;
	
	@Override
	
	public void save(User user) {
		userDaoImpl.save(user);
	}

	

	@Override
	public void del(int id) {
		userDaoImpl.del(id);
	}

	@Override
	public User update(User user) {
		return userDaoImpl.update(user);
	}

	@Override
	public List<User> getAll() {
		return userDaoImpl.getAll();
	}

	@Override
	public User find(int id) {
		return userDaoImpl.find(id);
	}

}

6、controller类,com.mvn.controller,ControUser.java

package com.mvn.controller;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvn.entity.User;
import com.mvn.service.impl.UserServiceImpl;

@Controller
public class ContrUser {

    @Autowired
    private UserServiceImpl userServiceimpl;
    
    //新增操作
    @RequestMapping(value="/doAdd")
    public String saveUser(User user){
    	userServiceimpl.save(user);
        return "saveSucess";
    }
    
	//根据id查询
    @RequestMapping(value="/get")
    public String findUser(int id, Model model){
    	User user= userServiceimpl.find(id);
    	model.addAttribute("user", user);
    	return "findUser";
    }
    
    //查询所有,这里暂时不做分页
    @RequestMapping(value="/findAllUser")
    public String findAllUser(Model model){
    	List<User> list = userServiceimpl.getAll();
    	model.addAttribute("list", list);
    	return "query";
    }
    
    //跳转新增页面
    @RequestMapping(value="/add")
    public String add(){
    	return "add";
    }
    
    //根据id删除
    @RequestMapping(value="/del")
    public String delUser(int id,Model model){
    	System.out.println("shifou");
    	userServiceimpl.del(id);
    	System.out.println("shifou"+id);
    	List<User> list = userServiceimpl.getAll();
    	model.addAttribute("list", list);
    	return "query";
    }

	//更新操作
    @RequestMapping(value="/updateUser")
    public String updateUser(User user,Model model){
		User user2 = userServiceimpl.update(user);
    	model.addAttribute("user", user2);
    	return "findUser";
    }
}

7、在WEB-INF下创建jsp文件夹,其中有
1)查询所有显示页面,query.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>
<script type="text/javascript" src="js/jquery-1.7.js"></script>
</head>
<body>
Hello
恭喜!
整合成功啦
<table border="2">
	<tr>
		<th>id</th>
		<th>name</th>
		<th>password</th>
		<th>look</th>
		<th>del</th>
		<th><a href="javascript:void(0);" class="add" >add</a></th>
	</tr>
	
	
<c:forEach items="${list }" var="user" >
	<tr>
		<td><c:out value="${user.id }"></c:out></td>
		<td><c:out value="${user.name }"></c:out></td>
		<td><c:out value="${user.password }"></c:out></td>
		<td><a href="javascript:void(0);" class="look" rel="${user.id }">look</a></td>
		<td><a href="javascript:void(0);" class="del" rel="${user.id }">del</a></td>
	</tr>
</c:forEach>

</table>

</body>
<script>
$(function(){
	$(".look").click(function(){
	
	var id = $(this).attr('rel');
		window.location.href="${ctx}/test-ssh/get.do?id="+id;
	});

	$(".add").click(function(){
	
		window.location.href="${ctx}/test-ssh/add.do";
	});
	
	$(".del").click(function(){
	var id = $(this).attr('rel');
		window.location.href="${ctx}/test-ssh/del.do?id="+id;
	});
	

});

</script>
</html>

2)添加页面add.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>
<script type="text/javascript" src="js/jquery-1.7.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
Hello
恭喜!
整合成功
<form id="editForm">
<table border="2">
	<tr>
		<th>name</th>
		<th>password</th>
		<th>operation1</th>
		<th>operation2</th>
	</tr>
	<tr>
		<td><input type="text" value="${user.name }" name="name"></td>
		<td><input type="text" value="${user.password }" name="password"></td>
		<td><input type="button" value="save" id="save"></td>
		<td><input type="button" value="back" id="back"></td>
	</tr>
</table>
</form>
</body>
<script>

$(function(){
	$("#save").click(function(){
	
		var url;
			url="${ctx}/test-ssh/doAdd.do";
		
		//异步提交表单
		var options = {
			url:	   url,
	        success:   callback, 
	        type:      'post',      
	        dataType:  'json'
		};

		$("#editForm").ajaxSubmit(options);
		
		alert("增加ing");
	});
	
	$("#back").click(function(){
		window.location.href= "${ctx}/test-ssh/findAllUser.do";
	});
	
	function callback(data){
		alert("chenggong");
	};
});

</script>
</html>

3)查询一个的页面findUser.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>
<script type="text/javascript" src="js/jquery-1.7.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
Hello
恭喜!
整合成功
<form id="editForm">
<table border="2">
	<tr>
		<th>id</th>
		<th>name</th>
		<th>password</th>
		<th>operation1</th>
		<th>operation2</th>
	</tr>
	<tr>
		<td><input type="text" value="${user.id }" name="id"></td>
		<td><input type="text" value="${user.name }" name="name"></td>
		<td><input type="text" value="${user.password }" name="password"></td>
		<td><input type="button" value="save" id="save"></td>
		<td><input type="button" value="back" id="back"></td>
	</tr>
</table>
</form>
</body>
<script>

$(function(){
	$("#save").click(function(){
	
		var url;
			url="${ctx}/test-ssh/updateUser.do";
		
		//异步提交表单
		var options = {
			url:	   url,
	        success:   callback, 
	        type:      'post',      
	        dataType:  'json'
		};

		$("#editForm").ajaxSubmit(options);
		
		alert("修改ing");
	});
	
	$("#back").click(function(){
		window.location.href="${ctx}/test-ssh/findAllUser.do";
	});
	
	function callback(data){
		alert("chenggong");
	};
});

</script>
</html>

其中使用了jquery工具,所以要在webapp下创建js文件夹来放jquery.js
其完整项目结构如下:
在这里插入图片描述
在这里插入图片描述
第二步:进行测试
1、创建数据库test
2、启动tomcat,因为配置hibernate.hbm2ddl.auto=update,所以当启动tonmcat时会自动生成表t_user
3、通过页面访问http://localhost:8080/test-ssh/add.do?name=xiaoming&password=1234
在这里插入图片描述
可以进行基本的增删改查操作,
至此,整合完成
本篇是参考https://www.cnblogs.com/sam-uncle/p/8681515.html写的,其中标准了项目的结构以及增加了基本的增删改查。
主要是自己记录保存下来以便于以后查看,其中搭建框架主要是各种配置文件的配置,pom文件版本之间的依赖,事务的配置等。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值