JavaEE學習日誌(一百零四): ssm練習之產品模塊實現

創建項目

在這裏插入圖片描述
其中dao依賴domain,service依賴dao,web依賴service

編寫配置文件

父工程的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</groupId>
    <artifactId>ssm_parent_331</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>ssm_dao_331</module>
        <module>ssm_service_331</module>
        <module>ssm_web_331</module>
        <module>ssm_domain_331</module>
        <module>ssm_utils_331</module>
    </modules>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.0.2.RELEASE</spring.version>
        <spring.security.version>5.0.2.RELEASE</spring.security.version>
    </properties>

    <dependencies>
        <!-- spring相關的jar包 -->
        <!-- 容器 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 事務 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 測試 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!-- mybatis與Spring整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- AOP切面 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
        <!-- 數據源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- 單元測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- servletAPI -->
        <!-- JSP應用 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- servlet應用 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- 日誌記錄工具 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--oracle的jar包-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.2.0</version>
        </dependency>
        <!-- JSTL -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- 文件上傳 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </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>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
    </dependencies>
</project>

dao層的spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
    <!--引入屬性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--創建數據源對象-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--sqlSessionFactoryBean對象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


    <!--掃描dao包,掃描dao接口的動態代理對象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定dao接口的包路徑-->
        <property name="basePackage" value="com.itheima.dao"></property>
    </bean>

</beans>

service層的spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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.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">

    <!--引入持久層的配置文件-->
<!--    <import resource="classpath*:spring/applicationcontext-dao.xml"></import>-->
    <!--掃描包,創建業務層對象-->
    <context:component-scan base-package="com.itheima.service"></context:component-scan>
    <!--事務管理器對象-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--事務通知對象-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--aop切面-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service..*.*(..))"></aop:advisor>
    </aop:config>
</beans>

web層的spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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">
    <!--掃描包,創建web層對象-->
    <context:component-scan base-package="com.itheima.controller"></context:component-scan>
    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--開啓註解-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--靜態資源放行-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <!--創建類型轉換器工廠類對象-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.itheima.converter.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>
</beans>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/*.xml</param-value>
  </context-param>
  <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>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


產品模塊

查詢所有商品

ProductController

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductService productService;
    /**
     * 查詢全部
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        //準備數據
        List<Product> productList = productService.findAll();
        //創建modelandview
        ModelAndView modelAndView = new ModelAndView();
        //添加數據
        modelAndView.addObject("productList",productList);
        //指定頁面
        modelAndView.setViewName("product-list");
        return modelAndView;

    }
}

ProductService

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductDao productDao;
    @Override
    public List<Product> findAll() {
        return productDao.findAll();
    }
}

ProductDao

public interface ProductDao {
    @Select("select * from product")
    List<Product> findAll();
}

前端頁面

在這裏插入圖片描述

<tbody>
	<%--
		循環標籤foreach
		items:要循環的集合對象
		var:循環中的每一個對象
	--%>
	<c:forEach items="${productList}" var="product">
	<tr>
		<td><input name="ids" type="checkbox"></td>
		<td>${product.id}</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"></fmt:formatDate>
		</td>
		<td>${product.productPrice}</td>
		<td>${product.productStatus == 1?"開啓":"關閉"}</td>


		<td class="text-center">
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="all-order-manage-edit.html"'>訂單</button>
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="${pageContext.request.contextPath}/product/updateUI?id=${product.id}"'>修改</button>
		</td>
	</tr>
	</c:forEach>


</tbody>

添加產品

在這裏插入圖片描述

ProductController

/**
     * 保存產品
     * @param product
     * @return
     */
    @RequestMapping("/save")
    public String save(Product product){
        //保存操作
        productService.save(product);
        //跳轉查詢全部
        return "redirect:/product/findAll";
    }

ProductService

@Override
    public void save(Product product) {
        productDao.save(product);
    }

ProductDao

//@Insert("insert into product values(product_seq.nextval,#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})")
    //keyProperty 主鍵的屬性名
    //keyColumn 主鍵列名
    //before 在添加之前或之後獲取主鍵
    //resultType主鍵類型
    //statement 獲取主鍵的sql語句
        //mysql:select last_insert_id();
        //oracle:select product_seq.nextval from dual
    @SelectKey(keyProperty = "id", keyColumn = "id",before = true, resultType = Integer.class,
    statement = "select product_seq.nextval from dual" )
    @Insert("insert into product values(#{id},#{productNum},#{productName},#{cityName},#{departureTime},#{productPrice},#{productDesc},#{productStatus})")
    void save(Product product);

自定義類型轉換器StringToDate

類寫完之後,在spring-web.xml中,也需要添加配置

public class StringToDateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date = sdf.parse(s);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
<!--開啓註解-->
    <mvc:annotation-driven conversion-service="conversionService"/>

    <!--創建類型轉換器工廠類對象-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.itheima.converter.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

修改產品之數據回顯

ProductController

@RequestMapping("/updateUI")
    public ModelAndView updateUI(Integer id){
        //根據查詢產品對象
        Product product = productService.findById(id);
        //創建ModelAndView對象
        ModelAndView modelAndView = new ModelAndView();
        //添加數據
        modelAndView.addObject("product",product);
        //指定頁面
        modelAndView.setViewName("product-update");
        return modelAndView;
    }

ProductService

@Override
    public Product findById(Integer id) {
        return productDao.findById(id);
    }

ProductDao

在pojo中添加一個屬性爲departureTime,方便回顯String類型的日期

@Select("select p.*,to_char(departureTime,'yyyy-mm-dd hh24:mi') departureTimeStr from product p where id = #{id}")
Product findById(Integer id);

前端

前端顯示略

下拉菜單的正確顯示,id爲productStatus

<script type="text/javascript">
		//更改產品的狀態
		//productStatus option得到select的所有option
		//#productStatus option[value = 1]得到select中value=1的所有option
		//prop:設置標籤選擇性的屬性
		$("#productStatus option[value = ${product.productStatus}]").prop("selected","selected");
	</script>

修改產品

ProductController

@RequestMapping("/update")
    public String update(Product product){
        productService.update(product);
        return "redirect:/product/findAll";
    }

ProductService

/**
     * 更新產品
     * @param product
     */
    @Override
    public void update(Product product) {
        productDao.update(product);
    }

ProductDao

@Update("update product set productNum = #{productNum},productName = #{productName},cityName = #{cityName},departureTime = #{departureTime},productPrice = #{productPrice},productDesc = #{productDesc},productStatus = #{productStatus} where id = #{id}")
    void update(Product product);

刪除產品

ProductController

/**
     * 刪除單個產品
     * @param id
     * @return
     */
    @RequestMapping("/delOne")
    public String delOne(Integer id){
        //執行刪除操作
        productService.delOne(id);
        return "redirect:/product/findAll";
    }

ProductService

@Override
    public void delOne(Integer id) {
        productDao.delOne(id);
    }

ProductDao

/**
     * 根據id刪除產品
     * @param id
     */
    @Delete("delete from product where id = #{id}")
    void delOne(Integer id);

前端頁面

在這裏插入圖片描述

<script type="text/javascript">
		function delOne(id) {
			if(confirm("您確定要刪除嗎?")){
				//執行刪除操作
				location.href="${pageContext.request.contextPath}/product/delOne?id="+id;
			}
		}
	</script>

刪除多個產品

前端

  1. 首先用form表單,把顯示產品列表的代碼括起來(注意form表單需要放在table標籤外)
  2. 使用jQuery,點擊在form表單外的刪除按鈕,執行提交在這裏插入圖片描述
/刪除多個
		//刪除多個
		function delMany() {
			if(confirm("您確定要刪除選擇的產品嗎?")) {
				//獲取表單
				//document.forms 得到所有表單
				var delForm = $("#delForm");
				//表單提交
				//submit:表單對象執行提交操作
				delForm.submit();
			}
		}

ProductController

 /**
     * 刪除多個
     * @param ids
     * @return
     */
    @RequestMapping("/delMany")
    public String delMany(Integer[] ids){
        //執行刪除操作
        productService.delMany(ids);
        return "redirect:/product/findAll";
    }

ProductService

@Override
    public void delMany(Integer[] ids) {
        //判斷ids是否爲null
        if(ids!=null){
            //遍歷ids,刪除多個產品
            for (Integer id : ids) {
                productDao.delOne(id);
            }
        }
    }

ProductDao

/**
     * 根據id刪除產品
     * @param id
     */
    @Delete("delete from product where id = #{id}")
    void delOne(Integer id);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章