构建最基础的ssh框架-商品添加
写代码这件事和很多技术活一样,当你许久未接触之后就会生疏了。
前言
整合ssh,搭建一个框架,将配置文件,基本类完成,实现产品添加入库。
目录
创建一个WEB项目并引入jar包
引入框架的配置文件
创建包结构和页面
编写Action/Dao/Service
Spring整合Struts
Spring整合hibernate
添加事务管理
运行程序
参考
一、创建一个WEB项目并引入jar包
lib.png二、引入框架的配置文件
- struts.xml
- applicationContext.xml
- web.xml
- log4j.properties
1、web.xml
<!-- Spring的框架的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- struts2的框架的核心过滤器的配置 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、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>
</struts>
3、applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
</beans>
4、log4j.properties
log4j.rootLogger=WARN,stdout,logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${catalina.home}/logs/SSH.log
log4j.appender.logfile.MaxBackupIndex=100
log4j.appender.logfile.MaxFileSize=1024KB
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] [%l] - %m%n
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d %p]>> %l\: - %m%n
log4j.logger.org.hibernate=ERROR
log4j.logger.org.hibernate.SQL=ERROR
log4j.logger.org.hibernate.cache=ERROR
#ibatis rizhixiangguan
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout
#ibatis rizhixiangguan
log4j.logger.org.springframework=ERROR
log4j.logger.org.springframework.aop.framework=ERROR
log4j.appender.CONSOLE=org.apache.log4j.RollingFileAppender
log4j.appender.CONSOLE.File=${catalina.home}/logs/SSHConsole.log
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd hh\:mm\:ss} %-5p %c %x - %m%n
三、创建包结构和页面
1、新建包结构如下:
- |-renault.ssh
- |-action
- |-model
- |-Product
- |-service
- |-dao
2、在model包下新建 Product.java实体类:
package renault.ssh.model;
/***
* 商品的实体类
* @author Renault
*
*/
public class Product {
private Integer pid;
private String pname;
private Double price;
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
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;
}
}
3、新建添加商品页面addProduct.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>保存</title>
</head>
<body>
<h1>保存商品的页面</h1>
<!-- struts标签下有默认theme,如果自己用了simple就不会使用默认的样式 -->
<s:form action="" method="post" namespace="/" theme="simple">
<table boder="1" width="400px">
<tr>
<td>商品名称</td>
<td><s:textfield name="pname"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><s:textfield name="price"/></td>
</tr>
<tr>
<td clospan="2"><input type="submit" value="添加"></td>
</tr>
</table>
</s:form>
</body>
</html>
四、编写Action/Dao/Service
1、在Action包下新建ProductAction.java
package renault.ssh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import renault.ssh.model.Product;
import renault.ssh.service.ProductService;
/**
* 商品管理的Action类
* @author Renault
*
*/
public class ProductAction extends ActionSupport implements ModelDriven<Product>{
//模型驱动使用的类
private Product product = new Product();
public Product getModel() {
return product;
}
//struts和Sring整合过程中按名称自动注入的业务层类
private ProductService productService;
public void setProducrService(ProductService productService) {
this.productService = productService;
}
}
2、在Service包下新建ProductService.java
package renault.ssh.service;
import renault.ssh.dao.ProductDao;
/**
* 商品管理的服务类
* @author renault
*
*/
public class ProductService {
//业务层注入DAO的类
private ProductDao productDao;
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
}
3、在Dao包下新建ProductDao.java
package renault.ssh.dao;
/**
* 商品管理的Dao类
* @author Renault
*
*/
public class ProductDao {
}
五、Spring整合Struts
配置Action、Service、Dao类和配置文件
1、在applicationContext.xml里面配置action、dao、service类
<!-- 配置Action的类 -->
<!-- SCOPE的作用在于申明ACTION为多例模式 -->
<bean id="productAction" class="renault.ssh.action.ProductAction" scope="prototype">
<!-- 手动注入Service -->
<property name="producrService" ref="productService"/>
</bean>
<!--配置业务层的类 -->
<bean id="productService" class="renault.ssh.service.ProductService">
<property name="productDao" ref="productDao" />
</bean>
<!-- 配置Dao的类 -->
<bean id="productDao" class="renault.ssh.dao.ProductDao">
</bean>
2、配置struts.xml
<package name="ssh" extends="struts-default" namespace="/">
<!-- 由Spring管理的ACTION的class为Spring中的ID值,不再是类的全名 -->
<action name="product_*" class="productAction" method="{1}">
</action>
</package>
3、将addProduct.jsp里面的表单的action改成 action="product_save"
4、在ProductAction.java里添加保存方法:
/**
* 保存商品
*/
public String save(){
System.out.println("Action里面的save方法执行了");
productService.save(product);
return NONE;
}
5、在ProductService.java里添加保存方法:
/**
* 业务层保存商品
* @param product
*/
public void save(Product product) {
System.out.println("service里面的save方法执行了");
productDao.save(product);
}
6、在ProductDao.java里添加保存方法:
/**
* Dao里面保存商品
* @param product
*/
public void save(Product product) {
System.out.println("Dao里面的save方法执行了");
}
7、启动服务器,运行addProduct.jsp,填写商品名称和价格后提交在控制台会打印
Action里面的save方法执行了
Service里面的save方法执行了
Dao里面的save方法执行了
六、Spring整合hibernate
1、创建数据库;
>create database ssh;
2、创建实体类的映射文件Product.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="renault.ssh.model.Product" table="product">
<id name="pid" column="pid">
<generator class="native"/>
</id>
<property name="pname" column="pname" length="20"/>
<property name="price" column="price"/>
</class>
</hibernate-mapping>
3、添加配置文件 jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssh
jdbc.username=root
jdbc.password=admin
jdbc.maxActive=2000
jdbc.initialSize=20
jdbc.maxWait=2000
jdbc.minIdle=10
4、在applicationContext.xml配置hibernate
<!-- 引入外部的属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置hibernate相关属性 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!--注入连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 加载Hibernate中的映射文件 -->
<property name="mappingResources">
<list>
<!-- 文件路径 -->
<value>renault/ssh/model/Product.hbm.xml</value>
</list>
</property>
</bean>
5、在applicationContext.xml中的DAO里面注入sessionFactory
<!-- 配置Dao的类 -->
<bean id="productDao" class="renault.ssh.dao.ProductDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
6、修改ProductDao.java,调用模板完成保存的操作
package renault.ssh.dao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import renault.ssh.model.Product;
/**
* 商品管理的Dao类
* @author Renault
*
*/
//注入sessionFactory必须继承HibernateDaoSupport
public class ProductDao extends HibernateDaoSupport {
/**
* Dao里面保存商品
* @param product
*/
public void save(Product product) {
System.out.println("Dao里面的save方法执行了");
//调用模板的方法
this.getHibernateTemplate().save(product);
}
}
七、添加事务管理
1、配置事务管理器,在applicationContext.xml添加如下代码:
<!--配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
2、给ProductService.java类添加注解@Transactional
八、运行程序
保存商品页面.png控制台输出.png
数据库.png