JAVAEE——ssm綜合練習:CRM系統(包含ssm整合)


CRM項目外觀

 

 

 

1. 開發環境

IDE Eclipse Mars2 

Jdk: 1.7

數據庫: MySQL

2. 創建數據庫

數據庫sql文件位置如下圖:

 

 

 

創建crm數據庫,執行sql

 

 

效果如下圖:

 

 

3. 工程搭建

使用的Bootstrap前端框架,官方網站

http://www.bootcss.com/

 

工程使用Springmvcspringmybatis框架整合完成。

 

3.1. 需要的jar

  1. spring(包括springmvc
  2. mybatis
  3. mybatis-spring整合包
  4. 數據庫驅動
  5. 第三方連接池。
  6. Json依賴包Jackson

 

jar包位置如下圖:

 

 

3.2. 整合思路

Dao層:

1、SqlMapConfig.xml,空文件即可,但是需要文件頭。

2、applicationContext-dao.xml

a) 數據庫連接Druid

b) SqlSessionFactory對象,需要springmybatis整合包下的。

c) 配置mapper文件掃描器。Mapper動態代理開發 增強版

 

Service層:

1、applicationContext-service.xml包掃描器,掃描@service注解的類。

2、applicationContext-trans.xml配置事務。

 

Controller層:

1、Springmvc.xml

a) 包掃描器,掃描@Controller注解的類。

b) 配置注解驅動

c) 配置視圖解析器

 

Web.xml文件:

1、配置spring監聽器

2、配置前端控制器。

 

3.3. 創建工程

創建動態web工程,步驟如下圖:

 

 

 

創建boot-crm,如下圖

 

 

 

3.4. 加入jar

加入課前資料中的jar

 

3.5. 加入配置文件

創建config資源文件夾,在里面創建mybatisspring文件夾

3.5.1. SqlMapConfig.xml

空文件即可

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

當然也可以加上包別名,在后面的Mapper xml文件中可以不用寫全類名

<typeAliases>
<package name="com.xyp.crm.entity"/>
</typeAliases>

 

3.5.2. applicationContext-dao.xml

需要配置:

加載properties文件,數據源,SqlSessionFactoryMapper掃描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 配置 讀取properties文件 jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 配置 數據源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 設置MyBatis核心配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
        <!-- 設置數據源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置Mapper掃描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 設置Mapper掃描包 -->
        <property name="basePackage" value="cn.itcast.crm.mapper" />
    </bean>
</beans>

 

 

3.5.3. jdbc.properties

配置數據庫信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

 

 

3.5.4. log4j.properties

配置日志信息

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 

 

3.5.5. applicationContext-service.xml

配置service掃描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 配置Service掃描 -->
    <context:component-scan base-package="cn.itcast.crm.service" />
</beans>

 

 

3.5.6. applicationContext-trans.xml

配置事務管理:事務管理器、通知、切面

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 事務管理器 -->
    <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行為 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* cn.itcast.crm.service.*.*(..))" />
    </aop:config>

</beans>

 

 

3.5.7. Springmvc.xml

配置SpringMVC表現層:Controller掃描、注解驅動、視圖解析器

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配置Controller掃描 -->
    <context:component-scan base-package="cn.itcast.crm.controller" />

    <!-- 配置注解驅動 -->
    <mvc:annotation-driven />

    <!-- 配置視圖解析器 -->
    <bean    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后綴 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

 

 

3.5.8. Web.xml

配置SpringSpringMVC、解決post亂碼問題

<?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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>boot-crm</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>

    <!-- 配置監聽器加載spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置過濾器,解決post的亂碼問題 -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置SpringMVC -->
    <servlet>
        <servlet-name>boot-crm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <!-- 配置springmvc什么時候啟動,參數必須為整數 -->
        <!-- 如果為0或者大於0,則springMVC隨着容器啟動而啟動 -->
        <!-- 如果小於0,則在第一次請求進來的時候啟動 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>boot-crm</servlet-name>
        <!-- 所有的請求都進入springMVC -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

3.6. 加入靜態資源

最終效果如下圖:

 

 

4. 實現頁面展示

4.1. 代碼實現

編寫CustomerController 顯示用戶列表

@Controller
@RequestMapping("customer")
public class CustomerController {

    /**
     * 顯示用戶列表
     * 
     * @return
     */
    @RequestMapping("list")
    public String queryCustomerList() {
        return "customer";
    }

}

 

 

4.2. 頁面顯示問題

訪問頁面,發現不能正常顯示

 

 

打開開發者工具,選擇Network

發現cssjs等資源文件無法加載

 

 

 

原因:web.xml配置時,是設置所有的請求都進入SpringMVC。但是SpringMVC    無法處理cssjs等靜態資源,所以無法正常顯示

 

解決方案:

 

方法一:通過mvc:resources

    <!-- 對靜態資源進行放行 -->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/fonts/" mapping="/fonts/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

 

 

方法二:

springmvc.xml中配置

    <!-- 解決靜態資源無法被springMVC處理的問題 -->
    <mvc:default-servlet-handler />

 方法三:

修改web.xml,讓所有以action結尾的請求都進入SpringMVC

    <servlet-mapping>
        <servlet-name>boot-crm</servlet-name>
        <!-- 所有的請求都進入springMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

 

 

解決后的效果如下圖,可以正常顯示頁面樣式:

 

 

 

我們使用第二種方式解決,因為此項目中的頁面的請求都是以action結尾的,所以使用第二種方式,在web.xml里面進行相應的配置

    <servlet-mapping>
        <servlet-name>boot-crm</servlet-name>
        <!-- 所有以action結尾的請求都進入springMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

 

 

5. 實現查詢條件初始化

5.1. 需求分析

 

 

頁面效果如上圖,在查詢客戶的時候,可以選擇客戶來源,所屬行業,客戶級別信息,頁面加載時需要初始化查詢條件下拉列表。

 

前端jsp邏輯

<form class="form-inline" action="${pageContext.request.contextPath }/customer/list.action" method="get">
    <div class="form-group">
        <label for="customerName">客戶名稱</label> 
        <input type="text" class="form-control" id="customerName" value="${custName }" name="custName">
    </div>
    <div class="form-group">
        <label for="customerFrom">客戶來源</label> 
        <select    class="form-control" id="customerFrom" placeholder="客戶來源" name="custSource">
            <option value="">--請選擇--</option>
            <c:forEach items="${fromType}" var="item">
                <option value="${item.dict_id}"<c:if test="${item.dict_id == custSource}"> selected</c:if>>${item.dict_item_name }</option>
            </c:forEach>
        </select>
    </div>
    <div class="form-group">
        <label for="custIndustry">所屬行業</label> 
        <select    class="form-control" id="custIndustry"  name="custIndustry">
            <option value="">--請選擇--</option>
            <c:forEach items="${industryType}" var="item">
                <option value="${item.dict_id}"<c:if test="${item.dict_id == custIndustry}"> selected</c:if>>${item.dict_item_name }</option>
            </c:forEach>
        </select>
    </div>
    <div class="form-group">
        <label for="custLevel">客戶級別</label>
        <select    class="form-control" id="custLevel" name="custLevel">
            <option value="">--請選擇--</option>
            <c:forEach items="${levelType}" var="item">
                <option value="${item.dict_id}"<c:if test="${item.dict_id == custLevel}"> selected</c:if>>${item.dict_item_name }</option>
            </c:forEach>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">查詢</button>
</form>

 

按照jsp的要求,把對應的數據查詢出來,放到模型中。

數據存放在base_dict表,可以使用dict_type_code類別代碼進行查詢

使用需要獲取的數據如下圖:

 

 

 

使用的sql:

SELECT * FROM base_dict WHERE dict_type_code = '001'

 

5.2. 實現DAO開發

5.2.1. pojo

因為頁面顯示的名字是下划線方式,和數據庫表列名一樣,根據頁面的樣式,編寫pojo

public class BaseDict {
    private String dict_id;
    private String dict_type_code;
    private String dict_type_name;
    private String dict_item_name;
    private String dict_item_code;
    private Integer dict_sort;
    private String dict_enable;
    private String dict_memo;
get/set。。。。。。
}

 

5.2.2. Mapper

編寫BaseDictMapper

public interface BaseDictMapper {
    /**
     * 根據類別代碼查詢數據
     * 
     * @param dictTypeCode
     * @return
     */
    List<BaseDict> queryBaseDictByDictTypeCode(String dictTypeCode);
    
}

 

 

5.2.3. Mapper.xml

編寫BaseDictMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itcast.crm.mapper.BaseDictMapper">

    <!-- 根據類別代碼查詢數據 -->
    <select id="queryBaseDictByDictTypeCode" parameterType="String"
        resultType="cn.itcast.crm.pojo.BaseDict">
        SELECT * FROM base_dict WHERE dict_type_code =
        #{dict_type_code}
    </select>

</mapper>

 

5.3. 實現Service開發

5.3.1. BaseDictService 接口

public interface BaseDictService {

    /**
     * 根據類別代碼查詢
     * 
     * @param dictTypeCode
     * @return
     */
    List<BaseDict> queryBaseDictByDictTypeCode(String dictTypeCode);
}

 

 

5.3.2. BaseDictServiceImpl 實現類

@Service
public class BaseDictServiceImpl implements BaseDictService {

    @Autowired
    private BaseDictMapper baseDictMapper;

    @Override
    public List<BaseDict> queryBaseDictByDictTypeCode(String dictTypeCode) {

        List<BaseDict> list = this.baseDictMapper.queryBaseDictByDictTypeCode(dictTypeCode);
        return list;
    }
}

 

 

5.4. 實現Controller開發

5.4.1. 修改之前編寫的controller

@Controller
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    private BaseDictService baseDictService;

    /**
     * 顯示客戶列表
     * 
     * @return
     */
    @RequestMapping("list")
    public String queryCustomerList(Model model) {
        // 客戶來源
        List<BaseDict> fromType = this.baseDictService.queryBaseDictByDictTypeCode("002");
        // 所屬行業
        List<BaseDict> industryType = this.baseDictService.queryBaseDictByDictTypeCode("001");
        // 客戶級別
        List<BaseDict> levelType = this.baseDictService.queryBaseDictByDictTypeCode("006");

        // 把前端頁面需要顯示的數據放到模型中
        model.addAttribute("fromType", fromType);
        model.addAttribute("industryType", industryType);
        model.addAttribute("levelType", levelType);

        return "customer";
    }
}

 

 

5.4.2. 效果

實現效果如下圖:

 

 

5.4.3. 硬編碼問題

這里是根據dict_type_code類別代碼查詢數據,這里的查詢條件是寫死的,有硬編碼問題。可以把類別代碼提取到配置文件中,再使用@value注解進行加載。

5.4.3.1. 添加env.properties

添加env.properties配置文件

#客戶來源
CUSTOMER_FROM_TYPE=002
#客戶行業
CUSTOMER_INDUSTRY_TYPE=001
#客戶級別
CUSTOMER_LEVEL_TYPE=006

 

 

5.4.3.2. 修改springmvc.xml配置文件

springmvc.xml中加載env.properties

    <!-- 加載controller需要的配置信息 -->
    <context:property-placeholder location="classpath:env.properties" />

 

注意:Controller需要的配置文件信息必須添加到springmvc的配置文件中

 

5.4.3.3. 修改Controller方法

@Controller
@RequestMapping("customer")
public class CustomerController {

    // 客戶來源
    @Value("${CUSTOMER_FROM_TYPE}")
    private String CUSTOMER_FROM_TYPE;
    // 客戶行業
    @Value("${CUSTOMER_INDUSTRY_TYPE}")
    private String CUSTOMER_INDUSTRY_TYPE;
    // 客戶級別
    @Value("${CUSTOMER_LEVEL_TYPE}")
    private String CUSTOMER_LEVEL_TYPE;

    @Autowired
    private BaseDictService baseDictService;

    /**
     * 顯示客戶列表
     * 
     * @return
     */
    @RequestMapping("list")
    public String queryCustomerList(Model model) {
        // 客戶來源
        List<BaseDict> fromType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_FROM_TYPE);
        // 所屬行業
        List<BaseDict> industryType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_INDUSTRY_TYPE);
        // 客戶級別
        List<BaseDict> levelType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_LEVEL_TYPE);

        // 把前端頁面需要顯示的數據放到模型中
        model.addAttribute("fromType", fromType);
        model.addAttribute("industryType", industryType);
        model.addAttribute("levelType", levelType);

        return "customer";
    }

}

 

6. 客戶列表展示

6.1. 需求

展示客戶列表,並且可以根據查詢條件過濾查詢結果,並且實現分頁。

效果如下圖:

 

 

 

頁面代碼:

<div class="panel-heading">客戶信息列表</div>
<!-- /.panel-heading -->
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>客戶名稱</th>
            <th>客戶來源</th>
            <th>客戶所屬行業</th>
            <th>客戶級別</th>
            <th>固定電話</th>
            <th>手機</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${page.rows}" var="row">
            <tr>
                <td>${row.cust_id}</td>
                <td>${row.cust_name}</td>
                <td>${row.cust_source}</td>
                <td>${row.cust_industry}</td>
                <td>${row.cust_level}</td>
                <td>${row.cust_phone}</td>
                <td>${row.cust_mobile}</td>
                <td>
                    <a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#customerEditDialog" onclick="editCustomer(${row.cust_id})">修改</a>
                    <a href="#" class="btn btn-danger btn-xs" onclick="deleteCustomer(${row.cust_id})">刪除</a>
                </td>
            </tr>
        </c:forEach>
    </tbody>
</table>

 

 

分析我們需要根據四個條件進行查詢,返回數據是分頁對象Page

 

Sql語句:

SELECT
    a.cust_id,
    a.cust_name,
    a.cust_user_id,
    a.cust_create_id,
    b.dict_item_name cust_source,
    c.dict_item_name cust_industry,
    d.dict_item_name cust_level,
    a.cust_linkman,
    a.cust_phone,
    a.cust_mobile,
    a.cust_zipcode,
    a.cust_address,
    a.cust_createtime
FROM
    customer a
LEFT JOIN base_dict b ON a.cust_source = b.dict_id
LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
LEFT JOIN base_dict d ON a.cust_level = d.dict_id
WHERE
    a.cust_name LIKE '%馬%'
AND a.cust_source = '6'
AND a.cust_industry = '2'
AND a.cust_level = '22'
LIMIT 0, 10

 

6.2. 創建pojo開發

public class Customer {

    private Long cust_id;
    private String cust_name;
    private Long cust_user_id;
    private Long cust_create_id;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_linkman;
    private String cust_phone;
    private String cust_mobile;
    private String cust_zipcode;
    private String cust_address;
    private Date cust_createtime;
get/set。。。。。。
}

 

 

6.3. 實現DAO

分析:

  1. 前台發起請求,需要接收請求過來的查詢條件數據,可以使用pojo接收數據。需要依此編寫查詢邏輯。
  2. 前台需要分頁顯示,根據准備好的分頁實現,應該返回分頁類Page,而創建Page分頁類需要數據總條數,所以也需要查詢數據總條數的邏輯。

 

根據分析,DAO需要編寫兩個方法:

  1. 需要根據條件分頁查詢客戶信息
  2. 需要根據條件查詢數據總條數

 

6.3.1. 創建QueryVo

需要編寫QueryVo,里面包含查詢條件屬性和分頁數據。

創建接受請求參數的QueryVo

public class QueryVo {

    private String custName;
    private String custSource;
    private String custIndustry;
    private String custLevel;

    // 當前頁碼數
    private Integer page = 1;
    // 數據庫從哪一條數據開始查
    private Integer start;
    // 每頁顯示數據條數
    private Integer rows = 10;
get/set。。。。。。
}

 

6.3.2. Mapper

創建CustomerMapper 接口

public interface CustomerMapper {

    /**
     * 根據queryVo分頁查詢數據
     * 
     * @param queryVo
     * @return
     */
    List<Customer> queryCustomerByQueryVo(QueryVo queryVo);

    /**
     * 根據queryVo查詢數據條數
     * 
     * @param queryVo
     * @return
     */
    int queryCountByQueryVo(QueryVo queryVo);

}

 

 

6.3.3. Mapper.xml

創建CustomerMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itcast.crm.mapper.CustomerMapper">
    <sql id="customerQueryVo">
        <where>
            <if test="custName != null and custName != ''">
                AND a.cust_name LIKE '%${custName}%'
            </if>
            <if test="custSource != null and custSource != ''">
                AND a.cust_source = #{custSource}
            </if>
            <if test="custIndustry != null and custIndustry != ''">
                AND a.cust_industry = #{custIndustry}
            </if>
            <if test="custLevel != null and custLevel != ''">
                AND a.cust_level = #{custLevel}
            </if>
        </where>
    </sql>

    <!-- 根據queryVo分頁查詢數據 -->
    <select id="queryCustomerByQueryVo" parameterType="cn.itcast.crm.pojo.QueryVo"
        resultType="cn.itcast.crm.pojo.Customer">
      SELECT
        a.cust_id,
        a.cust_name,
        a.cust_user_id,
        a.cust_create_id,
        b.dict_item_name cust_source,
        c.dict_item_name cust_industry,
        d.dict_item_name cust_level,
        a.cust_linkman,
        a.cust_phone,
        a.cust_mobile,
        a.cust_zipcode,
        a.cust_address,
        a.cust_createtime
      FROM
        customer a
        LEFT JOIN base_dict b ON a.cust_source = b.dict_id
        LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
        LEFT JOIN base_dict d ON a.cust_level = d.dict_id
        <include refid="customerQueryVo" />
        <if test="start != null">
            LIMIT #{start}, #{rows}
        </if>
    </select>

    <!-- 根據queryVo查詢數據條數 -->
    <select id="queryCountByQueryVo" parameterType="cn.itcast.crm.pojo.QueryVo"
        resultType="int">
        SELECT count(1) FROM customer a
        <include refid="customerQueryVo" />
    </select>
</mapper>

 

6.4. 實現service

6.4.1. 接口

編寫接口CustomerService

public interface CustomerService {
    /**
     * 根據條件分頁查詢客戶
     * 
     * @param queryVo
     * @return
     */
    Page<Customer> queryCustomerByQueryVo(QueryVo queryVo);
}

 

6.4.2. 實現類

編寫接口實現類CustomerServiceImpl

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public Page<Customer> queryCustomerByQueryVo(QueryVo queryVo) {
        // 設置查詢條件,從哪一條數據開始查
        queryVo.setStart((queryVo.getPage() - 1) * queryVo.getRows());

        // 查詢數據結果集
        List<Customer> list = this.customerMapper.queryCustomerByQueryVo(queryVo);
        // 查詢到的數據總條數
        int total = this.customerMapper.queryCountByQueryVo(queryVo);

        // 封裝返回的page對象
        Page<Customer> page = new Page<>(total, queryVo.getPage(), queryVo.getRows(), list);

        return page;
    }
}

 

 

6.5. 實現Controller

改造Controller的方法

@RequestMapping("list")
public String queryCustomerList(QueryVo queryVo, Model model) {

    try {
        // 解決get請求亂碼問題
        if (StringUtils.isNotBlank(queryVo.getCustName())) {
            queryVo.setCustName(new String(queryVo.getCustName().getBytes("ISO-8859-1"), "UTF-8"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 客戶來源
    List<BaseDict> fromType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_FROM_TYPE);
    // 所屬行業
    List<BaseDict> industryType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_INDUSTRY_TYPE);
    // 客戶級別
    List<BaseDict> levelType = this.baseDictService.queryBaseDictByDictTypeCode(this.CUSTOMER_LEVEL_TYPE);

    // 把前端頁面需要顯示的數據放到模型中
    model.addAttribute("fromType", fromType);
    model.addAttribute("industryType", industryType);
    model.addAttribute("levelType", levelType);

    // 分頁查詢數據
    Page<Customer> page = this.customerService.queryCustomerByQueryVo(queryVo);
    // 把分頁查詢的結果放到模型中
    model.addAttribute("page", page);

    // 數據回顯
    model.addAttribute("custName", queryVo.getCustName());
    model.addAttribute("custSource", queryVo.getCustSource());
    model.addAttribute("custIndustry", queryVo.getCustIndustry());
    model.addAttribute("custLevel", queryVo.getCustLevel());

    return "customer";
}

 

 

7. 修改客戶信息

7.1. 需求

頁面效果如下圖:

 

 

1、客戶列表中點擊“修改”按鈕彈出客戶信息修改窗,並初始化客戶信息

2、點擊“保存修改”按鈕將修改后的結果保存到數據庫中

 

 

 

 

7.2. 實現編輯數據回顯

在客戶列表顯示中,可以點擊修改按鈕,彈出修改界面,打開瀏覽器的開發者工具,發現當點擊修改按鈕,會發起一個請求

如下圖方式進行查看

 

 

 

分析這里應該是發起請求到后台,獲取該用戶的詳細信息,在頁面上可以回顯

 

復制請求路徑中的edit.action,在customer.jsp頁面中搜索,找到請求邏輯

找到的代碼如下圖:

 

 

發現這里是一個Ajax請求,根據這個請求我們可以開發后台邏輯,提供給前端頁面進行調用

 

7.3. 回顯功能實現

7.3.1. Mapper接口

CustomerMapper添加方法

/**
 * 根據id查詢客戶
 * 
 * @param id
 * @return
 */
Customer queryCustomerById(Long id);

 

 

7.3.2. Mapper.xml

CustomerMapper.xml編寫sql

<!-- 根據id查詢用戶 -->
<select id="queryCustomerById" resultType="cn.itcast.crm.pojo.Customer">
    SELECT * FROM customer WHERE cust_id = #{id}
</select>

 

 

7.3.3. Service接口

編寫CustomerService.接口方法

/**
 * 根據id查詢數據
 * 
 * @param id
 * @return
 */
Customer queryCustomerById(Long id);

 

 

7.3.4. Service接口實現類

CustomerServiceImpl實現接口方法

@Override
public Customer queryCustomerById(Long id) {
    Customer customer = this.customerMapper.queryCustomerById(id);
    return customer;
}

 

7.3.5. Controller

CustomerController編寫方法

/**
 * 根據id查詢用戶,返回json格式數據
 * 
 * @param id
 * @return
 */
@RequestMapping("edit")
@ResponseBody
public Customer queryCustomerById(Long id) {
    Customer customer = this.customerService.queryCustomerById(id);
    return customer;
}

 

 

7.4. 實現編輯客戶數據

在編輯框,點擊保存修改按鈕,應該進行數據保存,如下圖所示:

 

 

 

發起請求如下圖:

 

 

 

在頁面找到的請求邏輯是:

function updateCustomer() {
    $.post("<%=basePath%>customer/update.action",$("#edit_customer_form").serialize(),function(data){
        alert("客戶信息更新成功!");
        window.location.reload();
    });
}

 

 

7.5. 編輯功能實現

7.5.1. Mapper接口

CustomerMapper添加方法

/**
 * 根據id編輯客戶
 * 
 * @param customer
 */
void updateCustomerById(Customer customer);

 

 

7.5.2. Mapper.xml

CustomerMapper.xml編寫sql

<select id="updateCustomerById" parameterType="cn.itcast.crm.pojo.Customer">
    UPDATE `customer`
    SET
    <if test="cust_name !=null and cust_name != ''">
        `cust_name` = #{cust_name},
    </if>
    <if test="cust_user_id !=null">
        `cust_user_id` = #{cust_user_id},
    </if>
    <if test="cust_create_id !=null">
        `cust_create_id` = #{cust_create_id},
    </if>
    <if test="cust_source !=null and cust_source != ''">
        `cust_source` = #{cust_source},
    </if>
    <if test="cust_industry !=null and cust_industry != ''">
        `cust_industry` = #{cust_industry},
    </if>
    <if test="cust_level !=null and cust_level != ''">
        `cust_level` = #{cust_level},
    </if>
    <if test="cust_linkman !=null and cust_linkman != ''">
        `cust_linkman` = #{cust_linkman},
    </if>
    <if test="cust_phone !=null and cust_phone != ''">
        `cust_phone` = #{cust_phone},
    </if>
    <if test="cust_mobile !=null and cust_mobile != ''">
        `cust_mobile` = #{cust_mobile},
    </if>
    <if test="cust_zipcode !=null and cust_zipcode != ''">
        `cust_zipcode` = #{cust_zipcode},
    </if>
    <if test="cust_address !=null and cust_address != ''">
        `cust_address` = #{cust_address},
    </if>
    `cust_createtime` = NOW()
    WHERE
    (`cust_id` = #{cust_id});
</select>

 

 

7.5.3. Service接口

編寫CustomerService.接口方法

/**
 * 根據id編輯客戶數據
 * 
 * @param customer
 */
void updateCustomerById(Customer customer);

 

 

7.5.4. Service接口實現類

CustomerServiceImpl實現接口方法

@Override
public void updateCustomerById(Customer customer) {
    this.customerMapper.updateCustomerById(customer);
}

 

 

7.5.5. Controller

CustomerController編寫方法

需要正確的響應,要告訴前端更新成功。返回值有沒有都可以。

這里需要加@ResponseBody注解,使其不走視圖解析器。

/**
 * 根據id查詢用戶,返回更新后客戶的json格式數據
 * 
 * @param id
 * @return
 */
@RequestMapping("update")
@ResponseBody
public String updateCustomerById(Customer customer) {
    Customer result = this.customerService.updateCustomerById(customer);
    return "OK";
}

 

 

8. 刪除客戶

8.1. 需求分析

點擊客戶列表中的刪除按鈕,提示“警告信息”,如下圖

 

 

 

如下圖,點擊確定后刪除用戶信息,並刷新頁面。

 

 

 

 

發起的請求如下圖:

 

 

 

搜索前端jsp頁面邏輯找到如下代碼:

function deleteCustomer(id) {
    if(confirm('確實要刪除該客戶嗎?')) {
        $.post("<%=basePath%>customer/delete.action",{"id":id},function(data){
            alert("客戶刪除更新成功!");
            window.location.reload();
        });
    }
}

 

8.2. 功能開發

8.2.1. Mapper接口

CustomerMapper添加方法

/**
 * 根據id刪除用戶
 * 
 * @param id
 */
void deleteCustomerById(Long id);

 

 

8.2.2. Mapper.xml

CustomerMapper.xml編寫sql

<!-- 根據id刪除客戶 -->
<delete id="deleteCustomerById" parameterType="long">
    DELETE FROM
    customer WHERE cust_id = #{id}
</delete>

 

8.2.3. Service接口

CustomerService編寫接口方法

/**
 * 根據id刪除客戶
 * 
 * @param id
 */
void deleteCustomerById(Long id);

 

 

8.2.4. Service實現類

CustomerServiceImpl實現接口方法

@Override
public void deleteCustomerById(Long id) {
    this.customerMapper.deleteCustomerById(id);
}

 

 

8.2.5. Controller

CustomerController編寫方法

/**
 * 刪除用戶
 * 
 * @param id
 * @return
 */
@RequestMapping("delete")
@ResponseBody
public String deleteCustomerById(Long id) {
    this.customerService.deleteCustomerById(id);
    return "ok";
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM