一、Hibernate框架
二、Struts2框架
三、Spring框架
1. web应用的三层为:
- 1.1 web层,(struts2),Struts2框架用的最多的是action
- 1.2 service层(spring),spring中用的最多的是IoC和AOP,把对象的创建交给Spring进行管理
- 1.3 dao层(hibernate),hibernate则是用来操作数据库,进行CRUD
2. 哪么这三个框架应该是如何整合呢?
思想是两两整合:
1.创建web工程
2.创建如下项目结构
3.pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.saogroupId>
<artifactId>MyFirstSSHartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<struts.version>2.5.10struts.version>
<spring.version>4.3.8.RELEASEspring.version>
<hibernate.version>5.1.7.Finalhibernate.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-coreartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-spring-pluginartifactId>
<version>${struts.version}version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>${hibernate.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.42version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.10version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
dependencies>
project>
4.web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>CharactorFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharactorFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring.xmlparam-value>
context-param>
web-app>
5.spring.xml
<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"
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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.sao.*"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialectprop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/sshprop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driverprop>
props>
property>
<property name="packagesToScan" value="com.sao.entity"/>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.sao.service.*+.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
aop:config>
beans>
6.struts.xml
<struts>
<package name="default" extends="struts-default" namespace="/">
<default-action-ref name="default" />
<action name="default">
<result>index.jspresult>
action>
package>
<package name="product" extends="struts-default" namespace="/"
strict-method-invocation="false">
<action name="product_*" class="productAction" method="{1}Product">
<result>index.jspresult>
<result name="input">index.jspresult>
action>
package>
<constant name="struts.custom.i18n.resources" value="messageResource">constant>
struts>
7.jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/ssh?useSSL=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
8.log4j.properpies
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
9.messageResource.properpies
invalid.fieldvalue.price = 商品价格输入格式有误
10.创建数据库表
数据库表user
11.IntelliJ IDEA下自动生成Hibernate映射文件以及实体类
配置Hibernate
在com.sao.entity包下将自动创建实体类:
product.java
package com.sao.entity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Product {
private int id;
private String name;
private Double price;
public Product() {
}
public Product(String name, Double price) {
this.name = name;
this.price = price;
}
@Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "name", nullable = true, length = 100)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "price", nullable = true, precision = 0)
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
if (id != product.id) return false;
if (name != null ? !name.equals(product.name) : product.name != null) return false;
if (price != null ? !price.equals(product.price) : product.price != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}
}
12.ProductDao.java
package com.sao.dao;
import com.sao.entity.Product;
/**
* 商品操作-持久层接口
*
*/
public interface ProductDao {
void saveProduct(Product product);
}
13.ProductDaoImpl.java
package com.sao.dao.impl;
import com.sao.dao.ProductDao;
import com.sao.entity.Product;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
/**
* 商品信息-服务层实现
*
*/
@Repository
public class ProductDaoImpl implements ProductDao {
//HibernateTemplate是spring对hibernate使用的一个简单封装,事务的开启,关闭,都交给HibernateTemplate
private HibernateTemplate template;
@Autowired
public ProductDaoImpl(SessionFactory sessionFactory) {
this.template = new HibernateTemplate(sessionFactory);
}
public void saveProduct(Product product) {
template.save(product);
}
}
14.ProductService.java
package com.sao.service;
import com.sao.entity.Product;
/**
* 商品操作-服务层接口
*
*/
public interface ProductService {
void saveProduct(Product product);
}
15.ProductServiceImpl.java
package com.sao.service.impl;
import com.sao.dao.ProductDao;
import com.sao.entity.Product;
import com.sao.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
public void saveProduct(Product product) {
productDao.saveProduct(product);
}
}
16.ProductAction.java
添加@Controller注解代表此时Action已交由Spring进行管理。但是Struts2对Action的默认作用域是多实例的(prototype),而Spring默认Bean的作用域是单实例的,所以需设置Action的作用域为多实例的
package com.sao.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sao.entity.Product;
import com.sao.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
/**
* 商品操作-控制层
*
*/
@Controller
@Scope("prototype")
public class ProductAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Autowired
private ProductService productService;
private String pname;
private double price;
/**
* 保存商品操作
*
* @return
*/
public String saveProduct() {
Product product = new Product(pname, price);
productService.saveProduct(product);
this.addActionMessage("保存成功...");
return SUCCESS;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public void validate() {
if(pname == null || "".equals(pname.trim())) {
this.addFieldError("pname", "商品名称不能为空");
}
}
}
17.index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增商品界面title>
head>
<body>
<h1>新增商品h1>
<s:actionmessage/>
<s:form action="product_save" method="post" namespace="/" theme="simple">
<table width="600px">
<tr>
<th>商品名称th>
<td><s:textfield name="pname"/>td>
<td><font color="red"><s:fielderror fieldName="pname"/>font>td>
tr>
<tr>
<th>商品价格th>
<td><s:textfield name="price"/>td>
<td><font color="red"><s:fielderror fieldName="price"/>font>td>
tr>
<tr>
<th colspan="2">
<input type="submit" value="保存"/>
th>
<th> th>
tr>
table>
s:form>
body>
html>
测试: