SSM项目02

5 篇文章 0 订阅
4 篇文章 0 订阅

第1章 产品介绍

1.1 数据库与表结构

产品表信息描述

序号字段名称字段类型字段描述
1idint(11)主键自增
2productNumvarchar(50)产品编号,唯一不为空
3productNamevarchar(50)产品名称
4cityNamevarchar(50)出发城市
5departureTimedate出发时间
6productPricefloat产品价格
7productDescvarchar(500)产品描述
8productStatusint(1)产品状态,0关闭,1开启

手动创建一个数据库叫ssm,里面搞一张产品表,创建表sql,为了方便实现主键自增

-- 建表
CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `productNum` varchar(50) DEFAULT NULL COMMENT '产品编号,唯一不为空',
  `productName` varchar(50) DEFAULT NULL COMMENT '产品名称',
  `cityName` varchar(50) DEFAULT NULL COMMENT '出发城市',
  `departureTime` date DEFAULT NULL COMMENT '出发时间',
  `productPrice` float DEFAULT NULL COMMENT '产品价格',
  `productDesc` varchar(500) DEFAULT NULL COMMENT '产品描述',
  `productStatus` int(1) DEFAULT NULL COMMENT '产品状态,0关闭,1开启',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

第2章 SSM集成

我们这里采用Maven项目分模块的方式实现,要创建的模块如下:

1. 创建ssm-parent父工程(打包方式选择pom,必须的)
2. 创建ssm-web子模块(打包方式是war包)
3. 创建ssm-service子模块(打包方式是jar包)
4. 创建ssm-dao子模块(打包方式是jar包)
5. 创建ssm-domain子模块(打包方式是jar包)
6. 创建ssm-util子模块(打包方式是jar包)
7. web依赖于service,service依赖于dao,dao依赖于domain,domain依赖util
2.1 ssm-parent
2.1.1pom.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.ywj</groupId>
  <artifactId>ssm-parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <modules>
    <module>../ssm-model</module>
      <module>../ssm-dao</module>
      <module>../ssm-service</module>
      <module>../ssm-web</module>
      <module>../ssm-util</module>
  </modules>
    
  <!--打包方式为pom-->
  <packaging>pom</packaging>

  <!--统一管理版本-->
  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
    <aspectjweaver.version>1.6.8</aspectjweaver.version>
    <junit.version>4.12</junit.version>
    <jsp-api.version>2.0</jsp-api.version>
    <servlet-api.version>2.5</servlet-api.version>
    <jstl.version>1.2</jstl.version>
    <mybatis-spring.version>1.3.0</mybatis-spring.version>
    <druid.version>1.0.9</druid.version>
    <jackson-version>2.9.6</jackson-version>
    <!--文件的编码格式-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <!--jar包管理,并不会将jar包导入到工程中-->
  <dependencyManagement>
    <!--引入依赖-->
    <dependencies>
      <!-- spring -->
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectjweaver.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <!--spring包-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <!--用于SpringMVC-->
      <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>

      <!--用于数据库源相关操作-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <!--ServletAPI-->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servlet-api.version}</version>
        <scope>provided</scope>
      </dependency>

      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>${jsp-api.version}</version>
        <scope>provided</scope>
      </dependency>

      <!--jstl标签-->
      <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
      </dependency>

      <!--MySQL数据库驱动-->
      <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>${mysql.version}</version>
      </dependency>

      <!--测试框架-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>compile</scope>
      </dependency>

      <!--
        用于JSON数据转换
        实现Json 互转 JavaBean
    -->
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson-version}</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson-version}</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson-version}</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>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
      </dependency>
      <!-- log end -->

      <!--mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
      </dependency>

      <!--MyBatis集成Spring-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring.version}</version>
      </dependency>

      <!--数据源-->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
    
</project>
2.1.2 创建工具包工程

紧接着我们把ssm-util也创建了,该工程用于提供工具类的。
创建jar包工程,名字叫ssm-util

在其中创建一个类,提供时间转字符串类型。

public class DateUtils {
    //时间格式
    public  static SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /***
     * 时间格式转换
     * @param date
     * @return
     */
    public static String dateToStr1(Date date){
        return simpleDateFormat1.format(date);
    }
}
2.2 ssm-model

创建Product

package com.zl.bean;

import java.io.Serializable;
import java.util.Date;

public class Product implements Serializable {
    private Integer id;
    private String productNum;
    private String productName;
    private String cityName;
    private Date departureTime;
    private Float productPrice;
    private String productDesc;
    private int productStatus;

    public Product() {
    }

    public Product(Integer id, String productNum, String productName, String cityName, Date departureTime, Float productPrice, String productDesc, int productStatus) {
        this.id = id;
        this.productNum = productNum;
        this.productName = productName;
        this.cityName = cityName;
        this.departureTime = departureTime;
        this.productPrice = productPrice;
        this.productDesc = productDesc;
        this.productStatus = productStatus;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getProductNum() {
        return productNum;
    }

    public void setProductNum(String productNum) {
        this.productNum = productNum;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public Date getDepartureTime() {
        return departureTime;
    }

    public void setDepartureTime(Date departureTime) {
        this.departureTime = departureTime;
    }

    public Float getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(Float productPrice) {
        this.productPrice = productPrice;
    }

    public String getProductDesc() {
        return productDesc;
    }

    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }

    public int getProductStatus() {
        return productStatus;
    }

    public void setProductStatus(int productStatus) {
        this.productStatus = productStatus;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", productNum='" + productNum + '\'' +
                ", productName='" + productName + '\'' +
                ", cityName='" + cityName + '\'' +
                ", departureTime=" + departureTime +
                ", productPrice=" + productPrice +
                ", productDesc='" + productDesc + '\'' +
                ", productStatus=" + productStatus +
                '}';
    }
}

在ssm-model的pom.xml中引入spring以及工具包的依赖

<!--依赖工具包-->
<dependencies>
	<!--工具包-->
    <dependency>
        <groupId>com.ywj</groupId>
        <artifactId>ssm-util</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
	
	<!--引用Spring的jar包是为了后续使用一个@DateTimeFormat注解来做日期格式转换的-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>
2.3 ssm-dao
2.2.1 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">
    <parent>
        <artifactId>ssm-parent</artifactId>
        <groupId>com.ywj</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../ssm-parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ssm-dao</artifactId>

    <!--引入依赖-->
    <dependencies>
        <!--model的依赖-->
        <dependency>
            <groupId>com.ywj</groupId>
            <artifactId>ssm-model</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>

        <!--MyBatis集成Spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </dependency>

        <!--数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>

       <!--MySQL数据库驱动-->
       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
       </dependency>

        <!--SpringJdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>

        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <!-- log end -->
    </dependencies>
    
</project>
2.2.2 spring-mybatis.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"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssm" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!--SqlSessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--接口扫描 MapperScannerConfigurer-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定Dao接口的包-->
        <property name="basePackage" value="com.ywj.mapper" />
        <!--
            指定SqlSessionFactoryBeanName
            在多数据源情况下,需要指定,这里不需要指定↓!
        -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean" />
    </bean>

</beans>
2.2.3 ProductDao.java
public interface ProductDao {}
2.3 ssm-service
2.3.1 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">
    <parent>
        <artifactId>ssm-parent</artifactId>
        <groupId>com.ywj</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../ssm-parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>ssm-service</artifactId>
    
    <!--打包jar-->
    <packaging>jar</packaging>

    <!--引入依赖-->
    <dependencies>
        <!--依赖dao-->
        <dependency>
            <groupId>com.ywj</groupId>
            <artifactId>ssm-dao</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
    </dependencies>

</project>
2.3.2 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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.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
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd">

	<!--引入mybatis集成配置-->
    <import resource="spring-mybatis.xml" />
    
    <!-- 事务传播特性配置 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!-- the transactional semantics... -->
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="modify*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />

            <!-- 查询方法 -->
            <tx:method name="query*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置事务管理器 -->
    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 声明式事务AOP配置 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.ywj.service.impl.*.*(..))"
                      id="tranpointcut" />
        <!-- 事务控制 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tranpointcut" />
    </aop:config>
    
</beans>
2.3.3 ProductService接口
public interface ProductService {}
2.3.4 ProductServiceImpl
@Service
public class ProductServiceImpl implements ProductService {}
2.4 ssm-web
2.4.1 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">
    <parent>
        <artifactId>ssm-parent</artifactId>
        <groupId>com.ywj</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../ssm-parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>ssm-web</artifactId>
    
    <!--默认是jar包,可以不写,但是web工程需要的是war包一定要写,父工程是pom包也一定要写-->
    <packaging>war</packaging>

    <dependencies>
        <!--依赖service-->
        <dependency>
            <groupId>com.ywj</groupId>
            <artifactId>ssm-service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

        <!--JSON转换-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>

        <!--servletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <!--插件-->
        <plugins>
            <!--tomcat插件-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!--插件使用的相关配置-->
                <configuration>
                    <!--端口号-->
                    <port>18081</port>
                    <!--写当前项目的名字(虚拟路径),如果写/,那么每次访问项目就不需要加项目名字了-->
                    <path>/</path>
                    <!--解决get请求乱码-->
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
</project>
2.4.2 web.xml
<?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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <!--POST编码过滤器-->
  <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>

  <!--前端核心控制器-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!--指定springmvc核心配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>

    <!--启动加载优先级-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!--映射拦截-->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
2.4.3 springmvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--包扫描-->
    <context:component-scan base-package="com" />

    <!--注解驱动-->
    <mvc:annotation-driven />

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/pages/" />
        <!--后缀-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--静态资源过滤-->
    <mvc:default-servlet-handler />

    <!--引入spring.xml-->
    <import resource="spring.xml" />
</beans>
2.4.4 ProductController,这个类之间写,不要否则下面的,否则idea有时候会当做kotlin代码处理↓!
@Controller
@RequestMapping(value = "/product")
public class ProductController {}

web层导入或者说拷贝,静态资源即资料文件夹里面的前端页面到webapp文件夹下面,目录结构如下↓

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zOGGxOaU-1602591002213)(assets/1600137335774.png)]

第3章 产品功能模块

3.1 所有产品查询
3.1.1 Controller实现
@Controller
@RequestMapping(value = "/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    /***
     * 商品列表查询
     * @param model
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Model model){
        //集合查询,封装数据到域对象并且请求转发用Model比较方便↓
        List<Product> products = productService.list();
        model.addAttribute("products",products);
        return "product-list";
    }
}
3.1.2 Service实现
//接口
public interface ProductService {	
    List<Product> list();
}

//接口实现
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Override
    public List<Product> list() {
        return productDao.list();
    }
}
3.1.3 Dao实现
public interface ProductDao {
    /**
     * 查询所有
     * @return
     */
    @Select("select * from product")
    List<Product> list();
}
3.1.4 页面显示 product-list.jsp
<!--数据列表-->
<table id="dataList"
	class="table table-bordered table-striped table-hover dataTable">
	<thead>
		<tr>
			<th class="" style="padding-right: 0px;"><input
				id="selall" type="checkbox" class="icheckbox_square-blue">
			</th>
			<th class="sorting">产品编号</th>
			<th class="sorting">产品名称</th>
			<th class="sorting">出发城市</th>
			<th class="sorting">出发日期</th>
			<th class="sorting">价格</th>
			<th class="sorting">描述</th>
			<th class="sorting">状态</th>
			<th class="text-center">操作</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${products}" var="product">
			<tr>
				<td><input name="ids" value="${product.id}" type="checkbox"></td>
				<td>${product.productNum}</td>
				<td>${product.productName}</td>
				<td>${product.cityName}</td>
				<td>
					${product.departureTime}
                 </td>
				<td>${product.productPrice}</td>
				<td>${product.productDesc}</td>
				<td>
					${product.productStatus}
				</td>
				<td class="text-center">
					<button type="button" class="btn bg-olive btn-xs"
						onclick='del(${product.id})'>删除</button>
					<button type="button" class="btn bg-olive btn-xs"
						onclick='location.href="/product/one?id=${product.id}"'>查看</button>
				</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<!--数据列表/-->
3.1.5 日期格式解决

JSP页面显示的日期为默认的英文日期,转换成字符串格式有2种方式。

3.1.5.1 方案一

使用fmt标签进行转换,简单直接在idea软件写formatDate来提示选择会自动导入对应的标签库↓

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<fmt:formatDate value="${product.departureTime }" pattern="yyyy-MM-dd hh:mm:ss"/>
3.1.5.2 方案二

在JavaBean中添加属性,重写该属性的get方法进行转换

//添加该属性
private String departureTimeStr;

/**
 * 重新get方法,返回字符串类型的时间
 * @return
 */
public String getDepartureTimeStr() {
	if(departureTime == null) {
		return "";
	}else {
		return DateUtils.dateToStr(departureTime, "yyyy-MM-dd HH:mm:ss");
	}
}

public class DateUtils {
    /**
     * 把日期转换成字符串
     * @param date
     * @return
     */
    public static String dateToStr(Date date,String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }
}
3.1.6 处理状态的问题

有2种方法实现

1)在JSP页面进行判断
<c:if test="${product.productStatus == 0 }">关闭</c:if>
<c:if test="${product.productStatus == 1 }">开启</c:if>

2)在JavaBean中添加属性,重写get方法
private String productStatusStr;
public String getProductStatusStr() {
	return productStatus == 0?"关闭":"开启";
}

多学一个标签判断choose,when,otherwise↓

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Gfz3YLeU-1602591002216)(assets/1593398989280.png)]

3.2 保存产品
3.2.1 Controller

在ProductController中增加2个方法,一个是跳转到增加页面,一个是实现增加,他们的访问路径一致,提交方式不一样。

/***
 * 新增页面跳转
 */
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(){
    return "product-add";
}

/***
 * 增加操作
 * @return
 */
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(Product product){
    //增加数据
    int acount = productService.add(product);
    return "redirect:/product/list";//重定向后台查询得到产品列表数据,重定向调用之前的查询方法即可!
}
3.2.2 Service

新增一个add方法

//接口
int add(Product product);

//实现类
@Override
public int add(Product product) {
    return productDao.add(product);
}
3.2.3 Dao

新增一个add方法,这里使用@Insert注解实现增加操作,代码如下:

/***
 * 增加操作
 * @param product
 * @return
 */
@Insert("insert into product(productNum,productName,cityName,departureTime,productPrice,productDesc,productStatus)values(#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})")
int add(Product product);
3.2.4 页面 product-add.jsp
<form action="${pageContext.request.contextPath}/product/add" method="post">
    <!-- 正文区域 -->
    <section class="content"> <!--产品信息-->

    <div class="panel panel-default">
       <div class="panel-heading">产品信息</div>
       <div class="row data-type">

         <div class="col-md-2 title">产品编号</div>
         <div class="col-md-4 data">
          <input type="text" class="form-control" name="productNum"
              placeholder="产品编号" value="">
         </div>
         <div class="col-md-2 title">产品名称</div>
         <div class="col-md-4 data">
          <input type="text" class="form-control" name="productName"
              placeholder="产品名称" value="">
         </div>
         <div class="col-md-2 title">出发时间</div>
         <div class="col-md-4 data">
          <div class="input-group date">
              <div class="input-group-addon">
                 <i class="fa fa-calendar"></i>
              </div>
              <input type="text" class="form-control pull-right"
                 id="datepicker-a3" name="departureTime">
          </div>
         </div>

         <div class="col-md-2 title">出发城市</div>
         <div class="col-md-4 data">
          <input type="text" class="form-control" name="cityName"
              placeholder="出发城市" value="">
         </div>

         <div class="col-md-2 title">产品价格</div>
         <div class="col-md-4 data">
          <input type="text" class="form-control" placeholder="产品价格"
              name="productPrice" value="">
         </div>

         <div class="col-md-2 title">产品状态</div>
         <div class="col-md-4 data">
          <select class="form-control select2" style="width: 100%"
              name="productStatus">
              <option value="0" selected="selected">关闭</option>
              <option value="1">开启</option>
          </select>
         </div>

         <div class="col-md-2 title rowHeight2x">其他信息</div>
         <div class="col-md-10 data rowHeight2x">
          <textarea class="form-control" rows="3" placeholder="其他信息"
              name="productDesc"></textarea>
         </div>

       </div>
    </div>
    <!--订单信息/--> <!--工具栏-->
    <div class="box-tools text-center">
       <button type="submit" class="btn bg-maroon">保存</button>
       <button type="button" class="btn bg-default"
         onclick="history.back(-1);">返回</button>
    </div>
    <!--工具栏/--> </section>
    <!-- 正文区域 /-->
</form>
3.2.5 解决日期问题

在进行数据绑定的时候,日期出现了异常,该格式的日期不支持默认数据类型转换,比如前端出发时间是String字符串,而后面实体类接收的成员变量出发时间时Date类型,就会报如下错误,解决方案有三种,一般选择在实体类加注解↓

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-926qy9q5-1602591002218)(assets/1600153209193.png)]

3.2.5.1 自定义类型转换器

自定义类型转换器(比较麻烦,回去看第一天文档)

3.2.5.2 在实体类的成员变量departureTime属性上添加@DateTimeFormat日期时间格式化注解解决即可!
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")//在类上打个@提示即可,前提是要导入spring的jar包依赖!
private Date departureTime;
3.2.5.3 @InitBinder

在Controller类中添加方法,进行类型转换(可以把这个方法抽取到一个父类,然后让Controller类继承它复用也行!)

/**
 * 类型转换
 * @param dataBinder
 */
@InitBinder
public void initBinderDate(WebDataBinder dataBinder) {
	dataBinder.registerCustomEditor(Date.class, new PropertiesEditor() {
		// JSP页面传过来的数据
		public void setAsText(String text) throws IllegalArgumentException {
			// 把字符串转换成日期
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				Date date = sdf.parse(text);
				// 设置值
				super.setValue(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	});
}
3.3 修改产品
3.3.1 Controller

增加2个方法,一个是根据id查询产品,一个是保存方法

/***
 * 查询单个
 * @param id
 * @param model
 * @return
 */
@RequestMapping(value = "/one")
public String getById(Long id,Model model){
    Product product = productService.getById(id);
    model.addAttribute("product",product);
    return "product-update";
}

/***
 * 修改产品
 * @return
 */
@RequestMapping(value = "/update")
public String update(Product product){
    int mcount = productService.update(product);
    return "redirect:/product/list";
}
3.3.2 Service

分别在接口和实现类中新增2个方法

//接口 ProductService
Product getById(Long id);
int update(Product product); 

//实现类 ProductServiceImpl
@Override
public Product getById(Long id) {
    return productDao.getById(id);
}

@Override
public int update(Product product) {
    return productDao.update(product);
}
3.3.3 Dao

新增2个方法,一个根据ID查询,一个修改方法。

/**
 * 根据ID查询
 * @param id
 * @return
 */
@Select("select * from product where id=#{id}")
Product getById(Long id);

/***
 * 修改操作
 * @param product
 * @return
 */
@Update("update product set productNum = #{productNum},productName=#{productName},cityName=#{cityName},departureTime=#{departureTime},productPrice=#{productPrice},productDesc=#{productDesc},productStatus=#{productStatus} where id = #{id}")
int update(Product product);
3.3.4 页面 product-update.jsp,主要修改产品状态开关下拉选择项的回显,简单,已经改好↓
<form action="${pageContext.request.contextPath}/product/update2?id=${product.id}"
     method="post">
   <%--通过隐藏域传入id到后台的产品对象,无须自己手动赋值给对象,这样比较方便,不用上面的?问号请求参数来传递id到后台!--%>
   <input type="hidden" name="id" value="${product.id}">
   <!-- 正文区域 -->
   <section class="content"> <!--产品信息-->

      <div class="panel panel-default">
         <div class="panel-heading">产品信息</div>
         <div class="row data-type">

            <div class="col-md-2 title">产品编号</div>
            <div class="col-md-4 data">
               <input type="text" class="form-control" name="productNum"
                     placeholder="产品编号" value="${product.productNum}"
                     readonly="readonly">
            </div>
            <div class="col-md-2 title">产品名称</div>
            <div class="col-md-4 data">
               <input type="text" class="form-control" name="productName"
                     placeholder="产品名称" value="${product.productName}">
            </div>
            <div class="col-md-2 title">出发时间</div>
            <div class="col-md-4 data">
               <div class="input-group date">
                  <div class="input-group-addon">
                     <i class="fa fa-calendar"></i>
                  </div>
                  <input type="text" class="form-control pull-right"
                        id="datepicker-a3" name="departureTime"
                        value="<fmt:formatDate value="${product.departureTime}" pattern="yyyy-MM-dd HH:mm:ss"></fmt:formatDate>">
               </div>
            </div>


            <div class="col-md-2 title">出发城市</div>
            <div class="col-md-4 data">
               <input type="text" class="form-control" name="cityName"
                     placeholder="出发城市" value="${product.cityName}">
            </div>

            <div class="col-md-2 title">产品价格</div>
            <div class="col-md-4 data">
               <input type="text" class="form-control" placeholder="产品价格"
                     name="productPrice" value="${product.productPrice}">
            </div>

            <div class="col-md-2 title">产品状态</div>
            <div class="col-md-4 data">
               <select class="form-control select2" style="width: 100%"
                     name="productStatus">
                  <%--主要修改产品状态开关下拉选择项的回显,简单,已经改好--%>
                  <c:if test="${product.productStatus == 0 }">
                     <option value="0" selected="selected">关闭</option>
                     <option value="1">开启</option>
                  </c:if>
                  <c:if test="${product.productStatus == 1 }">
                     <option value="0">关闭</option>
                     <option value="1" selected="selected">开启</option>
                  </c:if>
               </select>
            </div>

            <div class="col-md-2 title rowHeight2x">其他信息</div>
            <div class="col-md-10 data rowHeight2x">
               <textarea class="form-control" rows="3" placeholder="其他信息"
                       name="productDesc">${product.productDesc}</textarea>
            </div>

         </div>
      </div>
      <!--订单信息/--> <!--工具栏-->
      <div class="box-tools text-center">
         <button type="submit" class="btn bg-maroon">修改</button>
         <button type="button" class="btn bg-default"
               οnclick="history.back(-1);">返回</button>
      </div>
      <!--工具栏/--> </section>
   <!-- 正文区域 /-->
</form>
3.4 删除产品
3.4.1 Controller层
/***
 * 根据ID删除
 * @param id
 * @return
 */
@RequestMapping(value = "/delete")
public String delete(Integer id){
    int dcount = productService.deleteById(id);
    return "redirect:/product/list";
}
3.4.2 Service层
//接口
int deleteById(Integer id);

//实现类
@Override
public int deleteById(Integer id) {
    return productDao.deleteById(id);
}
3.4.3 Dao层
/***
 * 删除操作
 * @param id
 * @return
 */
@Delete("delete from product where id=#{id}")
int deleteById(Integer id);
3.4.4 页面 product-list.jsp
<!--数据列表-->
<table id="dataList"
      class="table table-bordered table-striped table-hover dataTable">
   <thead>
   <tr>
      <th class="" style="padding-right: 0px;"><input
            id="selall" type="checkbox" class="icheckbox_square-blue">
      </th>
      <th class="sorting">产品编号</th>
      <th class="sorting">产品名称</th>
      <th class="sorting">出发城市</th>
      <th class="sorting">出发日期</th>
      <th class="sorting">价格</th>
      <th class="sorting">描述</th>
      <th class="sorting">状态</th>
      <th class="text-center">操作</th>
   </tr>
   </thead>
   <tbody>
   <c:forEach items="${products}" var="product">
      <tr>
         <td><input name="ids" value="${product.id}" type="checkbox"></td>
         <td>${product.productNum}</td>
         <td>${product.productName}</td>
         <td>${product.cityName}</td>
         <td>
               <fmt:formatDate value="${product.departureTime}" pattern="yyyy-MM-dd HH:mm:ss"></fmt:formatDate>
         </td>
         <td>${product.productPrice}</td>
         <td>${product.productDesc}</td>
         <td>
            <c:if test="${product.productStatus == 0 }">关闭</c:if>
            <c:if test="${product.productStatus == 1 }">开启</c:if>
         </td>
         <td class="text-center">
            <button type="button" class="btn bg-olive btn-xs"
                  οnclick="f(${product.id})">删除</button>
            <button type="button" class="btn bg-olive btn-xs"
                  οnclick='location.href="/product/update?id=${product.id}"'>修改</button>
         </td>
      </tr>
   </c:forEach>
   </tbody>
</table>
<!--数据列表/-->

<%--最下面写个js来响应删除点击事件--%>
<script>
	function f(id) {
		var flag = confirm("您确定要删除吗");
        if (flag) {
            location.href="/product/delete?id="+id
        }
    }
</script>

第4章 订单模块功能

4.1 订单表与产品表的关系
  1. 一个用户只会产生一个订单,一个订单只能选择一个产品,因为是旅游产品。
  2. 一个产品可以被多个订单所选择。
  3. 订单表与产品表的关系是多对一
  4. 订单表的SQL语句
  5. 订单表信息描述 orders
序号字段名称字段类型字段描述
1idbigint(20)主键自增
2orderNumvarchar(20)订单编号,唯一值
3orderTimedate下单时间
4peopleCountint(5)出行人数
5orderDescvarchar(500)订单描述
6payTypeint(1)支付方式(0支付宝,1微信,2其他)
7orderStatusint(1)订单状态(0未支付,1已支付)
8productIdbigint(20)产品ID外键

productId描述了订单与产品之间的关系。

4.2 创建表sql
CREATE TABLE `orders` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
  `orderNum` varchar(20) NOT NULL COMMENT '订单编号,唯一值',
  `orderTime` date DEFAULT NULL COMMENT '下单时间',
  `peopleCount` int(5) DEFAULT NULL COMMENT '出行人数',
  `orderDesc` varchar(500) DEFAULT NULL COMMENT '订单描述',
  `payType` int(1) DEFAULT NULL COMMENT '支付方式(0支付宝,1微信,2其他)',
  `orderStatus` int(1) DEFAULT NULL COMMENT '订单状态(0未支付,1已支付)',
  `productId` bigint(20) DEFAULT NULL COMMENT '产品ID外键',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.3 搭建订单模块的环境
4.3.1 创建Orders
package com.zl.bean;

import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

public class Orders implements Serializable {
    private Long id;
    private String orderNum;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
    private Date orderTime;
    private Integer peopleCount;
    private String orderDesc;
    private Integer payType;
    private Integer orderStatus;
    //private Long productId;
    //一对一映射关系
    private Product product;

    public Orders() {
    }

    public Orders(Long id, String orderNum, Date orderTime, Integer peopleCount, String orderDesc, Integer payType, Integer orderStatus, Product product) {
        this.id = id;
        this.orderNum = orderNum;
        this.orderTime = orderTime;
        this.peopleCount = peopleCount;
        this.orderDesc = orderDesc;
        this.payType = payType;
        this.orderStatus = orderStatus;
        this.product = product;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOrderNum() {
        return orderNum;
    }

    public void setOrderNum(String orderNum) {
        this.orderNum = orderNum;
    }

    public Date getOrderTime() {
        return orderTime;
    }

    public void setOrderTime(Date orderTime) {
        this.orderTime = orderTime;
    }

    public Integer getPeopleCount() {
        return peopleCount;
    }

    public void setPeopleCount(Integer peopleCount) {
        this.peopleCount = peopleCount;
    }

    public String getOrderDesc() {
        return orderDesc;
    }

    public void setOrderDesc(String orderDesc) {
        this.orderDesc = orderDesc;
    }

    public Integer getPayType() {
        return payType;
    }

    public void setPayType(Integer payType) {
        this.payType = payType;
    }

    public Integer getOrderStatus() {
        return orderStatus;
    }

    public void setOrderStatus(Integer orderStatus) {
        this.orderStatus = orderStatus;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", orderNum='" + orderNum + '\'' +
                ", orderTime=" + orderTime +
                ", peopleCount=" + peopleCount +
                ", orderDesc='" + orderDesc + '\'' +
                ", payType=" + payType +
                ", orderStatus=" + orderStatus +
                ", product=" + product +
                '}';
    }
}
4.3.2 订单查询
4.3.2.1 创建Controller
@Controller
@RequestMapping(value = "/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /***
     * 订单列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Model model){
        List<Orders> orders = ordersService.list();
        model.addAttribute("orders",orders);
        return "order-list";
    }
}
4.3.2.2 Service
//接口
public interface OrdersService {
    List<Orders> list();
}

//实现类
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersDao ordersDao;

    @Override
    public List<Orders> list() {
        return ordersDao.list();
    }
}
4.3.2.3 Dao
public interface OrdersDao {
    /**
     * 查询所有
     *
     * @return
     */
    @Select("select o.id as oid,o.orderNum,o.orderTime,o.peopleCount,o.orderDesc,o.payType,o.orderStatus,p.* from orders o,product p where o.productId = p.id")
    @Results(value = {
            @Result(id = true, property = "id", column = "oid"),
            @Result(property = "orderNum", column = "orderNum"),
            @Result(property = "orderTime", column = "orderTime"),
            @Result(property = "peopleCount", column = "peopleCount"),
            @Result(property = "orderDesc", column = "orderDesc"),
            @Result(property = "payType", column = "payType"),
            @Result(property = "orderStatus", column = "orderStatus"),
            @Result(property = "product.id", column = "id"),
            @Result(property = "product.productNum", column = "productNum"),
            @Result(property = "product.productName", column = "productName"),
            @Result(property = "product.cityName", column = "cityName"),
            @Result(property = "product.departureTime", column = "departureTime"),
            @Result(property = "product.productPrice", column = "productPrice"),
            @Result(property = "product.productDesc", column = "productDesc"),
            @Result(property = "product.productStatus", column = "productStatus")
    })
    List<Orders> list();
}
4.3.2.4 页面 order-list.jsp
<!--数据列表-->
<table id="dataList"
       class="table table-bordered table-striped table-hover dataTable">
    <thead>
        <tr>
            <th class="" style="padding-right: 0px;"><input
                                                            id="selall" type="checkbox" class="icheckbox_square-blue">
            </th>
            <th class="sorting_asc">ID</th>
            <th class="sorting">订单号</th>
            <th class="sorting">路线名称</th>
            <th class="sorting">出发日期</th>
            <th class="sorting">申请日期</th>
            <th class="sorting">状态</th>
            <th class="sorting">支付</th>

            <th class="text-center">操作</th>
        </tr>
    </thead>
    
    <tbody>
        <c:forEach items="${orders}" var="order">
            <tr>
                <td><input name="ids" type="checkbox"></td>
                <td>${order.id}</td>
                <td>${order.orderNum}</td>
                <td>${order.product.productName}</td>
               <td><fmt:formatDate value="${order.product.departureTime}" pattern="yyyy-MM-dd HH:mm" /></td>
                <td>
                    <fmt:formatDate value="${order.orderTime}" pattern="yyyy-MM-dd HH:mm" />
                </td>
                <td>
                    <c:choose>
                        <c:when test="${order.orderStatus==0}">未支付</c:when>
                        <c:otherwise>已支付</c:otherwise>
                    </c:choose>
                </td>
                <td>
                    <c:choose>
                        <c:when test="${order.payType==0}">支付宝</c:when>
                        <c:when test="${order.payType==1}">微信</c:when>
                        <c:otherwise>其他</c:otherwise>
                    </c:choose>
                </td>
                <td class="text-center">
                    <button type="button" class="btn bg-olive btn-xs"
                            οnclick='location.href="${pageContext.request.contextPath}/pages/order-show.jsp"'>订单</button>
                    <button type="button" class="btn bg-olive btn-xs"
                            οnclick='location.href="${pageContext.request.contextPath}/pages/order-show.jsp"'>查看</button>
                </td>
            </tr>
        </c:forEach>
    </tbody>

</table>
<!--数据列表/-->
4.3.3 新增订单
4.3.3.1 Controller

新增2个方法,分别实现页面跳转和保存订单操作。在这里,页面需要加载产品信息供用户选择,所以需要注入ProductService来实现查询.

@Autowired
private ProductService productService;

/**
 * 增加页面跳转,即点击新建按钮,后台查询产品列表数据,存到域对象,请求转发到order-add.jsp,回显产品信息!
 * @return
 */
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(Model model){
    //查询所有产品信息,页面需要加载,所以需要注入ProductService来实现查询
    List<Product> products = productService.findAll();
    model.addAttribute("plist",products);//add.jsp里面用的是plist所以改为这个
    return "order-add";
}

/**
 * 保存操作
 * @param orders
 * @return
 */
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(Orders orders){
    int acount = ordersService.add(orders);
    return "redirect:/orders/list";
}
4.3.3.2 Service
//接口
int add(Orders orders);

//实现类
@Override
public int add(Orders orders) {
    return ordersDao.add(orders);
}
4.3.3.3 Dao
/**
 * 插入数据操作,插入时,注意属性的属性,即订单对象orders里面的产品Product对象里面的id,写#{product.id}
 * @param orders
 * @return
 */
@Insert("insert into orders (orderNum,orderTime,peopleCount,orderDesc,payType,orderStatus,productId) values (#{orderNum},#{orderTime},#{peopleCount},#{orderDesc},#{payType},#{orderStatus},#{product.id})")
int add(Orders orders);

order-list.jsp,点击新建按钮,跳转后台地址↓

<!--工具栏-->
<div class="pull-left">
   <div class="form-group form-inline">
      <div class="btn-group">
         <button type="button" class="btn btn-default" title="新建"
            οnclick='location.href="/orders/add"'>
            <i class="fa fa-file-o"></i> 新建
         </button>
      </div>
   </div>
</div>
<div class="box-tools pull-right">
   <div class="has-feedback">
      <input type="text" class="form-control input-sm"
         placeholder="搜索"> <span
         class="glyphicon glyphicon-search form-control-feedback"></span>
   </div>
</div>
<!--工具栏/-->

order-add.jsp表单提交后台地址↓

<!-- 正文区域 -->
<section class="content"> <!--订单信息-->
<form action="${pageContext.request.contextPath}/orders/add" method="post">
   
   <div class="panel panel-default">
      <div class="panel-heading">订单信息</div>
      <div class="row data-type">

         <div class="col-md-2 title">订单编号</div>
         <div class="col-md-4 data">
            <input type="text" class="form-control" placeholder="订单编号"
                name="orderNum">
         </div>

         <div class="col-md-2 title">下单时间</div>
         <div class="col-md-4 data">
            <div class="input-group date">
               <div class="input-group-addon">
                  <i class="fa fa-calendar"></i>
               </div>
               <input type="text" class="form-control pull-right"
                  id="datepicker-a3" name="orderTime" >
            </div>
         </div>
         <div class="col-md-2 title">出行人数</div>
         <div class="col-md-4 data">
            <input type="text" class="form-control" placeholder="出行人数"
                name="peopleCount">
         </div>

         <div class="col-md-2 title">支付方式</div>
         <div class="col-md-4 data">
            <select class="form-control select2" style="width: 100%"
               name="payType">
               <option value="0" selected="selected">支付宝</option>
               <option value="1">微信</option>
               <option value="2">其他</option>
            </select>
         </div>
         
         <div class="col-md-2 title">订单状态</div>
         <div class="col-md-4 data">
            <select class="form-control select2" style="width: 100%"
               name="orderStatus">
               <option value="0" selected="selected">未支付</option>
               <option value="1">已支付</option>
            </select>
         </div>
         
         <div class="col-md-2 title">选择产品</div>
         <div class="col-md-4 data">
            <select class="form-control select2" style="width: 100%"
               name="product.id">
               
               <c:forEach items="${ plist }" var="p">
                  <option value="${ p.id }" >${ p.productName }</option>
               </c:forEach>
               
            </select>
         </div>

         <div class="col-md-2 title rowHeight2x">订单描述</div>
         <div class="col-md-10 data rowHeight2x">
            <textarea class="form-control" rows="3" placeholder="订单描述" name="orderDesc">
         </textarea>
         </div>

      </div>
   </div>
   <!--订单信息/-->
   
   
   <!--工具栏-->
   <div class="box-tools text-center">
      <button type="submit" class="btn bg-maroon">保存</button>
      <button type="button" class="btn bg-default"
         οnclick="history.back(-1);">返回</button>
   </div>
</form>
<!--工具栏/--> </section>
<!-- 正文区域 /-->
重点:
SSM集成
增加订单
订单查询
时间格式处理
熟练@Insert、@Select、@Update、@Delete注解的使用

type=“text” class=“form-control” placeholder=“出行人数”
name=“peopleCount”>

     <div class="col-md-2 title">支付方式</div>
     <div class="col-md-4 data">
        <select class="form-control select2" style="width: 100%"
           name="payType">
           <option value="0" selected="selected">支付宝</option>
           <option value="1">微信</option>
           <option value="2">其他</option>
        </select>
     </div>
     
     <div class="col-md-2 title">订单状态</div>
     <div class="col-md-4 data">
        <select class="form-control select2" style="width: 100%"
           name="orderStatus">
           <option value="0" selected="selected">未支付</option>
           <option value="1">已支付</option>
        </select>
     </div>
     
     <div class="col-md-2 title">选择产品</div>
     <div class="col-md-4 data">
        <select class="form-control select2" style="width: 100%"
           name="product.id">
           
           <c:forEach items="${ plist }" var="p">
              <option value="${ p.id }" >${ p.productName }</option>
           </c:forEach>
           
        </select>
     </div>

     <div class="col-md-2 title rowHeight2x">订单描述</div>
     <div class="col-md-10 data rowHeight2x">
        <textarea class="form-control" rows="3" placeholder="订单描述" name="orderDesc">
     </textarea>
     </div>

  </div>
保存 返回
```
重点:
SSM集成
增加订单
订单查询
时间格式处理
熟练@Insert、@Select、@Update、@Delete注解的使用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值