01 整合ssm(环境搭建,登录功能,客户列表)

【摘要】

基本学会了ssm框架的概念,并且都简单实践过了,接下来就要在项目中实战了,这周主要是把之前学的mybatis那一段时间的crm项目后端重新搭建.

【环境搭建】

1.新建一个web项目,2.5版本

2.导包,建库建表

大概31个包,包括Gson.jar,spring整合mybatis,springmvc,spring等的jar包

3.配置xml文件

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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>my1112ssm</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- 配置Spring容器随项目启动 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
    <!-- spring容器配置文件的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- 配置SpringMVC前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 指定SpringMVC配置文件 -->
		<!-- SpringMVC的配置文件的默认路径是/WEB-INF/${servlet-name}-servlet.xml -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- 1. /* 拦截所有 jsp js png .css 真的全拦截 建议不使用 2. *.action *.do 拦截以do action 
			结尾的请求 肯定能使用 ERP 3. / 拦截所有 (不包括jsp) (包含.js .png.css) 强烈建议使用 前台 面向消费者 www.jd.com/search对静态资源放行 -->
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>


	<!-- spring框架自带的过滤器用来处理乱码问题,名字就叫encoding -->
	<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>
    <!-- 过滤器encoding过滤以action结尾的url请求,进行乱码处理 -->
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>

</web-app>

src下

applicationContext.xml文件

用于配置spring容器

<?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
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:dbconfig.properties</value>
		</property>
	</bean>
	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.uname}" />
		<property name="password" value="${jdbc.upwd}" />
	</bean>
	<!-- 配置session工厂 -->
	<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
	</bean>
	
	
	<!-- mapper扫描式开发 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.wowowo.mapper"></property>
	</bean>
	

	<!-- Spring Aop事务操作 ,以下暂时还没用到-->
	<!-- 事务核心管理器, 操作事务全靠这个对象, 必须配置 -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 配置事务通知  
		属性介绍
		name : service中的方法名
		rollback-for : 发生何种异常回滚
		read-only : 是否只读(建议查询的方法设置为true)
		isolation : 事务隔离级别 (建议听架构师的)
		propagation : 事务传播行为 , 无脑选择 REQUIRED
	-->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="insert*" rollback-for="java.lang.Exception" read-only="false" isolation="READ_UNCOMMITTED" propagation="REQUIRED" />
			<tx:method name="delete*" rollback-for="java.lang.Exception" read-only="false" isolation="READ_UNCOMMITTED" propagation="REQUIRED" />
			<tx:method name="update*" rollback-for="java.lang.Exception" read-only="false" isolation="READ_UNCOMMITTED" propagation="REQUIRED" />
			<tx:method name="select*" rollback-for="java.lang.Exception" read-only="true" isolation="READ_COMMITTED" propagation="REQUIRED" />
			<tx:method name="tranMoney" rollback-for="java.lang.Exception" read-only="false" isolation="READ_UNCOMMITTED" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>


	<!-- 配置织入 -->
	<aop:config>
		<aop:pointcut id="pc"
			expression="execution(* com.wowowo.service..*ServiceImpl.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pc" />
	</aop:config>


</beans>

dconfig.properties文件

配置数据库连接参数

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm_ssm
jdbc.uname=root
jdbc.upwd=root

log4j.properties文件

把mybatis的操作流程打印在控制台方便调试

# 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

springmvc.xml文件

配置springmvc框架

<?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">
	<!-- 注解驱动 -->
	<mvc:annotation-driven />

	<!-- 扫描指定包下的注解 -->
	<context:component-scan base-package="com.wowowo"></context:component-scan>

	<!-- 配置拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 所有的请求都进入拦截器,实际上本例中值拦截*.action,因为在webxml中,springmvc映射的url是以action结尾 -->
			<mvc:mapping path ="/**" />
			<!-- 配置具体的拦截器 -->
			<bean class = "com.wowowo.interceptor.HandlerInterceptor1" />
		</mvc:interceptor>
	</mvc:interceptors>

</beans>

SqlMapConfig.xml

mybatis的配置文件,因为和spring容器整合了,所以说大多数配置都移到了spring框架的配置文件applicationContext.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>
	<!-- 起简单的别名 -->
	<typeAliases>
		<package name="com.wowowo.bean" />
	</typeAliases>

</configuration>

4.复制前端代码

集体复制到WebContent下

把所有涉及到访问项目资源的地方,其中的项目名硬编码改为用el表达式动态获取域对象里的项目名,这样以后更换了项目名也没关系

${pageContext.request.contextPath}

添加

【任务内容】

1.登录功能

实现登录功能,且在未登录情况下访问首页会强制跳转到登录页面(强制跳转功能做了一半)

2.分页功能

客户列表显示界面具有分页,模糊查询功能

【登录功能】

分析

功能实现的主要内容是对登录系统这个按钮进行设计,后端的流程图如下

逆向工程生成和登录有关的实体类,并把它们移动到项目中

方法改为post,表单建议都用post

登录的jsp页面:

一个表单形式的用户名密码还有提交按钮

改动:

1.保证登录界面是最大的父窗口,如果当前页面(登录)不是最大的父页面,那么地址栏就会跳转到登录页面,因为采用了框架页面,所以有可能在session失效的情况下访问某些页面,会出现一部分框架显示登录页面的情况

<script type="text/javascript">
	window.onload = function(){
		// 判断当前窗口是不是最大的父窗口
		if(window != window.parent){
			// 不是的话把父窗口的地址栏改掉
			window.parent.location = "${pageContext.request.contextPath}/user/login.action";
		}
	}
</script>

2.留一块合适的地方用于显示错误信息

<td>${error}</td>

UserController类:

类的包名,导的包就不写了

service层依赖和UserController类名的注解要写上



@Controller
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserService us;
	@Autowired
	private SysRoleService srs;

login方法

	//万一用户直接在url访问login.action那么直接转发到login.jsp页面
    @RequestMapping(value = "/login.action", method = RequestMethod.GET)
	public String login(HttpServletRequest request){
		return "/login.jsp"; 
	}
	
	
	
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public String login(SysUser sysUser,HttpSession session,Model model) {
		
		try {
			//调用service方法查询
			SysUser u=us.getUserByUnameandUpwd(sysUser);
			//登录成功,就把用户的id放到session中
			//过滤器还没写,所以用户直接访问首页时,暂时没法判断用户是否登录成功
			session.setAttribute("user",u);
			model.addAttribute("userId", u.getUserId());
			//转发到首页,也可以用重定向,但是重定向的话model里的k-v就无法拿过去,无所谓,反正session里面有
			return "/index.jsp";
			
		} catch (Exception e) {
			//如果捕捉到了service层的异常,那么说明用户名或者密码错了,并移除session中的uid
			//功能:防止登录成功后再次登录,如果失败还能进入首页,有丶绕口
			session.removeAttribute("user");
			//模型对象添加错误信息
			model.addAttribute("error", e.getMessage());
			//转发到登录页面
			return "/login.jsp";
			
		}

其实在前端jsp页面应该使用ajax技术,登录按钮绑定一个事件,里面调用ajax函数,访问登录的servlet方法,这个方法的方法名上面,requestmapping注解下面,加上一个@responsebody注解,这样返回的要么是成功所跳转的url要么是错误信息,前端根据这些做相应处理,登录成功则按照传过来的url跳转(window.loacton.href),失败则把错误信息显示。

调用service方法查询

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private SysUserMapper sm;

	@Autowired
	private SysUserRoleMapper surm;

	@Autowired
	private SysRoleMapper srm;

	@Override
	public SysUser getUserByUnameandUpwd(SysUser sysUser) throws Exception {
		// md5加密
		String md5 = MD5Utils.md5(sysUser.getUserPassword());
		sysUser.setUserPassword(md5);
		SysUserExample se = new SysUserExample();
		Criteria ca = se.createCriteria();
		// 单查一个用户名
		ca.andUserCodeEqualTo(sysUser.getUserCode());
		List<SysUser> list = sm.selectByExample(se);
		//如果用户名存在
		if (list != null && list.size() > 0) {

			SysUser user = list.get(0);
			//根据用户名查密码
			if (user.getUserPassword().equals(sysUser.getUserPassword())) {
				//密码匹配
				return user;
			} else {
				//抛出异常,让service层接收并以json格式返回
				throw new Exception("密码错误");
			}

		} else {
			//抛出异常,让service层接收并以json格式返回
			throw new Exception("用户名不存在");
		}

	}

03 显示登录错误的信息

前端通过传过来的model对象获取错误信息

【客户列表(带分页功能)】

分页查询是怎么做的?

[前端]
1. 当你点击客户列表/筛选/前一页/后一页/某一页go
都是提交表单
(提示: 提交表单是一个信息点, 因为前端到后端的方式很多, a标签, location.href, ...)

2. 表单中的数据:
    1) 搜索条件(可能为空)
    2) 当前页数
    3) 每页显示条数

[后端]
[控制层]
3. Controller就可以收到请求, 客户端传上来的参数都封装到了方法参数的QueryVo里面

4. 调用业务逻辑层的方法,把vo参数传进去,查询列表

[业务逻辑层-数据访问层]
5. 业务逻辑层拿到vo参数之后, 先调用mapper查询记录总数

6. 封装pagebean对象, 根据pageNum, pageSize, totalCount, 
    计算出LIMIT的第一个参数和最大页数

7. 用计算出来的LIMIT参数和pageSize, 调用mapper方法, 查询某一页的数据
 结果封装进pagebean

8. 返回pageBean

[控制层]
9. 拿到pageBean之后, 放到model中
10. 把用户之前上传的queryVo也放到model中
11. 把页面视图路劲设置为list.jsp

[jsp]
12. 把数据用jstl和el表达式写好

-----------------------------------------------------------------------------------

代码实现:

前端页面:

由于要和后面联系人功能的选择客户公用一个界面,所以里面添加了些许jstl表达式,这里只写客户列表的显示功能,选择功能到后面再讲。

这尼玛前端界面魔板像坨翔一样

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<TITLE>客户列表</TITLE> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK href="${pageContext.request.contextPath }/css/Style.css" type=text/css rel=stylesheet>
<LINK href="${pageContext.request.contextPath }/css/Manage.css" type=text/css
	rel=stylesheet>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<SCRIPT language=javascript>
	function to_page(page){
		if(page){
			// 把要跳转的页数值放到id="page"的input标签内,然后提交表单 
			$("#page").val(page);
		}
		document.customerForm.submit();
		
	}
	//这个用于客户拜访记录功能的,客户列表暂时用不到
	function clickSelect(id,name){
		//获取打开的window窗口对象
		var win=window.opener;
		//获取这个窗口的dom对象
		var winDom=win.document;
		//拿到id隐藏域和name域的dom对象
		var custid=winDom.getElementById("custId");
		var custname=winDom.getElementById("custName");
		//设置属性zhi
		custid.value=id;
		custname.value=name;
		close();
		
	}
</SCRIPT>

<META content="MSHTML 6.00.2900.3492" name=GENERATOR>
</HEAD>
<BODY>
<!-- action路径里面的jstl标签也用于客户拜访记录列表 -->
	<FORM id="customerForm" name="customerForm"
		action="${pageContext.request.contextPath }/customer/list.action<c:if test="${queryVo.select}">?select=true</c:if>"
		method=post>
		
		<TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
			<TBODY>
				<TR>
					<TD width=15><IMG src="${pageContext.request.contextPath }/images/new_019.jpg"
						border=0></TD>
					<TD width="100%" background="${pageContext.request.contextPath }/images/new_020.jpg"
						height=20></TD>
					<TD width=15><IMG src="${pageContext.request.contextPath }/images/new_021.jpg"
						border=0></TD>
				</TR>
			</TBODY>
		</TABLE>
		<TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
			<TBODY>
				<TR>
					<TD width=15 background=${pageContext.request.contextPath }/images/new_022.jpg><IMG
						src="${pageContext.request.contextPath }/images/new_022.jpg" border=0></TD>
					<TD vAlign=top width="100%" bgColor=#ffffff>
						<TABLE cellSpacing=0 cellPadding=5 width="100%" border=0>
							<TR>
								<TD class=manageHead>当前位置:客户管理 &gt; 客户列表</TD>
							</TR>
							<TR>
								<TD height=2></TD>
							</TR>
						</TABLE>
						<TABLE borderColor=#cccccc cellSpacing=0 cellPadding=0
							width="100%" align=center border=0>
							<TBODY>
								<TR>
									<TD height=25>
										<TABLE cellSpacing=0 cellPadding=2 border=0>
											<TBODY>
												<TR>
												<!-- 这里是筛选条件的输入框,value的作用是回显,这样点击筛选按钮之后,你输入的关键字会通过服务器返回,name的话springmvc框架自动会给相应的bean元素注入属性 -->
													<TD>客户名称:</TD>
													<TD><INPUT class=textbox id=sChannel2
														style="WIDTH: 80px" maxLength=50 value="${queryvo.customer.custName}" name="customer.custName"></TD>
													<!-- 这里规范化编程的话就不是submit了,而是绑定一个onclick事件 -->
													<TD><INPUT class=button id=sButton2 type=submit
														value=" 筛选 " name=sButton2></TD>
												</TR>
											</TBODY>
										</TABLE>
									</TD>
								</TR>
							    
								<TR>
									<TD>
										<TABLE id=grid
											style="BORDER-TOP-WIDTH: 0px; FONT-WEIGHT: normal; BORDER-LEFT-WIDTH: 0px; BORDER-LEFT-COLOR: #cccccc; BORDER-BOTTOM-WIDTH: 0px; BORDER-BOTTOM-COLOR: #cccccc; WIDTH: 100%; BORDER-TOP-COLOR: #cccccc; FONT-STYLE: normal; BACKGROUND-COLOR: #cccccc; BORDER-RIGHT-WIDTH: 0px; TEXT-DECORATION: none; BORDER-RIGHT-COLOR: #cccccc"
											cellSpacing=1 cellPadding=2 rules=all border=0>
											<TBODY>
												<TR
													style="FONT-WEIGHT: bold; FONT-STYLE: normal; BACKGROUND-COLOR: #eeeeee; TEXT-DECORATION: none">
													<TD>客户名称</TD>
													<TD>客户级别</TD>
													<TD>客户来源</TD>
													<TD>客户行业</TD>
													<TD>电话</TD>
													<TD>手机</TD>
													<TD>操作</TD>
												</TR>
												<!-- 遍历传过来的客户list -->
												<c:forEach items="${pageBean.list}" var="customer">
												<TR
													style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
													<TD>${customer.custName}</TD>
													<TD>${customer.custLevel.dictItemName}</TD>
													<TD>${customer.custSource.dictItemName}</TD>
													<TD>${customer.custIndustry.dictItemName}</TD>
													<TD>${customer.custPhone }</TD>
													<TD>${customer.custMobile }</TD>
													<TD>
													<!-- jstl标签用于判断右侧是选择功能还是修改删除功能 -->
													<c:if test="${!queryVo.select}">
													<a href="${pageContext.request.contextPath }/customer/toEdit.action?custId=${customer.custId}">修改</a>
													&nbsp;&nbsp;
													<a href="${pageContext.request.contextPath }/customer/delete.action?custId=${customer.custId}">删除</a>
													</c:if>
													<c:if test="${queryVo.select}">
													<input type="button" value="选择" onclick="clickSelect('${customer.custId}','${customer.custName}')"/>
													</c:if>
													</TD>
												</TR>
												
												</c:forEach>

											</TBODY>
										</TABLE>
									</TD>
								</TR>
								
								<TR>
									<TD><SPAN id=pagelink>
											<DIV
												style="LINE-HEIGHT: 20px; HEIGHT: 20px; TEXT-ALIGN: right">
												<!-- 分页功能 -->
												共[<B>${pageBean.total}</B>]条记录,[<B>${pageBean.totalPage}</B>]页
												,每页显示
												<!-- 下拉框,配置每页显示的条数,这里的pageSize传到后端,在queryvo中能获取到 -->
												<select name="pageSize">
												<option value="5" <c:if test="${pageBean.pageSize==5 }">selected</c:if>>5</option>
												<option value="10" <c:if test="${pageBean.pageSize==10 }">selected</c:if>>10</option>
												</select>
												条
												<!-- js方法:用于分页功能 -->
												<!-- 向前翻页如果是第一页也没关系,后端会处理 -->
												[<A href="javascript:to_page(${pageBean.pageNum-1})">前一页</A>]
												<B>${pageBean.pageNum}</B>
												<!-- 三目运算符,用于判断当前页是否是最后一页 -->
												[<A href="javascript:to_page(${pageBean.pageNum>=pageBean.totalPage?pageBean.pageNum:pageBean.pageNum+1})">后一页</A>] 
												到
												<!-- 
												1.点击上一页,下一页触发jsp函数,该函数会把页数放到下面的text文本框内,然后提交表单
												2.点输入页数点击go按钮触发js函数(js函数的参数可以),也是提交表单
												这里的文本框,name=pageNum传到后端,在queryvo对象中能获取到 
												-->
												<input type="text" size="3" id="page" name="pageNum"  />
												页
												
												<input type="button" value="Go" onclick="to_page()"/>
											</DIV>
									</SPAN></TD>
								</TR>
							</TBODY>
						</TABLE>
					</TD>
					<TD width=15 background="${pageContext.request.contextPath }/images/new_023.jpg"><IMG
						src="${pageContext.request.contextPath }/images/new_023.jpg" border=0></TD>
				</TR>
			</TBODY>
		</TABLE>
		<TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
			<TBODY>
				<TR>
					<TD width=15><IMG src="${pageContext.request.contextPath }/images/new_024.jpg"
						border=0></TD>
					<TD align=middle width="100%"
						background="${pageContext.request.contextPath }/images/new_025.jpg" height=15></TD>
					<TD width=15><IMG src="${pageContext.request.contextPath }/images/new_026.jpg"
						border=0></TD>
				</TR>
			</TBODY>
		</TABLE>
	</FORM>
</BODY>
</HTML>

【后端】

数据模型层:

因为数据库表采用了第三范式,所以在表内不能出现别的表的非主关键字,所以客户表里的客户来源,客户部门,客户等级的中文名称(实际要显示的)都是来自basedict(数据字典)表,在模型对象的设计时就要考虑获取到客户表的这三个字段之后,去数据字典表查询相关的记录。

联系人字段建议改成老板,因为联系人和客户是多对一,在修改联系人所属客户的时候要跨表修改,难度很大,时间有限,这个功能就不做了

[数据字典表]
 管理项目中的所有枚举项(有限的选项)

所以customervo的设计思路如下:

customervo

package com.wowowo.bean;

/*
客户的vo对象
*/

public class CstCustomerVo {
	private Long custId;

	private String custName;

	private Long custUserId;

	private Long custCreateId;
	//数据字典中获取客户来源对象
	private BaseDict custSource;
	//数据字典中获取客户所属部门对象
	private BaseDict custIndustry;
	//数据字典中获取客户等级对象
	private BaseDict custLevel;

	private String custLinkman;

	private String custPhone;

	private String custMobile;
	//构造方法把customer对象(po对象)传入
	public CstCustomerVo(CstCustomer po) {
		this.custId = po.getCustId();
		this.custName = po.getCustName();
		this.custUserId = po.getCustUserId();
		this.custCreateId = po.getCustCreateId();
        //联系人可以改成老板
		this.custLinkman = po.getCustLinkman();
		this.custPhone = po.getCustPhone();
		this.custMobile = po.getCustMobile();
	}

	public Long getCustId() {
		return custId;
	}

	public void setCustId(Long custId) {
		this.custId = custId;
	}

	public String getCustName() {
		return custName;
	}

	public void setCustName(String custName) {
		this.custName = custName == null ? null : custName.trim();
	}

	public Long getCustUserId() {
		return custUserId;
	}

	public void setCustUserId(Long custUserId) {
		this.custUserId = custUserId;
	}

	public Long getCustCreateId() {
		return custCreateId;
	}

	public void setCustCreateId(Long custCreateId) {
		this.custCreateId = custCreateId;
	}

	public BaseDict getCustSource() {
		return custSource;
	}

	public void setCustSource(BaseDict custSource) {
		this.custSource = custSource;
	}

	public BaseDict getCustIndustry() {
		return custIndustry;
	}

	public void setCustIndustry(BaseDict custIndustry) {
		this.custIndustry = custIndustry;
	}

	public BaseDict getCustLevel() {
		return custLevel;
	}

	public void setCustLevel(BaseDict custLevel) {
		this.custLevel = custLevel;
	}

	public String getCustLinkman() {
		return custLinkman;
	}

	public void setCustLinkman(String custLinkman) {
		this.custLinkman = custLinkman == null ? null : custLinkman.trim();
	}

	public String getCustPhone() {
		return custPhone;
	}

	public void setCustPhone(String custPhone) {
		this.custPhone = custPhone == null ? null : custPhone.trim();
	}

	public String getCustMobile() {
		return custMobile;
	}

	public void setCustMobile(String custMobile) {
		this.custMobile = custMobile == null ? null : custMobile.trim();
	}

	@Override
	public String toString() {
		return "CstCustomerVo [custId=" + custId + ", custName=" + custName + ", custUserId=" + custUserId
				+ ", custCreateId=" + custCreateId + ", custSource=" + custSource + ", custIndustry=" + custIndustry
				+ ", custLevel=" + custLevel + ", custLinkman=" + custLinkman + ", custPhone=" + custPhone
				+ ", custMobile=" + custMobile + "]";
	}

}

为了满足分页的功能,所以要写一个pagebean类来实现分页功能,在这个类里面还要有个泛型list以达到分页功能复用的效果

pagebean类

package com.wowowo.bean;

import java.util.List;
//泛型类,可以存放任何类型的list
public class PageBean<T> {
	//当前页数
	private Integer pageNum;
	//每页大小
	private Integer pageSize;
	//起始页,也就是sql的limit语句第一个参数
	private Integer startPage;
	//所有记录数
	private Integer total;
	//总页数
	private Integer totalPage;
	//泛型容器存放记录
	private List<T> list;

	public PageBean(Integer pageNum, Integer pageSize, Integer total) {
		//构造方法传入页数,每页大小,总共记录数量
		this.pageNum = pageNum;
		this.pageSize = pageSize;
		this.total = total;
		//点击客户列表或者是当前第一页的情况下点击前一页,默认设为第一页
		if (pageNum == null || pageNum <= 0) {

			this.pageNum = 1;
		}
		//点击客户列表或者每页显示记录数小于等于0的情况下,默认设为每页5条记录
		if (pageSize == null || pageSize <= 0) {

			this.pageSize = 5;
		}
		//根据页数和每页显示记录数生成limit第一个参数
		startPage = (this.pageNum - 1) * this.pageSize;
		//根据每页显示记录数和总共记录数,生成总页数
		totalPage = (this.total + this.pageSize - 1) / this.pageSize;
		
	}

	
}

因为分页查询是调selectbyexample的sql语句的,该语句入口参数是CstCustomerExample类型,所以在逆向工程生成的查询类(CstCustomerExample)中添加2个成员属性和他们的get/set方法,这2个成员属性用于limit参数

    protected Integer off;
	protected Integer len;

	public Integer getOff() {
		return off;
	}

	public void setOff(Integer off) {
		this.off = off;
	}

在mapper.xml中的id为selectbyexample的查询语句中加入分页条件

	<if test="off!=null &amp;&amp; len!=null">
			limit #{off} ,#{len}
		</if>

QueryVo类:用于筛选,分页,

public class QueryVo {

	private Integer pageNum;
	private Integer pageSize;
	private CstCustomer customer;

数据模型层设计完毕,接下来就可以写控制层和service层了

控制层:

@Controller
@RequestMapping("customer")
public class CustomerController {
	
	@Autowired
	private CustomerService cs;

	@RequestMapping(value = "list.action")
	public String list(QueryVo queryvo, Model model) {

		//调service层方法传入筛选对象查询
		PageBean<CstCustomerVo> pageBean=cs.getCustomerList(queryvo);
		model.addAttribute("pageBean", pageBean);
		model.addAttribute("queryVo", queryvo);
		System.out.println(queryvo.getSelect());
                //return "forward:/jsp/customer/list.jsp";和下面的效果一样,都是转发
		return "/jsp/customer/list.jsp";

	}

service层:

package com.wowowo.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wowowo.bean.CstCustomerVo;
import com.wowowo.bean.BaseDict;
import com.wowowo.bean.CountInfo;
import com.wowowo.bean.CstCustomer;
import com.wowowo.bean.CstCustomerExample;
import com.wowowo.bean.CstCustomerExample.Criteria;
import com.wowowo.bean.PageBean;
import com.wowowo.bean.QueryVo;
import com.wowowo.mapper.BaseDictMapper;
import com.wowowo.mapper.CstCustomerMapper;
import com.wowowo.service.CustomerService;

@Service
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private CstCustomerMapper customerMapper;
	@Autowired
	private BaseDictMapper baseDictMapper;

	@Override
	public PageBean<CstCustomerVo> getCustomerList(QueryVo qvo) {
		CstCustomerExample example = new CstCustomerExample();
		Criteria criteria = example.createCriteria();
		// qvo也就是筛选条件不为空的情况下,查寻对象里添加筛选条件
		if (qvo != null && qvo.getCustomer() != null && qvo.getCustomer().getCustName() != null
				&& qvo.getCustomer().getCustName().length() > 0) {
			// 为了防sql注入,还是用#{}的方式,模糊查询记得要在两边加上"%"
			criteria.andCustNameLike("%" + qvo.getCustomer().getCustName() + "%");
		}
		// 1. 查记录总数
		int totalCount = customerMapper.countByExample(example);

		// 2. 封装pageBean
        //页数和每页记录数是从上传的QueryVo获取
		PageBean<CstCustomerVo> pageBean = new PageBean<>(qvo.getPageNum(), qvo.getPageSize(), totalCount);

		// 把pagebean的参数放入example
		example.setOff(pageBean.getStartPage());
		example.setLen(pageBean.getPageSize());

		// 3. LIMIT查询
		List<CstCustomer> poList = customerMapper.selectByExample(example);
		List<CstCustomerVo> voList = new ArrayList<>();

		// 4. 把poList转成voList
		for (CstCustomer po : poList) {
			CstCustomerVo vo = new CstCustomerVo(po);

			// 查询数据库, 根据数据字典项ID查出数据字典对象, 设置进vo
			vo.setCustIndustry(baseDictMapper.selectByPrimaryKey(po.getCustIndustry()));
			vo.setCustSource(baseDictMapper.selectByPrimaryKey(po.getCustSource()));
			vo.setCustLevel(baseDictMapper.selectByPrimaryKey(po.getCustLevel()));

			voList.add(vo);
		}

		// 放到pagebean
		pageBean.setList(voList);

		// 4. 返回pagebean
		return pageBean;
	}

猜你喜欢

转载自blog.csdn.net/qq_36194262/article/details/83996294