溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring+Spring MVC+Hibernate框架搭建實(shí)例

發(fā)布時(shí)間:2020-07-08 09:47:12 來(lái)源:網(wǎng)絡(luò) 閱讀:10267 作者:pangfc 欄目:開(kāi)發(fā)技術(shù)

前言:這里只是說(shuō)明整個(gè)搭建流程,并不進(jìn)行原理性的講解

一 下面所需要用到的數(shù)據(jù)庫(kù)配置:

數(shù)據(jù)庫(kù)方面,使用mysql創(chuàng)建一個(gè)users表,具體代碼如下:

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `UserID` int(4) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(16) NOT NULL,
  `Password` varchar(16) NOT NULL,
  `Telephone` varchar(16) NOT NULL,
  `Address` varchar(16) NOT NULL,
  PRIMARY KEY (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'aa', 'aa12', 'aa', 'aa');
INSERT INTO `users` VALUES ('2', 'bb', 'bb', 'bb', 'bb');
INSERT INTO `users` VALUES ('3', 'cc', 'cc', 'cc', 'cc');
INSERT INTO `users` VALUES ('7', 'admin', 'admin', '12306', '北京天安門(mén)');

二 創(chuàng)建web項(xiàng)目,并導(dǎo)入相關(guān)jar包:

創(chuàng)建一個(gè)dynamic web project,然后在WEB-INF/lib下導(dǎo)入spring和hibernate的jar包,嫌麻煩的話也可以使用我用到的jar包,鏈接:http://pan.baidu.com/s/1kUse26z 。整個(gè)項(xiàng)目的結(jié)構(gòu)是這樣的:

Spring+Spring MVC+Hibernate框架搭建實(shí)例

三 創(chuàng)建視圖頁(yè)面user.jsp:

路徑是:/WEB-INF/jsp/user/user.jsp,代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<base href="<%=basePath%>">
	<title>Insert title here</title>
</head>
<body>
	<h2>Message : ${message}</h2>
	
</body>
</html>

四 根據(jù)數(shù)據(jù)庫(kù)表的字段建立實(shí)體類Users.java:

實(shí)體類放在cn.zifangsky.entity包中,這里采用了注解的方式來(lái)配置,Users.java代碼如下:

package cn.zifangsky.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="users")
public class Users implements java.io.Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="UserID")
	private Integer userId;
	@Column(name="UserName",length=16)
	private String userName;
	@Column(name="Password",length=16)
	private String password;
	@Column(name="Telephone",length=16)
	private String telephone;
	@Column(name="Address",length=16)
	private String address;
	
	public Users(){
		
	}	
	public Users(Integer userId, String userName, String password, String telephone, String address) {
		this.userId = userId;
		this.userName = userName;
		this.password = password;
		this.telephone = telephone;
		this.address = address;
	}
	public Integer getUserId() {
		return userId;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

五 處理框架整合的配置文件:

(1)首先是web.xml,路徑是:WEB-INF/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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<!-- 配置Spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/spring-*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 定義DispatcherServlet -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/classes/springmvc-servlet.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>

	<!-- 設(shè)置字符集 -->
	<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的開(kāi)關(guān) -->
	<filter>
		<filter-name>openSession</filter-name>
		<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>openSession</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

(2)spring mvc所需要用到的配置文件springmvc-servlet.xml,路徑是:src/springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">

      
    <!-- 啟用spring mvc 注解 -->
	<mvc:annotation-driven />
	<!-- 不操作靜態(tài)資源 -->
	<mvc:default-servlet-handler />  
    <!-- 啟動(dòng)自動(dòng)掃描該包下所有的Bean(例如@Controller) -->
    <context:component-scan base-package="cn.zifangsky.controller" />  
    
    <!-- 定義視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/user/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>

(3)整合hibernate所需要用到的配置文件spring-hibernate.xml,這里為了簡(jiǎn)單只用了基礎(chǔ)的jdbc數(shù)據(jù)源,路徑是src/spring-hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-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/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   ">

	<!-- 聲明事務(wù)管理器 -->
	<bean id="myHibTxManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 定義事務(wù)通知 -->
	<tx:advice id="tx_Advice" transaction-manager="myHibTxManager">
		<!-- 定義事務(wù)傳播規(guī)則 -->
		<tx:attributes>
			<!-- 對(duì)get/load/search開(kāi)頭的方法應(yīng)用只讀事務(wù)規(guī)則 -->
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="load*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="search*" propagation="SUPPORTS" read-only="true" />
			<!-- 對(duì)其他方法應(yīng)用REQUIRED事務(wù)規(guī)則 -->
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<!-- 對(duì)com.zxpm.biz包下的所有類的所有方法都應(yīng)用事務(wù)規(guī)則 -->
		<aop:pointcut id="bizMethods"
			expression="execution(* cn.zifangsky.service.*.*(..))" />
		<!-- 將事務(wù)通知和切面組合 -->
		<aop:advisor advice-ref="tx_Advice" pointcut-ref="bizMethods" />
	</aop:config>

	<!-- 配置數(shù)據(jù)源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1/zxpm" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan">
			<list>
				<!-- 可以加多個(gè)包 -->
				<value>cn.zifangsky.entity</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

</beans>

(4)加載bean配置文件spring-bean.xml,當(dāng)然具體的一些bean將在下一環(huán)節(jié)中配置,路徑:src/spring-bean.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
      
    <bean id="usersDAO" class="cn.zifangsky.dao.UsersDAO">
          <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="userService" class="cn.zifangsky.service.UserService">
        <property name="userDao" ref="usersDAO"></property>
    </bean>
</beans>

六 業(yè)務(wù)處理DAO,Service和Controller:

(1)UsersDAO.java,在cn.zifangsky.dao這個(gè)包中:

package cn.zifangsky.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import cn.zifangsky.entity.Users;

public class UsersDAO extends HibernateDaoSupport{
    public List<Users> getAllUser(){
    	Object execute =  super.getHibernateTemplate().execute(new HibernateCallback<Object>() { 		
			public Object doInHibernate(Session session) throws HibernateException {
				 String hql="from users";
				 Query query = session.createQuery(hql);
			        
			     return query.list();
			}
		});
		
		return (List<Users>) execute;    
    }
}

(2)UserService.java,在cn.zifangsky.service這個(gè)包中:

package cn.zifangsky.service;

import cn.zifangsky.dao.UsersDAO;

public class UserService {
    private UsersDAO userDao;
    
    public int userCount(){
        return userDao.getAllUser().size();
    }

    public UsersDAO getUserDao() {
        return userDao;
    }

    public void setUserDao(UsersDAO userDao) {
        this.userDao = userDao;
    }

}

(3)UserController.java,在cn.zifangsky.controller這個(gè)包中:

package cn.zifangsky.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.zifangsky.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @Resource(name="userService")
    private UserService service;
    
    @RequestMapping(value="/manager",method=RequestMethod.GET)
    public ModelAndView hello2(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", "HelloMVC");
        mv.setViewName("user");
        return mv;
    }
    
    @RequestMapping(value="/count",method=RequestMethod.GET)
    public ModelAndView count(){
        
        int c = service.userCount();
        
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", c);
        mv.setViewName("user");
        return mv;
    }
}

從上面的代碼可以看出,定義了兩個(gè)請(qǐng)求,分別是:http://localhost:8080/SpringDemo/user/manager 和 http://localhost:8080/SpringDemo/user/count ,分別返回一個(gè)字符串和users這個(gè)表中數(shù)據(jù)的條數(shù)。下面我們將對(duì)這兩個(gè)請(qǐng)求進(jìn)行測(cè)試

七 測(cè)試:

測(cè)試結(jié)果如下:

http://localhost:8080/SpringDemo/user/manager 

Spring+Spring MVC+Hibernate框架搭建實(shí)例

http://localhost:8080/SpringDemo/user/count

Spring+Spring MVC+Hibernate框架搭建實(shí)例

可以看出,這個(gè)框架已經(jīng)搭建成功了


注:如果在項(xiàng)目啟動(dòng)時(shí)報(bào)錯(cuò)的話,第一是檢查配置文件中是不是有哪個(gè)地方寫(xiě)錯(cuò)了,第二是注意看下/WEB-INF/lib下有沒(méi)有aopalliance.jar和aspectjweaver-1.5.4.jar這兩個(gè)jar包。因?yàn)槲覄傞_(kāi)始時(shí)就是因?yàn)闆](méi)有這兩個(gè)jar包,在項(xiàng)目啟動(dòng)時(shí)各種報(bào)錯(cuò),真的挺坑的Spring+Spring MVC+Hibernate框架搭建實(shí)例

PS:參考文章:http://www.cnblogs.com/leiOOlei/p/3727859.html

歡迎大家有時(shí)間來(lái)我個(gè)人獨(dú)立博客(http://www.zifangsky.cn)踩踩Spring+Spring MVC+Hibernate框架搭建實(shí)例

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI