伙伴云客服论坛»论坛 S区 S客户管理 查看内容

0 评论

0 收藏

分享

BOOT客户管理系统(详解)

BOOT客户管理系统(详解)

Github:https://github.com/wz20

Gitee:https://gitee.com/Wang-ZeLXM/boot-CRM

本文中的代码不可以直接粘贴,因为有一些没有写在注释中的文字分析!请前往github,或网站资源
演示图:

BOOT客户管理系统(详解)-1.jpg


本系统SSM整合思路:

BOOT客户管理系统(详解)-2.jpg


springMVC系统流程图:

BOOT客户管理系统(详解)-3.jpg


一. 环境搭建

1.pom.xml添加依赖
  1. <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- spring--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.12.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.2.12.RELEASE</version></dependency><!--springmvc所用依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.12.RELEASE</version></dependency><!--Servlet - JSP--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!--  mybatis所用依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency><!--   数据库所用依赖--><!--数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.24</version></dependency><!--数据库连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.1</version></dependency><!--jdbc--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.12.RELEASE</version></dependency><!--日志 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.14</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.25</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.25</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.logback-extensions</groupId><artifactId>logback-ext-spring</artifactId><version>0.1.4</version></dependency><!-- 工具包 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.11</version></dependency><!--jackson--><!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.2</version></dependency><!-- 文件上传下载 --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.2</version></dependency><!--事务--><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.12.RELEASE</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency>
复制代码
2. 创建目录构造

BOOT客户管理系统(详解)-4.jpg


3. 配置文件的编写

spring配置文件—applicationContext的编写
  1. <?xml version="1.0" encoding="UTF-8"?><beansxmlns="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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--扫描包除了带有controller注解的--><context:component-scanbase-package="com.wangze"use-default-filters="true"><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 整合mybatis--><context:property-placeholderlocation="classpath:db.properties"/><!--连接池--><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="driverClassName"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/><!--最大连接数10,最小空闲数5--><propertyname="maxActive"value="10"/><propertyname="minIdle"value="5"/></bean><!--配置sqlSessionFactoryBean--><beanid="sqlSessionFactoryBean"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><propertyname="typeAliasesPackage"value="com.wangze.core.entity"/>有了这个别名,在mapper中就可以不用写全类名
  2.         <propertyname="mapperLocations"><list><value>classpath:com.wangze.mapper/*Mapper.xml</value>扫描mapper下所有以Mapper结尾的文件
  3.             </list></property></bean><!--创建DAO对象 MapperScannerConfigure--><beanid="scanner"class="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactoryBean"/><propertyname="basePackage"value="com.wangze.core.dao">  指定mapper对应的dao接口包
  4.         </property></bean><!--  整合mybatis完毕--><!--注解开发 事务  事务的开发就是把AOP开发中的额外方法换成事务--><beanid="dataSourceTransactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"/></bean><tx:annotation-driventransaction-manager="dataSourceTransactionManager"/><!--只需要在原始对象上加注解:@Tronsaction    增删改操作 @Transactional 查询操作  @Transactional(propagation=Propagation.SUPPORTS,readOnly=true)--></beans>
复制代码
mvc配置文件
  1. <?xml version="1.0" encoding="UTF-8"?><beansxmlns="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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"><!--配置包扫描--><context:component-scanbase-package="com.wangze"use-default-filters="false"><context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan><!--加载属性文件--><context:property-placeholderlocation="classpath:resource.properties"/><!--处置器映射器 适配器--><mvc:annotation-driven/><!--配置静态资源访问映射,此配置中的文件将不会呗前端控制器拦截 --><mvc:resourceslocation="/js/"mapping="/js/**"/><mvc:resourceslocation="/css/"mapping="/css/**"/><mvc:resourceslocation="/fonts/"mapping="/fonts/**"/><mvc:resourceslocation="/images/"mapping="/images/**"/><!-- 配置视图解释器ViewResolver --><beanid="jspViewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/WEB-INF/jsp/"/><propertyname="suffix"value=".jsp"/></bean></beans>
复制代码
db.properties(数据库连接池)
  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/boot_crm
  3. jdbc.username=root
  4. jdbc.password=123456
  5. jdbc.initialSize=5
复制代码
resource.properties(用于查询数据字典中的数据)
  1. customer.from.type=002
  2. customer.industry.type=001
  3. customer.level.type=006
复制代码
log4j.properties(log4j配置文件)
  1. # resources文件夹根目录下
  2. log4j.rootLogger=debug,console
  3. log4j.appender.console=org.apache.log4j.ConsoleAppender
  4. log4j.appender.console.Target=System.out
  5. log4j.appender.console.layout=org.apache.log4j.PatternLayout
  6. log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
复制代码
logback.xml(logback配置文件)

当取消spring文件用spring3.0+提供的@Bean所取代时,log4j不能用了,我们使用logback日志
  1. <?xml version="1.0" encoding="UTF-8"?><configuration><!-- 控制台输出 --><appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender"><encoder><!--格式化输出:%d表示⽇期,%thread表示线程名,
  2.            %-5level:级别从左显示5个字符宽度%msg:⽇志消息,%n是换⾏符--><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}
  3.                 [%thread] %-5level %logger{50} - %msg%n</pattern></encoder></appender><rootlevel="DEBUG"><appender-refref="STDOUT"/></root></configuration>
复制代码
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?><web-appxmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><!-- spring--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!--监听器--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--springmvc--><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  //中央控制器
  2.         <init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc-config.xml</param-value></init-param><load-on-startup>1</load-on-startup>         //启动时机
  3.     </servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern>             //默认所有恳求都被springmvc处置,需要配置静态资源不被拦截;
  4.     </servlet-mapping><!--    过滤器 防止恳求和相应的数据乱码 --><filter><filter-name>encodingFilter</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><init-param><param-name>forceRequestEncoding</param-name><param-value>true</param-value></init-param><init-param><param-name>forceResponseEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--默认首页--><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
复制代码
4.导入页面资源
  1. 请访问我的github获取:https://github.com/wz20
复制代码
5.导入数据库
  1. boot_crm
复制代码
二、实现登录功能(User相关)
  1. 用户发出登录恳求后,验证登录账号和密码,假设正确,跳转视图层;假设错误,给出提示;
复制代码
1.编写user实体类

在entity包下,由于我使用了lombok,所以@Data 自动生成set,get方法
  1. package com.wangze.core.entity;import lombok.Data;import org.springframework.stereotype.Component;import java.io.Serial;import java.io.Serializable;/**
  2. * @author: 王泽20
  3. * 一个对象序列化的接口,一个类只要实现了Serializable接口,它的对象才干被序列化。
  4. *    从说明中我们可以看到,假设我们没有自己声明一个serialVersionUID变量,接口会默认生成一个serialVersionUID
  5. *    但是强烈建议用户自定义一个serialVersionUID,因为默认的serialVersionUID对于class的细节非常敏感,反序列化时可能会导致InvalidClassException这个异常。
  6. *    在前面我们已经新建了一个实体类User实现Serializable接口,并且定义了serialVersionUID变量。
  7. */@Component@DatapublicclassUserimplementsSerializable{@Serialprivatestaticfinallong serialVersionUID =1L;private Integer user_Id;//用户idprivate String user_code;//用户账号private String user_name;//用户名称private String user_password;//用户密码private Integer user_state;//用户状态}
复制代码
2.编写UserDao接口
  1. package com.wangze.core.dao;import com.wangze.core.entity.User;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;/**
  2. * @author: 王泽20
  3. * 通过账号密码查询用户
  4. */@Repository//这个注解相当于<bean>标签,是@Component的衍生注解,用于dao层publicinterfaceUserDao{public User findUser(@Param("usercode") String usercode,@Param("password") String password);//当你使用了使用@Param注解来声明参数时,假设使用 #{} 或 ${} 的方式都可以。//在旧版本中假设想在mapper.xml 中引用变量使用${} 必需用@param为变量起别名;新版只要是只要一个参数都可以不用起别名//# 和 $ 到底有什么区别???   #采用占位符的方式   $采用参数拼接的方式    参数拼接有SQL注入的风险}
复制代码
对应mapper.xml
  1. <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
  2.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.wangze.core.dao.UserDao"><!--查询用户--><selectid="findUser"parameterType="String"resultType="com.wangze.core.entity.User">
  4.         select * from sys_user
  5.         where user_code = #{usercode}
  6.         and user_password = #{password}
  7.         and user_state = '1'
  8.     </select></mapper>
复制代码
3.编写UserService接口
  1. package com.wangze.core.service;import com.wangze.core.entity.User;publicinterfaceUserService{public User findUser(String usercode,String password);}
复制代码
4.编写UserServiceImpl
  1. package com.wangze.core.service;import com.wangze.core.dao.UserDao;import com.wangze.core.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/**
  2. * @author: 王泽20
  3. */@Service//这个注解相当于<bean>标签,是@Component的衍生注解,用于service层@TransactionalpublicclassUserServiceImplimplementsUserService{@Autowired//注入成员变量userDaoprivate UserDao userDao;@Override//在数据库中找这个userpublic User findUser(String usercode, String password){
  4.         User user =this.userDao.findUser(usercode,password);return user;}}
复制代码
5.编写UserController类
  1. package com.wangze.core.controller;import com.wangze.core.entity.User;import com.wangze.core.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import javax.servlet.http.HttpSession;/**
  2. * @author: 王泽20
  3. */@Controller//这个注解相当于<bean>标签,是@Component的衍生注解,用于Controller层publicclassUserController{@Autowired//依赖注入private UserService userService;@RequestMapping(value ="/login",method = RequestMethod.POST)//必需是post方法 public String login(String usercode, String password, Model model, HttpSession session){
  4.         User user = userService.findUser(usercode,password);if(user != null){
  5.                 session.setAttribute("USER_SESSION",user);return"customer";}
  6.         model.addAttribute("msg","账号或密码错误,请重新输入");return"login";}}
复制代码
6.测试

登录验证(拦截器)

1.创建LoginInterceptor类
  1. package com.wangze.core.interceptor;import com.wangze.core.entity.User;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;/**
  2. * @author: 王泽20    springmvc中的拦截器,只要返回值为true,后面的方法才会继续执行
  3. */@ComponentpublicclassLoginInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws ServletException, IOException {//获取恳求的url
  4.         String url =request.getRequestURI();//拦截不是登录的恳求if(url.contains("/login")){returntrue;}//获取session
  5.         HttpSession session =request.getSession();
  6.         User user=(User) session.getAttribute("USER_SESSION");//判断session中是否有用户数据,假设有,则返回true,继续向下执行if(user != null){returntrue;}//不符合条件的给出提示信息,并转发到登录界面
  7.         request.setAttribute("msg","您还没有登录,请先登录");
  8.         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);//抛出异常returnfalse;}@OverridepublicvoidpostHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {}@OverridepublicvoidafterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {}}
复制代码
2.在springmvc配置文件中配置拦截器
  1. <!--   拦截器--><mvc:interceptors><mvc:interceptor><mvc:mappingpath="/**"/><refbean="loginInterceptor"/></mvc:interceptor></mvc:interceptors>
复制代码
3.验证
  1. @RequestMapping("/tocon")public String tocon(){return"customer";}
  2. 阅读器输入...../tocon   
复制代码
退出登录

在userController中
  1. /* 退出登录 */@RequestMapping("logout")public String logout(HttpSession session){
  2.         session.invalidate();//肃清sessionreturn"redirect:login";}//向用户登录界面跳转@RequestMapping(value ="login",method = RequestMethod.GET)public String toLogin(){return"login";}
复制代码
三、客户管理模块
  1. 对客户表,停止增删改查  (重点:分页查询  详细两个工具类此处不做介绍,在github中可以获取源码)
复制代码
一、查询操作

1.实体类


  • Customer
    1. package com.wangze.core.entity;import lombok.Data;import org.springframework.stereotype.Component;import java.io.Serial;import java.io.Serializable;import java.util.Date;/**
    2. * @author: 王泽20
    3. */@Data@ComponentpublicclassCustomerimplementsSerializable{@Serialprivatestaticfinallong serialVersionUID =1L;private Integer cust_id;//客户编号private String cust_name;//客户名称private Integer cust_user_id;//负责人idprivate Integer cust_create_id;//创建人idprivate 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;//创建时间private Integer start;//起始行private Integer rows;//所取行数}
    复制代码
  • 数据字典 BaseDict
    1. package com.wangze.core.entity;import lombok.Data;import org.springframework.stereotype.Component;import java.io.Serial;import java.io.Serializable;/**
    2. * @author: 王泽20
    3. */@Data@ComponentpublicclassBaseDictimplementsSerializable{@Serialprivatestaticfinallong serialVersionUID =1L;private String dict_id;//数据字典idprivate 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;//备注}
    复制代码
2.Dao

    CustomerDao
    1. package com.wangze.core.dao;import com.wangze.core.entity.Customer;import org.springframework.stereotype.Repository;import java.util.List;@RepositorypublicinterfaceCustomerDao{//客户列表public List<Customer>selectCustomerList(Customer customer);//客户数public Integer selectCustomerListCount(Customer customer);}
    复制代码
    BaseDictDao
    1. package com.wangze.core.dao;import com.wangze.core.entity.BaseDict;import java.util.List;publicinterfaceBaseDictDao{public List<BaseDict>selectBaseDictByTypeCode(String typecode);}
    复制代码
3.Mapper


  • CustomerMapper
    1. <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
    2.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.wangze.core.dao.CustomerDao"><sqlid="selectCustomerListWhere"><where><iftest="cust_name != null">
    4.                                 cust_name like "%"#{cust_name}"%"
    5.                         </if><iftest="cust_source != null">
    6.                                 and cust_source = #{cust_source}
    7.                         </if><iftest="cust_industry != null">
    8.                                 and cust_industry = #{cust_industry}
    9.                         </if><iftest="cust_level != null">
    10.                                 and cust_level = #{cust_level}
    11.                         </if></where></sql><!--        查询客户列表--><selectid="selectCustomerList"parameterType="com.wangze.core.entity.Customer"resultType="com.wangze.core.entity.Customer">
    12.                 SELECT
    13.                 cust_id,
    14.                 cust_name,
    15.                 cust_user_id,
    16.                 cust_create_id,
    17.                 b.dict_item_name,cust_source,
    18.                 c.dict_item_name,cust_industry,
    19.                 d.dict_item_name,cust_level,
    20.                 cust_linkman,
    21.                 cust_phone,
    22.                 cust_mobile,
    23.                 cust_createtime
    24.                 FROM
    25.                 customer a
    26.                 LEFT JOIN (
    27.                 SELECT
    28.                 dict_id,
    29.                 dict_item_name
    30.                 FROM
    31.                 base_dict
    32.                 WHERE
    33.                 dict_type_code = '002'
    34.                 ) b ON a.cust_source = b.dict_id
    35.                 LEFT JOIN (
    36.                 SELECT
    37.                 dict_id,
    38.                 dict_item_name
    39.                 FROM
    40.                 base_dict
    41.                 WHERE
    42.                 dict_type_code = '001'
    43.                 ) c ON a.cust_industry = c.dict_id
    44.                 LEFT JOIN (
    45.                 SELECT
    46.                 dict_id,
    47.                 dict_item_name
    48.                 FROM
    49.                 base_dict
    50.                 WHERE
    51.                 dict_type_code = '006'
    52.                 ) d ON a.cust_level = d.dict_id
    53.                 <includerefid="selectCustomerListWhere"/><!-- 执行分页查询 --><iftest="start !=null and rows != null">
    54.                         limit #{start},#{rows}
    55.                 </if></select><!-- 查询客户总数 --><selectid="selectCustomerListCount"parameterType="com.wangze.core.entity.Customer"resultType="Integer">
    56.                 select count(*) from customer
    57.                 <includerefid="selectCustomerListWhere"/></select></mapper>
    复制代码
  • BaseDictMapper.xml
    1. <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
    2.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.wangze.core.dao.BaseDictDao"><selectid="selectBaseDictByTypeCode"parameterType="String"resultType="com.wangze.core.entity.BaseDict">
    4.                 select * from base_dict where dict_type_code=#{typecode}
    5.         </select></mapper>
    复制代码
4.service

    CustomerService
    1. package com.wangze.core.service;import com.wangze.common.utils.Page;import com.wangze.core.entity.Customer;import org.springframework.stereotype.Service;@ServicepublicinterfaceCustomerService{// 查询客户列表public Page<Customer>findCustomerList(Integer page,Integer rows,String custName,String custSource,String custIndustry,String custLevel);}
    复制代码
    BaseDictService
    1. package com.wangze.core.service;import com.wangze.core.entity.BaseDict;import org.springframework.stereotype.Service;import java.util.List;@ServicepublicinterfaceBaseDictService{//根据类别代码查询数据字典public List<BaseDict>findBaseDictByTypeCode(String typecode);}
    复制代码
5.serviceimpl


  • Custormer
    1. package com.wangze.core.service;import com.wangze.common.utils.Page;import com.wangze.core.dao.CustomerDao;import com.wangze.core.entity.Customer;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.List;/**
    2. * @author: 王泽20
    3. * 客户管理
    4. */@Service("customerService")@TransactionalpublicclassCustomerServiceImplimplementsCustomerService{@Autowiredprivate CustomerDao customerDao;@Overridepublic Page<Customer>findCustomerList(Integer page, Integer rows, String custName, String custSource, String custIndustry, String custLevel){//创建客户对象
    5.         Customer customer =newCustomer();// 判断客户名称if(StringUtils.isNotBlank(custName)){
    6.             customer.setCust_name(custName);}// 判断客户信息来源if(StringUtils.isNotBlank(custSource)){
    7.             customer.setCust_source(custSource);}// 判断客户所属行业if(StringUtils.isNotBlank(custIndustry)){
    8.             customer.setCust_industry(custIndustry);}// 判断客户级别if(StringUtils.isNotBlank(custLevel)){
    9.             customer.setCust_level(custLevel);}// 当前页
    10.         customer.setStart((page-1)* rows);// 每页数
    11.         customer.setRows(rows);// 查询客户列表
    12.         List<Customer> customers =
    13.                 customerDao.selectCustomerList(customer);// 查询客户列表总记录数
    14.         Integer count = customerDao.selectCustomerListCount(customer);// 创建Page返回对象
    15.         Page<Customer> result =newPage<>();
    16.         result.setPage(page);
    17.         result.setRows(customers);
    18.         result.setSize(rows);
    19.         result.setTotal(count);return result;}}
    复制代码
  • BaseDict
    1. package com.wangze.core.service;import com.wangze.core.dao.BaseDictDao;import com.wangze.core.entity.BaseDict;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/**
    2. * @author: 王泽20
    3. */@Service("baseDictService")publicclassBaseDictServiceImplimplementsBaseDictService{@Autowiredprivate BaseDictDao baseDictDao;@Overridepublic List<BaseDict>findBaseDictByTypeCode(String typecpde){return baseDictDao.selectBaseDictByTypeCode(typecpde);}}
    复制代码
6.Controller
  1. package com.wangze.core.controller;import com.wangze.common.utils.Page;import com.wangze.core.entity.BaseDict;import com.wangze.core.entity.Customer;import com.wangze.core.service.BaseDictService;import com.wangze.core.service.CustomerService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.PropertySource;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import java.util.List;/**
  2. * @author: 王泽20
  3. */@ControllerpublicclassCustomerController{@Autowiredprivate CustomerService customerService;@Autowiredprivate BaseDictService baseDictService;@Value("${customer.from.type}")private String FROM_TYPE;// 客户所属行业@Value("${customer.industry.type}")private String INDUSTRY_TYPE;// 客户级别@Value("${customer.level.type}")private String LEVEL_TYPE;/**
  4.      *  客户列表
  5.      */@RequestMapping(value ="/customer/list")public String list(@RequestParam(defaultValue="1")Integer page,@RequestParam(defaultValue="10")Integer rows,
  6.                        String custName, String custSource, String custIndustry,
  7.                        String custLevel, Model model){// 条件查询所有客户
  8.         Page<Customer> customers = customerService.findCustomerList(page, rows, custName,
  9.                         custSource, custIndustry, custLevel);
  10.         model.addAttribute("page", customers);// 客户来源
  11.         List<BaseDict> fromType = baseDictService.findBaseDictByTypeCode(FROM_TYPE);// 客户所属行业
  12.         List<BaseDict> industryType = baseDictService.findBaseDictByTypeCode(INDUSTRY_TYPE);// 客户级别
  13.         List<BaseDict> levelType = baseDictService.findBaseDictByTypeCode(LEVEL_TYPE);// 添加参数
  14.         model.addAttribute("fromType", fromType);
  15.         model.addAttribute("industryType", industryType);
  16.         model.addAttribute("levelType", levelType);
  17.         model.addAttribute("custName", custName);
  18.         model.addAttribute("custSource", custSource);
  19.         model.addAttribute("custIndustry", custIndustry);
  20.         model.addAttribute("custLevel", custLevel);return"customer";}}
复制代码
二、添加客户(增)

分析:增添用户实则在客户表中增加数据,前面已经创建了客户的实体类,所以只用编写controller层和service以及Dao中的方法。
此过程是添加,所以需要注意事务的提交。前面有配置…可以查看spring配置文件
1.Dao层
  1. // 创建客户publicintcreateCustomer(Customer customer);
复制代码
2.mapper
  1. <!-- 添加客户 --><insertid="createCustomer"parameterType="com.wangze.core.entity.Customer">
  2.                 insert into customer(
  3.                         cust_name,
  4.                         cust_user_id,
  5.                         cust_create_id,
  6.                         cust_source,
  7.                         cust_industry,
  8.                         cust_level,
  9.                         cust_linkman,
  10.                         cust_phone,
  11.                         cust_mobile,
  12.                         cust_zipcode,
  13.                         cust_address,
  14.                         cust_createtime
  15.                 )
  16.                 values(#{cust_name},
  17.                            #{cust_user_id},
  18.                            #{cust_create_id},
  19.                            #{cust_source},
  20.                            #{cust_industry},
  21.                            #{cust_level},
  22.                            #{cust_linkman},
  23.                            #{cust_phone},
  24.                            #{cust_mobile},
  25.                            #{cust_zipcode},
  26.                            #{cust_address},
  27.                            #{cust_createtime}
  28.                           )
  29.         </insert>
复制代码
3.Service
  1. //新建客户intcreateCustomer(Customer customer);
复制代码
4.ServiceImpl
  1. /**
  2.      * 创建客户
  3.      */@OverridepublicintcreateCustomer(Customer customer){return customerDao.createCustomer(customer);}
复制代码
5.Controller
  1. /**
  2.      * 创建客户
  3.      */@RequestMapping("/customer/create")@ResponseBodypublic String customerCreate(Customer customer, HttpSession session){// 获取Session中的当前用户信息
  4.         User user =(User) session.getAttribute("USER_SESSION");// 将当前用户id存储在客户对象中
  5.         customer.setCust_create_id(user.getUser_Id());// 创建Date对象
  6.         Date date =newDate();// 得到一个Timestamp格式的时间,存入mysql中的时间格式“yyyy/MM/dd HH:mm:ss”
  7.         Timestamp timeStamp =newTimestamp(date.getTime());
  8.         customer.setCust_createtime(timeStamp);// 执行Service层中的创建方法,返回的是受影响的行数int rows = customerService.createCustomer(customer);if(rows >0){return"OK";}else{return"FAIL";}}
复制代码
三、修改、删除 客户

由于增删改大同小异,所以这两个合起来写了。
1.Dao层
  1. // 通过id查询客户public Customer getCustomerById(Integer id);// 更新客户信息publicintupdateCustomer(Customer customer);// 删除客户int deleteCustomer (Integer id);
复制代码
2.mapper
  1. <!-- 根据id获取客户信息 --><selectid="getCustomerById"parameterType="Integer"resultType="com.wangze.core.entity.Customer">
  2.                 select * from customer where cust_id = #{id}
  3.         </select><!-- 更新客户 --><updateid="updateCustomer"parameterType="com.wangze.core.entity.Customer">
  4.                 update customer
  5.                 <set><iftest="cust_name!=null">
  6.                                 cust_name=#{cust_name},
  7.                         </if><iftest="cust_user_id!=null">
  8.                                 cust_user_id=#{cust_user_id},
  9.                         </if><iftest="cust_create_id!=null">
  10.                                 cust_create_id=#{cust_create_id},
  11.                         </if><iftest="cust_source!=null">
  12.                                 cust_source=#{cust_source},
  13.                         </if><iftest="cust_industry!=null">
  14.                                 cust_industry=#{cust_industry},
  15.                         </if><iftest="cust_level!=null">
  16.                                 cust_level=#{cust_level},
  17.                         </if><iftest="cust_linkman!=null">
  18.                                 cust_linkman=#{cust_linkman},
  19.                         </if><iftest="cust_phone!=null">
  20.                                 cust_phone=#{cust_phone},
  21.                         </if><iftest="cust_mobile!=null">
  22.                                 cust_mobile=#{cust_mobile},
  23.                         </if><iftest="cust_zipcode!=null">
  24.                                 cust_zipcode=#{cust_zipcode},
  25.                         </if><iftest="cust_address!=null">
  26.                                 cust_address=#{cust_address},
  27.                         </if><iftest="cust_createtime!=null">
  28.                                 cust_createtime=#{cust_createtime},
  29.                         </if></set>
  30.                 where cust_id=#{cust_id}
  31.         </update><!-- 删除客户 --><deleteid="deleteCustomer"parameterType="Integer">
  32.                 delete from customer where cust_id=#{id}
  33.         </delete>
复制代码
3.service
  1. // 通过id查询客户public Customer getCustomerById(Integer id);// 更新客户publicintupdateCustomer(Customer customer);// 删除客户publicintdeleteCustomer(Integer id);
复制代码
4.serviceImpl
  1. /**
  2.      * 创建客户
  3.      */@OverridepublicintcreateCustomer(Customer customer){return customerDao.createCustomer(customer);}/**
  4.      * 通过id查询客户
  5.      */@Overridepublic Customer getCustomerById(Integer id){
  6.         Customer customer = customerDao.getCustomerById(id);return customer;}/**
  7.      * 更新客户
  8.      */@OverridepublicintupdateCustomer(Customer customer){return customerDao.updateCustomer(customer);}/**
  9.      * 删除客户
  10.      */@OverridepublicintdeleteCustomer(Integer id){return customerDao.deleteCustomer(id);}
复制代码
5.controller
  1. /**
  2.      * 通过id获取客户信息
  3.      */@RequestMapping("/customer/getCustomerById")@ResponseBodypublic Customer getCustomerById(Integer id){
  4.         Customer customer = customerService.getCustomerById(id);return customer;}/**
  5.      * 更新客户
  6.      */@RequestMapping("/customer/update")@ResponseBodypublic String customerUpdate(Customer customer){int rows = customerService.updateCustomer(customer);if(rows >0){return"OK";}else{return"FAIL";}}/**
  7.      * 删除客户
  8.      */@RequestMapping("/customer/delete")@ResponseBodypublic String customerDelete(Integer id){int rows = customerService.deleteCustomer(id);if(rows >0){return"OK";}else{return"FAIL";}}
  9. Customer getCustomerById(Integer id){
  10.         Customer customer = customerDao.getCustomerById(id);return customer;}/**
  11.      * 更新客户
  12.      */@OverridepublicintupdateCustomer(Customer customer){return customerDao.updateCustomer(customer);}/**
  13.      * 删除客户
  14.      */@OverridepublicintdeleteCustomer(Integer id){return customerDao.deleteCustomer(id);}
复制代码
5.controller
  1. /**
  2.      * 通过id获取客户信息
  3.      */@RequestMapping("/customer/getCustomerById")@ResponseBodypublic Customer getCustomerById(Integer id){
  4.         Customer customer = customerService.getCustomerById(id);return customer;}/**
  5.      * 更新客户
  6.      */@RequestMapping("/customer/update")@ResponseBodypublic String customerUpdate(Customer customer){int rows = customerService.updateCustomer(customer);if(rows >0){return"OK";}else{return"FAIL";}}/**
  7.      * 删除客户
  8.      */@RequestMapping("/customer/delete")@ResponseBodypublic String customerDelete(Integer id){int rows = customerService.deleteCustomer(id);if(rows >0){return"OK";}else{return"FAIL";}}
复制代码

回复

举报 使用道具

相关帖子
全部回复
暂无回帖,快来参与回复吧
本版积分规则 高级模式
B Color Image Link Quote Code Smilies

Happy柠檬
注册会员
主题 22
回复 21
粉丝 0
|网站地图
快速回复 返回顶部 返回列表