文章目录
一、环境准备
1、数据库与表结构
(1)用户和数据库
数据库我们使用mysql,创建一个用户(并且授权)
用户名:ssm
密码:password
创建一个数据库:orcl
(2)数据表(product)
产品表信息描述
注意:本文所有的varchar2换成varchar。timestamp换成Date
创建表的SQL
USE `orcl`;
CREATE TABLE product(
id varchar(32) PRIMARY KEY,
productNum VARCHAR(50) NOT NULL,
productName VARCHAR(50),
cityName VARCHAR(50),
DepartureTime Date,
productPrice Double,
productDesc VARCHAR(500),
productStatus INT,
CONSTRAINT product UNIQUE (id, productNum)
);
--为product表中的id创建一个触发器
--触发器名字为id_product_trigger
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
TRIGGER `orcl`.`id_product_trigger` BEFORE INSERT
ON `orcl`.`product`
FOR EACH ROW BEGIN
SET new.id=REPLACE(UUID(),'-',''); -- 触发器执行的逻辑
END$$
DELIMITER ;
--插入数据
INSERT INTO PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
VALUES ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-001', '北京三日游',
'北京', '2012-12-21',1200, '不错的旅行', 1);
INSERT INTO PRODUCT (productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
VALUES ('itcast-002', '西安五日游', '上海', '2015-04-20', 1600, '我都我来了', 0);
INSERT INTO PRODUCT (productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
VALUES ('itcast-003', '海南三日游', '海南','2010-04-15', 4200, '说走就走', 0);
2、Maven工程的搭建
(1)创建一个父工程heima_ssm
创建父工程不使用骨架,注解快速创建。
(2)创建五个子模块
前四个不使用骨架,web使用webApp骨架
(3)导入pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.itheima.heima_ssm</groupId>
<artifactId>heima_ssm</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<oracle.version>11.2.0.1.0</oracle.version>
<mybatis.version>3.4.5</mybatis.version>
<spring.security.version>5.0.3.RELEASE</spring.security.version>
</properties>
<dependencies> <!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</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-web</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-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</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-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<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>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency> <!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>heima_ssm_dao</module>
<module>heima_ssm_domain</module>
<module>heima_ssm_service</module>
<module>heima_ssm_utils</module>
<module>heima_ssm_web</module>
</modules>
</project>
3、编写实体类
/**
* 产品信息
*/
public class Product {
private String id; // 主键
private String productNum; // 编号 唯一
private String productName; // 名称
private String cityName; // 出发城市
private Date departureTime; // 出发时间
private String departureTimeStr;//出发时间格式化的数据-------------
private double productPrice; // 产品价格
private String productDesc; // 产品描述
private Integer productStatus; // 状态 0 关闭 1 开启
private String productStatusStr;//状态格式化的数据------------------
public String getDepartureTimeStr() {
System.out.println("方法");
if (departureTime!=null){
System.out.println("if");
departureTimeStr = DateUtils.data2String(departureTime,"yyyy-MM-dd");
System.out.println("转换完毕");
}
return departureTimeStr;
}
public String getProductStatusStr() {
if(productStatus!=null){
//状态0关闭1开启
productStatusStr="关闭";
}
if(productStatus==1){
//状态0关闭1开启
productStatusStr="开启";
}
return productStatusStr;
}
}
4、编写工具类
package com.itheima.ssm.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
//日期转换成字符串
public static String data2String(Date dateTime, String patt){
SimpleDateFormat sdf = new SimpleDateFormat(patt);
String timeStr = sdf.format(dateTime);
return timeStr;
}
//字符串转为日期
public static Date string2Date(String dateStr, String patt) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat();
Date parse = sdf.parse(dateStr);
return parse;
}
}
5、编写业务层接口
public interface IProductService {
List<Product> findAll() throws Exception;
}
业务层实现类
@Service
@Transactional//事务控制
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductDao productDao;
@Override
public List<Product> findAll() throws Exception {
return productDao.findAll();
}
}
6、编写持久层接口
public interface IProductDao {
@Select("select * from product")
List<Product> findAll() throws Exception;
}
7、问题:为什么在SSM中的dao层不用写@Repository注解
在Spring配置Mybatis的文件中我们可以看到如下代码:
<!-- 扫描dao接口-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.ssm.dao"/>
</bean>
MapperScannerConfigurer
,让它扫描特定的包,自动帮我们成批地创建映射器。这样就大大减少了配置的工作量。
二、SSM整合与产品查询
1、applicationContext.xml配置文件
包括spring配置和spring整合mybatis的配置文件。
<?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"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描,管理service和dao -->
<context:component-scan base-package="com.itheima.ssm.service">
</context:component-scan>
<context:component-scan base-package="com.itheima.ssm.dao">
</context:component-scan>
<!--spring整合mybatis-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 把交给IOC管理 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 扫描dao接口-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.ssm.dao"/>
</bean>
<!-- 配置Spring的声明式事务管理 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--<tx:annotation-driven/> 就是支持事务注解的(@Transactional)-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
2、web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--spring整合springmvc-->
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 前端控制器(加载classpath:springmvc.xml 服务器启动创建servlet) -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 解决中文乱码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
3、spring-mvc配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描controller的注解,别的不扫描 -->
<context:component-scan base-package="com.itheima.ssm.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/" /><!-- JSP文件所在的目录 -->
<property name="suffix" value=".jsp" /><!-- 文件的后缀名 -->
</bean>
<!-- 设置静态资源不过滤 -->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/img/" mapping="/img/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/plugins/" mapping="/plugins/**" />
<!-- 开启对SpringMVC注解的支持 -->
<mvc:annotation-driven />
<!--
支持AOP的注解支持,AOP底层使用代理技术
JDK动态代理,要求必须有接口
cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
4、导入log4j.properties配置文件
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
# log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# log4j.appender.LOGFILE.File=d:\axis.log
# log4j.appender.LOGFILE.Append=true
# log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
# log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
5、编写ProductController
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private IProductService productService;
//查询全部产品
@RequestMapping("/findAll.do")
public ModelAndView findAll() throws Exception{
ModelAndView mv = new ModelAndView();
List<Product> ps = productService.findAll();
mv.addObject("productList",ps);
mv.setViewName("product-list");
return mv;
}
}
6、测试运行
index.jsp
URL:http://localhost:8888/heima_ssm_web/index.jsp重定向到main.jsp,main.jsp页面包含产品管理
超链接,点击跳转到product/findAll.do展示所需页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="/pages/main.jsp"></jsp:forward>
</body>
</html>
main.jsp
<a href="${pageContext.request.contextPath}/product/findAll.do">
<i class="fa fa-circle-o"></i> 产品管理
</a>
三、产品的添加功能
1、商品添加页面 product-add.jsp
页面详细代码请查看今天课程资料
2、Controller
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private IProductService productService;
@RequestMapping("/save.do")
public String save(Product product,String departureTime) throws Exception {
System.out.println("添加成功:"+departureTime);
productService.save(product);
System.out.println("product.getDepartureTime():"+product.getDepartureTime());
return "redirect:findAll.do";
}
//查询全部产品
@RequestMapping("/findAll.do")
public ModelAndView findAll() throws Exception{
ModelAndView mv = new ModelAndView();
List<Product> ps = productService.findAll();
mv.addObject("productList",ps);
mv.setViewName("product-list");
return mv;
}
}
3、Dao
public interface IProductDao {
@Select("select * from product")
List<Product> findAll() throws Exception;
@Insert("insert into product(productNum,productName,cityName,departureTime,productPrice,productDesc,productStatus)" +
"values(#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})")
void save(Product product) throws Exception;
}
4、日期格式化
实体类中加日期格式化注解
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date departureTime; // 出发时间
业务层自己编写。