标签:
这篇主要采用Maven搭建Spring+Struts2+Hibernate的整合项目,复习一下SSH框架,虽然spring提供自己的MVC框架, 但是Spring也提供和其他框架的无缝整合,采用组件形式对个框架进行管理,项目实例是按照真实企业里面的开发搭建,也是web的最后一片了。数据库使 用mysql,连接池使用的是Druid数据源(这些都无关紧要,可以随时的替换),下面就将详细的介绍一下Maven搭建 Spring,Struts2,和hibernation的步奏。
1、数据库设计
数据库库表很简单,设计好数据库后,直接逆向生成实体,提高速度。数据库名为shop,只有一个表user_info。其结构如下:
2、创建Maven的webapp项目
创建maven项目,pom.xml配置中引入所需依赖包。
引入所需的依赖包,pom.xml内容如下:
以上就是ssh所需的所有依赖包。、
3、引入Spring
最优先引入的是Spring框架,他是管理其他框架的容器,spring中需要配置的是自动扫描的dao,和service层的注解,然后将其注入为bean,管理。
配置文件在src/main/java目录下,创建spring的配置文件spring.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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd">
-
-
- <context:property-placeholder location="classpath:config.properties"/>
-
- <context:component-scan base-package="org.andy.shop.service.impl,org.andy.shop.dao.impl" />
-
- </beans>
3.1、引入日志Log4j配置
log4j.properties配置内容如下:
- ### set log levels ###
- log4j.rootLogger = INFO , C , D , E
-
- ### console ###
- log4j.appender.C = org.apache.log4j.ConsoleAppender
- log4j.appender.C.Target = System.out
- log4j.appender.C.layout = org.apache.log4j.PatternLayout
- log4j.appender.C.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
-
- ### log file ###
- log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.D.File = ../logs/spring_struts2_Hibernate_demo.log
- log4j.appender.D.Append = true
- log4j.appender.D.Threshold = INFO
- log4j.appender.D.layout = org.apache.log4j.PatternLayout
- log4j.appender.D.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
-
- ### exception ###
- log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.E.File = ../logs/spring_struts2_Hibernate_demo_error.log
- log4j.appender.E.Append = true
- log4j.appender.E.Threshold = ERROR
- log4j.appender.E.layout = org.apache.log4j.PatternLayout
- log4j.appender.E.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
3.2、项目配置文件
添加项目的配置文件config.properties,有spring管理。
- #application configs
-
- #jdbc druid config
- validationQuery = SELECT 1
- jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
- jdbc.username = root
- jdbc.password = root
-
- #hibernate config
- hibernate.dialect = org.hibernate.dialect.MySQLDialect
- hibernate.show_sql = true
- hibernate.format_sql = false
- hibernate.hbm2ddl.auto = update
4、引入Hibernation
Hibernation的配置主要有如下内容:数据源,SessionFactory,事务等的配置。
spring-hibernate.xml配置如下(配置文件名可以随便起)
注意:Hibernation4使用的是SessionFactory而不是HibernationTemplate。
5、生成实体
我们先添加实体entity,Dao,Service,Action等几个包,一般设计如下:
设计好数据表之后,采用Hibernation tools自动逆向生成实体,其实体UserInfo如下:
- package org.andy.shop.entity;
-
-
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
-
- @Entity
- @Table(name = "user_info", catalog = "shop")
- public class UserInfo implements java.io.Serializable {
-
-
- private static final long serialVersionUID = 5127853981202454040L;
- private int id;
- private String name;
- private Integer age;
- private String telephone;
-
- public UserInfo() {
- }
-
- public UserInfo(int id, String name) {
- this.id = id;
- this.name = name;
- }
-
- public UserInfo(int id, String name, Integer age, String telephone) {
- this.id = id;
- this.name = name;
- this.age = age;
- this.telephone = telephone;
- }
-
- @Id
- @Column(name = "id", unique = true, nullable = false)
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- @Column(name = "name", nullable = false)
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Column(name = "age")
- public Integer getAge() {
- return this.age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- @Column(name = "telephone")
- public String getTelephone() {
- return this.telephone;
- }
-
- public void setTelephone(String telephone) {
- this.telephone = telephone;
- }
-
- }
6、创建Dao层
我们采用面向接口编程,所以先设计接口,在写dao的实现类,其理,同样适用于service层。
6.1、Dao层接口
我们先定义一个通用的GenericDao接口,如下:
- package org.andy.shop.dao;
-
- import java.io.Serializable;
- import java.util.List;
-
-
- interface GenericDao<T, PK extends Serializable> {
-
- T load(PK id);
-
- T get(PK id);
-
- List<T> findAll();
-
- void persist(T entity);
-
- PK save(T entity);
-
- void saveOrUpdate(T entity);
-
- void delete(PK id);
-
- void flush();
- }
具体的UserInfo的Dao接口UserInfoDao如下:
- package org.andy.shop.dao;
-
- import org.andy.shop.entity.UserInfo;
-
-
- public interface UserInfoDao extends GenericDao<UserInfo, Integer> {
-
- }
6.2、Dao层实现类
UserInfo的Dao层实现类UserInfoDaoImpl如下:
- package org.andy.shop.dao.impl;
-
- import java.util.List;
-
- import org.andy.shop.dao.UserInfoDao;
- import org.andy.shop.entity.UserInfo;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
-
-
- @Repository("userInfoDao")
- public class UserInfoDaoImpl implements UserInfoDao {
-
- @Autowired
- private SessionFactory sessionFactory;
-
- private Session getCurrentSession() {
- return this.sessionFactory.getCurrentSession();
- }
-
- @Override
- public UserInfo load(Integer id) {
- return (UserInfo) this.getCurrentSession().load(UserInfo.class, id);
- }
-
- @Override
- public UserInfo get(Integer id) {
- return (UserInfo) this.getCurrentSession().get(UserInfo.class, id);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<UserInfo> findAll() {
- List<UserInfo> userInfos = this.getCurrentSession()
- .createQuery("from UserInfo").list();
- return userInfos;
- }
-
- @Override
- public void persist(UserInfo entity) {
- this.getCurrentSession().persist(entity);
-
- }
-
- @Override
- public Integer save(UserInfo entity) {
- return (Integer) this.getCurrentSession().save(entity);
- }
-
- @Override
- public void saveOrUpdate(UserInfo entity) {
- this.getCurrentSession().saveOrUpdate(entity);
- }
-
- @Override
- public void delete(Integer id) {
- UserInfo entity = this.load(id);
- this.getCurrentSession().delete(entity);
- }
-
- @Override
- public void flush() {
- this.getCurrentSession().flush();
-
- }
-
- }
我们采用@Repository注解将其注入为dao的bean,交由spring管理。
7、创建Service层
Service层同理按照面向接口编程。
7.1、Service层接口
UserInfo层接口UserInfoService如下:
- package org.andy.shop.service;
-
- import java.util.List;
-
- import org.andy.shop.entity.UserInfo;
-
-
- public interface UserInfoService {
- UserInfo load(Integer id);
-
- UserInfo get(Integer id);
-
- List<UserInfo> findAll();
-
- void persist(UserInfo entity);
-
- Integer save(UserInfo entity);
-
- void saveOrUpdate(UserInfo entity);
-
- void delete(Integer id);
-
- void flush();
- }
7.2、service层实现类
service层我们使用@Service注解将其注入为bean。
- package org.andy.shop.service.impl;
-
- import java.util.List;
-
- import org.andy.shop.dao.UserInfoDao;
- import org.andy.shop.entity.UserInfo;
- import org.andy.shop.service.UserInfoService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- @Service("userInfoService")
- public class UserInfoServiceImpl implements UserInfoService {
-
- @Autowired
- private UserInfoDao userInfoDao;
-
- @Override
- public UserInfo load(Integer id) {
- return null;
- }
-
- @Override
- public UserInfo get(Integer id) {
- return userInfoDao.get(id);
- }
-
- @Override
- public List<UserInfo> findAll() {
- return userInfoDao.findAll();
- }
-
- @Override
- public void persist(UserInfo entity) {
- userInfoDao.persist(entity);
- }
-
- @Override
- public Integer save(UserInfo entity) {
- return userInfoDao.save(entity);
- }
-
- @Override
- public void saveOrUpdate(UserInfo entity) {
- userInfoDao.saveOrUpdate(entity);
- }
-
- @Override
- public void delete(Integer id) {
- userInfoDao.delete(id);
- }
-
- @Override
- public void flush() {
- userInfoDao.flush();
- }
-
- }
8、单元测试Spring和Hibernation框架的整合
以上,spring和Hibernation框架就算是整合完成了,我们需要测试一下是否整合成功,事务是否起作用等,所以我们需要在src/test/java源目录中编写测试类,进行测试:
我们创建了TestUserService类,进行单元测试:
TestUserService内容如下:
- package org.andy.shop.service;
-
- import org.andy.shop.entity.UserInfo;
- import org.apache.log4j.Logger;
- 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 com.alibaba.fastjson.JSON;
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:spring.xml",
- "classpath:spring-hibernate.xml" })
- public class TestUserService {
-
- private static final Logger LOGGER = Logger
- .getLogger(TestUserService.class);
-
- @Autowired
- private UserInfoService userInfoService;
-
- @Test
- public void save() {
- UserInfo userInfo = new UserInfo();
- userInfo.setName("zty");
- userInfo.setAge(23);
- userInfo.setTelephone("13212221333");
- Integer id = userInfoService.save(userInfo);
- JSON.toJSONString(id);
- }
-
- }
我们需要引入springjunit的包,将spring配置加载,如果单元测试成功,那么项目搭建已经成功了一半了。
9、引入Struts2
配置Struts框架的配置文件,Struts2不同于前面的框架,其配置文件名必须为struts.xml,内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
- <struts>
-
- <constant name="struts.objectFactory" value="spring" />
-
- <constant name="struts.action.extension" value="action" />
-
- <constant name="struts.devMode" value="true" />
-
- <constant name="struts.configuration.xml.reload" value="true" />
-
- <constant name="struts.serve.static.browserCache" value="false" />
-
- <constant name="struts.i18n.encoding" value="utf-8" />
-
- <constant name="struts.i18n.reload" value="true" />
-
- <constant name="struts.multipart.maxSize" value="104857600" />
-
- <constant name="struts.enable.DynamicMethodInvocation" value="true" />
-
- <constant name="struts.enable.SlashesInActionNames" value="false" />
-
- <constant name="struts.tag.altSyntax" value="true" />
-
- <constant name="struts.dispatcher.parametersWorkaround" value="false" />
-
-
- <package name="crud-default" extends="convention-default">
-
- <interceptors>
- <interceptor-stack name="crudStack">
- <interceptor-ref name="store">
- <param name="operationMode">AUTOMATIC</param>
- </interceptor-ref>
- <interceptor-ref name="paramsPrepareParamsStack" />
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="crudStack" />
- </package>
-
-
-
- </struts>
上面配置的比较详细,可以按照实际项目,做一下筛检。
10、配置web容器web.xml
web.xml是web项目的核心,里面配置了容器启动是的加载文件,以及监听器,过滤器等内容,所以需要我们配置对个框架的启动,加载。其内容如下:
- <?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/web-app_2_5.xsd"
- 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>spring_struts2_Hibernate_demo</display-name>
-
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath:spring.xml
- classpath:spring-hibernate.xml
- </param-value>
- </context-param>
-
-
- <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>openSessionInViewFilter</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
-
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
-
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
-
-
-
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
-
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping>
-
-
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping>
-
-
- <session-config>
- <session-timeout>30</session-timeout>
- </session-config>
-
- <welcome-file-list>
- <welcome-file>/index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
注意:上面Hibernation4和3还是有点区别的。
11、创建控制层Action
控制层Struts2我们采用annotation 约束注解方式实现action的零配置,需要我们在WEB-INF下创建content目录(必须是content),里面存放是视图层jsp。
UserinfoAction内容如下:
- package org.andy.shop.action;
-
- import java.util.List;
-
- import org.andy.shop.entity.UserInfo;
- import org.andy.shop.service.UserInfoService;
- import org.andy.shop.utils.AjaxUtil;
- import org.apache.log4j.Logger;
- import org.apache.struts2.ServletActionContext;
- import org.apache.struts2.convention.annotation.Namespace;
- import org.springframework.beans.factory.annotation.Autowired;
-
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.ModelDriven;
- import com.opensymphony.xwork2.Preparable;
-
- @Namespace("/user")
- public class UserinfoAction extends ActionSupport implements
- ModelDriven<UserInfo>, Preparable {
- private static final long serialVersionUID = -2301203156032690317L;
-
- private static final Logger LOGGER = Logger.getLogger(UserinfoAction.class);
- private Integer id;
- private UserInfo userInfo;
- private List<UserInfo> userInfos;
-
- @Autowired
- private UserInfoService userInfoService;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public UserInfo getUserInfo() {
- return userInfo;
- }
-
- public void setUserInfo(UserInfo userInfo) {
- this.userInfo = userInfo;
- }
-
- public List<UserInfo> getUserInfos() {
- return userInfos;
- }
-
- public void setUserInfos(List<UserInfo> userInfos) {
- this.userInfos = userInfos;
- }
-
- @Override
- public UserInfo getModel() {
- if (null != id) {
- userInfo = userInfoService.get(id);
- } else {
- userInfo = new UserInfo();
- }
- return userInfo;
- }
-
- @Override
- public String execute() throws Exception {
- LOGGER.info("查询所有用户");
- userInfos = userInfoService.findAll();
- return SUCCESS;
-
- }
-
- public void detail() {
- String id = ServletActionContext.getRequest().getParameter("id");
- LOGGER.info("查看用户详情:" + id);
- userInfo = userInfoService.get(Integer.valueOf(id));
- AjaxUtil.ajaxJSONResponse(userInfo);
-
- }
-
- @Override
- public void prepare() throws Exception {
-
- }
-
- }
按照约束原则,上面success是会跳转到content下的/user/userinfo.jsp视图。
注意:如果上述的UserinfoAction写出了UserInfoAction,那么对应的视图为/user/user-info.jsp,对应的Action为user-info.action
12、创建视图层
视图userinfo.jsp内容如下:
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
-
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="<%=basePath%>" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
- <title>userInfo</title>
- </head>
- <body>
- 全部用户信息:
- <c:forEach items="${ userInfos}" var="user">
- <div> 姓
名:${user.name } 年龄:${user.age } 电
话: ${user.telephone } <a target="_blank" href="user/userinfo!detail.action?id=${user.id}"&
gt;json详情</a></div>
- </c:forEach>
-
- </body>
- </html>
通过这个视图,我们可以测试UserinfoAction中的两个url。
13、部署服务器测试
使用Maven打包部署:clean compile package
测试 http://localhost:8080/spring_struts2_Hibernate_demo/user/userinfo.action
json返回数据 http://localhost:8080/spring_struts2_Hibernate_demo/user/userinfo!detail.action?id=1
OK,到此为止Spring+Struts2+Hibernate全部搭建完成。
博客来源:http://blog.csdn.net/fengshizty?viewmode=list
项目源码:http://download.csdn.net/detail/fengshizty/8464569
Spring+Struts2+Hibernate的整合
标签:
原文地址:http://www.cnblogs.com/lykxqhh/p/5690904.html