当前位置:   article > 正文

Springmvc框架---案例CRMSSM(1.0)实训 2019/11/1_springmav框架实战实验报告结果

springmav框架实战实验报告结果

在这里插入图片描述

整体介绍

如图 我们来实现一下—>

  • 多条件查询 ,
  • 下拉列表
  • 修改(数据回显), 保持回数据库
  • 删除,+提示“警告信息”+并刷新页面。
  • 分页,
  • 显示所有内容

在这里插入图片描述

在这里插入图片描述

3. SSM整合

  1. Dao层
    pojo和映射文件以及接口
    SqlMapConfig.xml mybatis核心配置文件
    ApplicationContext-dao.xml 整合后spring在dao层的配置
    数据源
    会话工厂
    扫描Mapper

  2. service层
    事务 ApplicationContext-trans.xml
    @Service注解扫描 ApplicationContext-service.xml

  3. controller层
    SpringMvc.xml
    注解扫描:扫描@Controller注解
    注解驱动:显示的配置了最新版的处理器映射器和处理器适配器
    视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径

  4. web.xml
    springMvc前端控制器配置
    spring监听

  5. 参数绑定(从请求中接收参数)
    1)默认类型:
    在controller方法中可以有也可以没有,看需求随意添加.
    httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类,一般用的不多)
    2)基本类型:string,double,float,integer,long.boolean
    3)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
    4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性…
    5)自定义转换器converter:
    作用:由于springMvc无法将string自动转换成date所以需要自己手动编写类型转换器
    需要编写一个类实现Converter接口
    在springMvc.xml中配置自定义转换器
    在springMvc.xml中将自定义转换器配置到注解驱动上

3. SSM整合

  1. Dao层
    pojo和映射文件以及接口
    SqlMapConfig.xml mybatis核心配置文件
    ApplicationContext-dao.xml 整合后spring在dao层的配置
    数据源
    会话工厂
    扫描Mapper

  2. service层
    事务 ApplicationContext-trans.xml
    @Service注解扫描 ApplicationContext-service.xml

  3. controller层
    SpringMvc.xml
    注解扫描:扫描@Controller注解
    注解驱动:显示的配置了最新版的处理器映射器和处理器适配器
    视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径

  4. web.xml
    springMvc前端控制器配置
    spring监听

  5. 参数绑定(从请求中接收参数)
    1)默认类型:
    在controller方法中可以有也可以没有,看需求随意添加.
    httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类,一般用的不多)
    2)基本类型:string,double,float,integer,long.boolean
    3)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
    4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性…
    5)自定义转换器converter:
    作用:由于springMvc无法将string自动转换成date所以需要自己手动编写类型转换器
    需要编写一个类实现Converter接口
    在springMvc.xml中配置自定义转换器
    在springMvc.xml中将自定义转换器配置到注解驱动上

4. 环境搭建

工程使用Springmvc、spring、mybatis框架整合完成。
属性配置
jdbc.properties 数据库连接

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

resource.properties 查询条件

customer.from.type=002
customer.industry.type=001
customer.level.type=006

  1. SqlMapConfig.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  1. applicationContext-dao.xml
<beansxmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	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 
		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/task
		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo        
		http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

	<!-- 配置 读取properties文件 jdbc.properties -->
	<context:property-placeholderlocation="classpath:jdbc.properties"/>
	<!-- 配置 数据源 -->
	<beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource">
		<!-- 驱动 -->
		<propertyname="driverClassName"value="${jdbc.driver}"/>
		<!-- url -->
		<propertyname="url"value="${jdbc.url}"/>
		<!-- 用户名 -->
		<propertyname="username"value="${jdbc.username}"/>
		<!-- 密码 -->
		<propertyname="password"value="${jdbc.password}"/>
	</bean>

	<!-- 配置 Mybatis的工厂 -->
	<beanclass="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 -->
		<propertyname="dataSource"ref="dataSource"/>
		<!-- 配置Mybatis的核心 配置文件所在位置 -->
		<propertyname="configLocation"value="classpath:SqlMapConfig.xml"/>
		<!-- 配置pojo别名 -->
		<propertyname="typeAliasesPackage"value="cn.atcast.core.bean"></property>
	</bean>

	<!-- 配置 1:原始Dao开发 接口实现类 Mapper.xml 三个 2:接口开发 接口 不写实现类 Mapper.xml 两个 (UserDao、ProductDao 、BrandDao。。。。。。。) 3:接口开发、并支持扫描 cn.itcast.core.dao(UserDao。。。。。) 写在此包下即可被扫描到 .自动扫描 将Mapper接口生成代理注入到Spring Mybatis在与Spring集成的时候可以配置 MapperFactoryBean来生成Mapper接口的代理。-->
	<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<propertyname="basePackage"value="cn.atcast.core.dao"/>
	</bean>
</beans>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  1. applicationContext-service.xml
<beansxmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	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 
		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/task
		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo        
		http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
		<!-- 配置  扫描   @Service -->
		<context:component-scanbase-package="cn.atcast.core.service"/>
</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  1. applicationContext-trans.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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">
	<!-- 事务管理器 -->
	<beanid="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 数据源 -->
		<propertyname="dataSource"ref="dataSource"/>
	</bean>
	<!-- 通知 -->
	<tx:adviceid="txAdvice"transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 传播行为 -->
			<tx:methodname="save*"propagation="REQUIRED"/>
			<tx:methodname="insert*"propagation="REQUIRED"/>
			<tx:methodname="add*"propagation="REQUIRED"/>
			<tx:methodname="create*"propagation="REQUIRED"/>
			<tx:methodname="delete*"propagation="REQUIRED"/>
			<tx:methodname="update*"propagation="REQUIRED"/>
			<tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
			<tx:methodname="select*"propagation="SUPPORTS"read-only="true"/>
			<tx:methodname="get*"propagation="SUPPORTS"read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- 切面 -->
	<aop:config>
		<aop:advisoradvice-ref="txAdvice"
			pointcut="execution(* cn.atcast.core.service.*.*(..))"/>
	</aop:config>
</beans>
10)	Springmvc.xml
<beansxmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	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 
		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/task
		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo        
		http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
		
		<!-- 加载属性文件 -->
		<context:property-placeholderlocation="classpath:resource.properties"/>
		<!-- 配置扫描 器 -->
		<context:component-scanbase-package="cn.atcast.core.web.controller"/>
		<!-- 配置处理器映射器  适配器 -->
		<mvc:annotation-driven/>
		<!-- 配置视图解释器 jsp -->
<bean  id="jspViewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<propertyname="prefix"value="/WEB-INF/jsp/"/>
			<propertyname="suffix"value=".jsp"/>
		</bean>	
</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

属性文件的使用
在这里插入图片描述

  1. web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<welcome-file-list>
		<welcome-file>customer.action</welcome-file>
	</welcome-file-list>

	<!-- 上下文的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-*.xml</param-value>
	</context-param>
	<!-- Spring的监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- POST提交过滤器 UTF-8 -->
	<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>*.action</url-pattern>
	</filter-mapping>
	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>crm</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- 此处不配置 默认找 /WEB-INF/[servlet-name]-servlet.xml -->
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>crm</servlet-name>
		<!-- 1:*.do *.action 拦截以.do结尾的请求 (不拦截 jsppngjpg .js .css) 2:/ 拦截所有请求 
			(不拦截.jsp) 建议使用此种 方式 (拦截 .js.css .png) (放行静态资源) 3:/* 拦截所有请求(包括.jsp) 此种方式 不建议使用 -->
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
</web-app>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  1. 加入jsp及分页标签

http://localhost:8080/CRMSSM01/customer/list.action

13)工具类

在这里插入图片描述

package cn.atcast.common.utils;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.taglibs.standard.tag.common.core.UrlSupport;

/**
 * 显示格式 上一页 1 2 3 4 5 下一页
 */
public class NavigationTag extends TagSupport {
    static final long serialVersionUID = 2372405317744358833L;
    
    /**
     * request 中用于保存Page<E> 对象的变量名,默认为“page”
     */
    private String bean = "page";
    
    /**
     * 分页跳转的url地址,此属性必须
     */
    private String url = null;
    
    /**
     * 显示页码数量
     */
    private int number = 5;
    
    @Override
    public int doStartTag() throws JspException {
        JspWriter writer = pageContext.getOut();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Page page = (Page)request.getAttribute(bean); 
        if (page == null) 
            return SKIP_BODY;
        url = resolveUrl(url, pageContext);
        try {
        	//计算总页数
        	int pageCount = page.getTotal() / page.getSize();
        	if (page.getTotal() % page.getSize() > 0) {
        		pageCount++;
        	}
        	writer.print("<nav><ul class=\"pagination\">");
            //显示“上一页”按钮
        	if (page.getPage() > 1) {
                String preUrl = append(url, "page", page.getPage() - 1);
                preUrl = append(preUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + preUrl + "\">上一页</a></li>");
            } else {
            	writer.print("<li class=\"disabled\"><a href=\"#\">上一页</a></li>");
            }
            //显示当前页码的前2页码和后两页码 
            //若1 则 1 2 3 4 5, 若2 则 1 2 3 4 5, 若3 则1 2 3 4 5,
            //若4 则 2 3 4 5 6 ,若10  则 8 9 10 11 12
            int indexPage = (page.getPage() - 2 > 0)? page.getPage() - 2 : 1;  
            for(int i=1; i <= number && indexPage <= pageCount; indexPage++, i++) {
                if(indexPage == page.getPage()) {
                    writer.print( "<li class=\"active\"><a href=\"#\">"+indexPage+"<span class=\"sr-only\">(current)</span></a></li>");
                    continue;
                }
                String pageUrl  = append(url, "page", indexPage);
                pageUrl = append(pageUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + pageUrl + "\">"+ indexPage +"</a></li>");
            }
            //显示“下一页”按钮
            if (page.getPage() < pageCount) {
                String nextUrl  = append(url, "page", page.getPage() + 1);
                nextUrl = append(nextUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + nextUrl + "\">下一页</a></li>");
            } else {
            	writer.print("<li class=\"disabled\"><a href=\"#\">下一页</a></li>");
            }
            writer.print("</nav>");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }
    
    private String append(String url, String key, int value) {

        return append(url, key, String.valueOf(value));
    }
    
    /**
     * 为url 参加参数对
     * 
     * @param url
     * @param key
     * @param value
     * @return
     */
    private String append(String url, String key, String value) {
        if (url == null || url.trim().length() == 0) {
            return "";
        }

        if (url.indexOf("?") == -1) {
            url = url + "?" + key + "=" + value;
        } else {
            if(url.endsWith("?")) {
                url = url + key + "=" + value;
            } else {
                url = url + "&amp;" + key + "=" + value;
            }
        }
        
        return url;
    }
    
    /**
     * 为url 添加翻页请求参数
     * 
     * @param url
     * @param pageContext
     * @return
     * @throws javax.servlet.jsp.JspException
     */
    private String resolveUrl(String url, javax.servlet.jsp.PageContext pageContext) throws JspException{
    	//UrlSupport.resolveUrl(url, context, pageContext)
    	Map params = pageContext.getRequest().getParameterMap();
    	for (Object key:params.keySet()) {
    		if ("page".equals(key) || "rows".equals(key)) continue;
    		Object value = params.get(key);
    		if (value == null) continue;
    		if (value.getClass().isArray()) {
    			url = append(url, key.toString(), ((String[])value)[0]);
    		} else if (value instanceof String) {
    			url = append(url, key.toString(), value.toString());
    		}
    	}
        return url;
    }
    
    

    /**
     * @return the bean
     */
    public String getBean() {
        return bean;
    }

    /**
     * @param bean the bean to set
     */
    public void setBean(String bean) {
        this.bean = bean;
    }

    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }

    /**
     * @param url the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }

    public void setNumber(int number) {
        this.number = number;
    }
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172

package cn.atcast.common.utils;

import java.util.List;

public class Page<T> {
    
	private int total;
	private int page;
	private int size;
    private List<T> rows;
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public List<T> getRows() {
		return rows;
	}
	public void setRows(List<T> rows) {
		this.rows = rows;
	}	
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

StringUtils的isNotBlank和isNotEmpty区别整理

StringUtils.isNotBlank(null) = false
StringUtils.isNotBlank(“”) = false
StringUtils.isNotBlank(” “) = false
StringUtils.isNotBlank(“777”) = true
StringUtils.isNotBlank(” 444 “) = true

StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty(“”) = false
StringUtils.isNotEmpty(” “) = true
StringUtils.isNotEmpty(“777”) = true
StringUtils.isNotEmpty(” 444 “) = true

@RequestParam、@RequestBody和@ModelAttribute区别

  1. @RequestParam使用defaultValue属性设置默认值

前台: 用户名:< input type=“text” name=“username”>< br>
控制层 public String requestParamTest(@RequestParam(value=“username”) String userName) String userNick){}

也可以不使用@RequestParam,直接接收,此时要求controller方法中的参数名称要跟form中name名称一致

介绍:
@RequestParam
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。

  1. @RequestBody注解
    (1)@RequestBody接收一个对象。

public DbBook findBookByName(@RequestBody DbBook book){

(2)@RequestBody接收不同的字符串

前台
wx.request({
      url: host.host + `/WxProgram/deleteBookById`,
      method: 'POST',
      data: {
        nick: this.data.userInfo.nickName,
        bookIds: bookIds
      },
      success: (res) => {
        console.log(res);
        this.getCollectionListFn();
      },
      fail: (err) => {
        console.log(err);
      }
    })



controller


@RequestMapping(value="/deleteBookById",method=RequestMethod.POST)
@ResponseBody
public void deleteBookById(@RequestBody Map<String, String> map){
    String bookIds = map.get("bookIds");
    String nick = map.get("nick");
    String[] idArray = bookIds.split(",");
    Integer userId = wxService.findIdByNick(nick);
    for(String id : idArray){
        Integer bookid = Integer.parseInt(id);
        System.out.println("bookid: " + bookid);
        wxService.removeBookById(bookid, userId);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

注意:
@RequestBody用于post请求,不能用于get请求

这里涉及到使用@RequestBody接收不同的对象

  1. 创建一个新的entity,将两个entity都进去。这是最简单的,但是不够“优雅”。
  2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。
  3. 类似方法2,不过更为generic,实现自己的HandlerMethodArgumentResolver。
  1. @ModelAttribute
    @ModelAttribute注解类型将参数绑定到Model对象

4.总结
当前台界面使用GET或POST方式提交数据时,数据编码格式由请求头的ContentType指定。分为以下几种情况:

  1. application/x-www-form-urlencoded,这种情况的数据@RequestParam、@ModelAttribute可以处理,@RequestBody也可以处理。
  2. multipart/form-data,@RequestBody不能处理这种格式的数据。(form表单里面有文件上传时,必须要指定enctype属性值为multipart/form-data,意思是以二进制流的形式传输文件。)
  3. application/json、application/xml等格式的数据,必须使用@RequestBody来处理。

后续代码

CustomerDao

public interface CustomerDao {

	 List<Customer> selectCustomerList(Customer customer); //查询用户列用(包括多条件查询)
	 
	 Integer selectCustomerListCount(Customer customer); //查到的个数,用于分页
	 
	 Customer getCusotmerById(Long id); //按id查询
	 
	 void updateCustomer(Customer customer); //更新
	 
	 void deleteCustomer(Long id); //删除
	
}

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.atcast.core.dao.CustomerDao">

	<sql id="selectCustomerListWhere">
		<where>
	      <if test="cust_name != null" >
	        cust_name like "%"#{cust_name}"%"
	      </if>
	      <if test="cust_source != null" >
	        and cust_source = #{cust_source}
	      </if>
	      <if test="cust_industry != null" >
	        and cust_industry = #{cust_industry}
	      </if>
	      <if test="cust_level != null" >
	        and cust_level = #{cust_level}
	      </if>
    	</where>
	</sql>
	<select id="selectCustomerList" parameterType="customer" resultType="customer">
		SELECT
			cust_id,
			cust_name,
			cust_user_id,
			cust_create_id,
			b.dict_item_name cust_source,
			c.dict_item_name cust_industry,
			d.dict_item_name cust_level,
			cust_linkman,
			cust_phone,
			cust_mobile,
			cust_createtime
		FROM
			customer a
		LEFT JOIN (
			SELECT
				dict_id,
				dict_item_name
			FROM
				base_dict
			WHERE
				dict_type_code = '002'
		) b ON a.cust_source = b.dict_id
		LEFT JOIN (
			SELECT
				dict_id,
				dict_item_name
			FROM
				base_dict
			WHERE
				dict_type_code = '001'
		) c ON a.cust_industry = c.dict_id
		LEFT JOIN (
			SELECT
				dict_id,
				dict_item_name
			FROM
				base_dict
			WHERE
				dict_type_code = '006'
		) d ON a.cust_level = d.dict_id
		<include refid="selectCustomerListWhere"/>
		<if test="start !=null and rows != null">
			limit #{start},#{rows}
		</if>
	</select>
	
	<select id="selectCustomerListCount" parameterType="customer" resultType="int">
		select count(*)
		from customer
		<include refid="selectCustomerListWhere"/>
	</select>	
	
	<select id="getCustomerById" parameterType="long" resultType="customer">
		select * from customer where cust_id = #{id}
	</select>
	
	<update id="updateCustomer" parameterType="customer">
		update customer
		<set>
			<if test="cust_name!=null">
				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">
				cust_source=#{cust_source},
			</if>
			<if test="cust_industry!=null">
				cust_industry=#{cust_industry},
			</if>
			<if test="cust_level!=null">
				cust_level=#{cust_level},
			</if>
			<if test="cust_linkman!=null">
				cust_linkman=#{cust_linkman},
			</if>
			<if test="cust_phone!=null">
				cust_phone=#{cust_phone},
			</if>
			<if test="cust_mobile!=null">
				cust_mobile=#{cust_mobile},
			</if>
			<if test="cust_zipcode!=null">
				cust_zipcode=#{cust_zipcode},
			</if>
			<if test="cust_address!=null">
				cust_address=#{cust_address},
			</if>
			<if test="cust_createtime!=null">
				cust_createtime=#{cust_createtime},
			</if>
		</set>
		where cust_id=#{cust_id}
	</update>
	
	<delete id="deleteCustomer" parameterType="long">
		delete from customer where cust_id=#{id}
	</delete>

</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141

CustomerServiceImpl

/**
 * 客户管理
 *
 */

@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	private CustomerDao customerDao;


	@Override
	public Page<Customer> findCustomerList(Integer page, Integer rows, String custName, String custSource,
			String custIndustry, String custLevel) {
		Customer customer=new Customer();
		if(StringUtils.isNotBlank(custName)){ //判断用户名
			customer.setCust_name(custName);
		}
		
		if(StringUtils.isNotBlank(custSource)){ //判断用户名
			customer.setCust_source(custSource);
		}
		
		if(StringUtils.isNotBlank(custIndustry)){ //判断用户名
			customer.setCust_industry(custIndustry);;
		}
		if(StringUtils.isNotBlank(custLevel)){ //判断用户名
			customer.setCust_level(custLevel);
		}
		
	customer.setStart((page-1)*rows );
	customer.setRows(rows);
	
	List<Customer> customers = customerDao.selectCustomerList(customer);
	
	Integer count =customerDao.selectCustomerListCount(customer);
	
	Page<Customer> result = new Page<>();
	result.setPage(page);
	result.setRows(customers);
	result.setSize(rows);
	result.setTotal(count);

		return result;
	}

	@Override
	public Customer getCustomerById(Long id) {
		Customer customer=customerDao.getCusotmerById(id);
		return customer;
	}

	@Override
	public void updateCustomer(Customer customer) {
		customerDao.updateCustomer(customer);
		
	}	 

	@Override
	public void deleteCustomer(Long id) {
		customerDao.deleteCustomer(id);
		
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

CustomerController

@Controller
public class CustomerController {

	// 依赖注入
	@Autowired
	private CustomerService customerService;
	@Autowired
	private SystemService systemService;
	/*
	Spring 3支持@value注解的方式获取properties文件中的配置值,大简化了读取配置文件的代码。
	1、在applicationContext.xml文件中配置properties文件
	<!-- 配置 读取properties文件 jdbc.properties -->
		<context:property-placeholder location="classpath:jdbc.properties" />
	2、在bean中使用@value注解获取配置文件的值
	@Value("${customer.from.type}")
	 */
	@Value("${customer.from.type}")
	private String FROM_TYPE;
	@Value("${customer.industry.type}")
	private String INDUSTRY_TYPE;
	@Value("${customer.level.type}")
	private String LEVEL_TYPE;
	
	@RequestMapping(value = "/customer")
	public String showCumtomer() {
		return "redirect:/customer/list.action";
	}
	
	// 客户列表
	@RequestMapping(value = "/customer/list")
	public String list(@RequestParam(defaultValue="1")Integer page, @RequestParam(defaultValue="10")Integer rows, 
			String custName, String custSource,	String custIndustry, String custLevel, Model model) {

		Page<Customer> customers = customerService.findCustomerList(page, rows, custName, custSource, custIndustry,
				custLevel);
		model.addAttribute("page", customers);
		//客户来源
		List<BaseDict> fromType = systemService.findBaseDictListByType(FROM_TYPE);
		//客户所属行业
		List<BaseDict> industryType = systemService.findBaseDictListByType(INDUSTRY_TYPE);
		//客户级别
		List<BaseDict> levelType = systemService.findBaseDictListByType(LEVEL_TYPE);
		model.addAttribute("fromType", fromType);
		model.addAttribute("industryType", industryType);
		model.addAttribute("levelType", levelType);
		//参数回显到页面
		model.addAttribute("custName", custName);
		model.addAttribute("custSource", custSource);
		model.addAttribute("custIndustry", custIndustry);
		model.addAttribute("custLevel", custLevel);
		return "customer";
	}
	
	@RequestMapping("/customer/edit")
	@ResponseBody
	public Customer getCustomerById(Long id) {
		Customer customer = customerService.getCustomerById(id);
		return customer;
	}
	
	@RequestMapping("/customer/update")
	@ResponseBody
	public String customerUpdate(Customer customer) {
		customerService.updateCustomer(customer);
		return "OK";
	}
	@RequestMapping("/customer/delete")
	@ResponseBody
	public String customerDelete(Long id) {
		customerService.deleteCustomer(id);
		return "OK";
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

大家好,我是凯凯!

大家看完觉得不错 请点个赞呗! 评论一句也可以! 整理不易, 请转发加我的名字哦!

你的支持 使我更有动力!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/767639
推荐阅读
相关标签
  

闽ICP备14008679号