Struts2 Spring Hibernate 框架整合 Annotation MavenProject

时间:2021-09-09 17:25:44

项目结构目录

Struts2 Spring Hibernate 框架整合  Annotation  MavenProject

pom.xml       添加和管理jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lee</groupId>
<artifactId>Struts2_Spring_Hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Struts2_Spring_Hibernate Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- Struts2版本号 -->
<Struts2.version>2.3.16.3</Struts2.version>
<!-- Spring版本号 -->
<spring.version>4.2.3.RELEASE</spring.version>
<!-- Hibernate版本号 -->
<hibernate.version>5.0.6.Final</hibernate.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- struts2核心包 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${Struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${Struts2.version}</version>
</dependency>
<!-- Spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Hibernate核心包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency> <!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.3</version>
</dependency>
<!-- jta -->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<finalName>Struts2_Spring_Hibernate</finalName>
</build>
</project>

jdbc.properties

host=127.0.0.1
dbName=police
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://${host}:3306/${dbName}
jdbc.username=root
jdbc.password=lifu jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600 jdbc.c3p0.initialPoolSize=10
jdbc.c3p0.minPoolSize=10
jdbc.c3p0.maxPoolSize=100
jdbc.c3p0.maxIdleTime=3600 hibernate.connection.driverClass=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://${host}:3306/${dbName}
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update

spring-core.xml   spring 核心配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 扫描路径,不扫描Controller -->
<context:component-scan base-package="com.lee">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- 导入数据库的相关配置 -->
<import resource="classpath:spring/spring-hibernate.xml" />
<!-- Entity beans -->
<import resource="classpath:spring/spring-entity.xml" /> </beans>

spring-hibernate.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"
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"> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"
file-encoding="utf-8" ignore-unresolvable="true" /> <bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.lee.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
</bean> <!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" p:driverClass="${jdbc.driverClassName}"
p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}"
p:testConnectionOnCheckout="${jdbc.c3p0.testConnectionOnCheckout}"
p:testConnectionOnCheckin="${jdbc.c3p0.testConnectionOnCheckin}"
p:idleConnectionTestPeriod="${jdbc.c3p0.idleConnectionTestPeriod}"
p:initialPoolSize="${jdbc.c3p0.initialPoolSize}" p:minPoolSize="${jdbc.c3p0.minPoolSize}"
p:maxPoolSize="${jdbc.c3p0.maxPoolSize}" p:maxIdleTime="${jdbc.c3p0.maxIdleTime}" /> <!-- jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" /> <!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <!-- 基于数据源的事务管理器 -->
<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" /> --> <!-- 配合<tx:advice>和<aop:advisor>完成了事务切面的定义 -->
<!-- 使用强大的切点表达式是语言轻松定义目标方法 -->
<aop:config proxy-target-class="true">
<!-- 通过aop定义事务增强切面 -->
<aop:pointcut expression=" execution(* com.lee.service..*(..))"
id="serviceMethod" />
<!-- 引用事务增强 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
<!-- 事务增强 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 事务属性定义 -->
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice> </beans>

spring-entity.xml    管理entity  beans

<?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"
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"> <bean id="user" class="com.lee.entity.User"></bean> </beans>

struts.xml    struts2与spring整合需要 struts2-spring-plugin.jar ,并设置struts2对象由spring创建,即  <constant name="struts.objectFactory" value="spring" />

<?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>
<!-- struts常量定义 -->
<!-- 允许动态调用true -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<!-- 把它设置为开发模式,发布时要设置为false -->
<constant name="struts.devMode" value="true" />
<!-- 配置应用的编码方式 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- struts.xml变更时是否自动重新加载 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 资源文件 -->
<constant name="struts.custom.i18n.resources" value="MessageResource" />
<!-- 告知Struts2运行时使用Spring来创建对象 -->
<constant name="struts.objectFactory" value="spring" /> <package name="default" namespace="/" extends="struts-default">
<action name="userLogin" class="com.lee.controller.IndexAction">
<result>/jsp/Index.jsp</result>
<result name="input">/jsp/Login.jsp</result>
</action>
</package> <!-- Add packages here --> </struts>

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-core.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter>
<filter-name>charsetEncoding</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>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>charsetEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

struts2  Action  (controller)   IndexAction.java

package com.lee.controller;

import java.io.Serializable;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import com.lee.entity.User;
import com.lee.service.user.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; @Controller
public class IndexAction extends ActionSupport implements Serializable { @Autowired
private UserService userService; @Override
public String execute() throws Exception { // System.out.println(this.userService.login(phone, password));
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
session.put("user",this.userService.login(phone, password));
return SUCCESS;
}
/**
* default
*/
private static final long serialVersionUID = 1L;
private String phone;
private String password;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }

service    (service)  UserServiceImpl.java

package com.lee.service.user.impl;

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;

import com.lee.dao.UserDao;
import com.lee.entity.User;
import com.lee.service.user.UserService;
@Service
public class UserServiceImpl implements UserService { @Autowired
private UserDao userDao; public User login(String phone, String password) {
return userDao.login(phone, password);
}
}

dao   (Repository)    UserDaoImpl.java

package com.lee.dao.impl;

import java.util.ArrayList;
import java.util.List; import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; import com.lee.dao.UserDao;
import com.lee.entity.User;
@Repository
public class UserDaoImpl extends BaseDaoImpl implements UserDao { @Autowired
private SessionFactory sessionFactory;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private User user; public User login(String phone, String password) {
List<User> userList = new ArrayList<User>();
try {
String sql = "select id,name,phone,password,level from usertbl where phone=? and password=?";
// userList = session.createQuery("from com.wechat.entity.po.User where phone = ? and password = ?").setParameter(0, phone).setParameter(1, password).list();
userList = jdbcTemplate.query(sql,new Object[]{phone,password},new BeanPropertyRowMapper<User>(User.class));
//判断登录有且只有一个用户返回
if(userList.size()>0){
User u = (User)userList.get(0);
return u;
}else{
user.setLevel("1");
user.setName("default");
user.setPassword(password);
user.setPhone(phone);
this.save(user);
return user;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} public void save(User u) {
// TODO Auto-generated method stub
super.save(u);
}
}

model  (Entity)   User.java

package com.lee.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "usertbl")
public class User implements Serializable { /**
* default
*/
private static final long serialVersionUID = 1L; @Id
// @GenericGenerator(name="systemNative",strategy="native")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id; @Column(name = "phone")
private String phone; @Column(name = "name")
private String name; @Column(name = "password")
private String password; @Column(name = "level")
private String level; public String getLevel() {
return level;
} public void setLevel(String level) {
this.level = level;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} 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;
} }

Login.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>Login</title>
</head>
<body>
<form action="<%=request.getContextPath() %>/userLogin.action" method="post">
手机号:<input type="text" name="phone" /><br />
密码:<input type="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
</body>
</html>

Index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page isELIgnored="false" %> <!-- 必須設置否則EL表達式無效 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Index</title>
</head> <body>
Welcome! ${user.name}
</body>
</html>

源码下载:http://download.csdn.net/detail/askyy1232008/9873052