72 views

Spring+Spring MVC+Hibernate框架搭建实例

By | 2019年2月21日

一 下面所需要用到的数据库配置:

数据库使用mysql创建一个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’, ‘北京天安门’);
二 创建web项目,并导入相关jar包:

先创建dynamic web project,随后在WEB-INF/lib导入spring和hibernate的jar包。

三 使用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>
<h1>Message : ${message}</h1>

</body>
</html>
四 依据数据库表的字段来建立实体类Users.java:

这里使用注解的方式来配置,并把实体类放在cn.zifangsky.entity中,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>

<!– 设置字符集 –>
<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.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=org/schema/beans”
xmlns:context=org/schema/context”
xmlns:mvc=schema/mvc”
xmlns:p=org/schema/p”
xmlns:xsi=2001/XMLSchema-instance”
xmlns:tx=mework.org/schema/tx”

<!– 启用spring mvc 注解 –>
<mvc:annotation-driven />
<!– 不操作静态资源 –>
<mvc:default-servlet-handler />
<!– 启动自动扫描该包下所有的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,这里为了简单只用了基础的jdbc数据源,路径是src/spring-hibernate.xml:

<!– 声明事务管理器 –>
<bean id=”myHibTxManager”
class=”org.springframework.orm.hibernate5.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>

<!– 定义事务通知 –>
<tx:advice id=”tx_Advice” transaction-manager=”myHibTxManager”>
<!– 定义事务传播规则 –>
<tx:attributes>
<!– 对get/load/search开头的方法应用只读事务规则 –>
<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” />
<!– 对其他方法应用REQUIRED事务规则 –>
<tx:method name=”*” propagation=”REQUIRED” />
</tx:attributes>
</tx:advice>
<aop:config>
<!– 对com.zxpm.biz包下的所有类的所有方法都应用事务规则 –>
<aop:pointcut id=”bizMethods”
expression=”execution(* cn.zifangsky.service.*.*(..))” />
<!– 将事务通知和切面组合 –>
<aop:advisor advice-ref=”tx_Advice” pointcut-ref=”bizMethods” />
</aop:config>

<!– 配置数据源 –>
<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>
<!– 可以加多个包 –>
<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,当然具体的一些bean将在下一环节中配置,路径:src/spring-bean.xml:

<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>

六 业务处理DAO,Service和Controller:

(1)UsersDAO.java,在cn.zifangsky.dao这个包中:

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这个包中:

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这个包中:

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;
}
}

本文转载于:http://win-man.com
作者:云漫网络有限公司

发表评论

电子邮件地址不会被公开。 必填项已用*标注