SSHDay03(异步查询客户的级别和来源, 保存客户上传文件 , UploadUtils, FastJsonUtil)

查询所有客户
异步获取客户级别
    ajax的代码
        var url = "${pageContext.request.contextPath}/dict_findByCode.action";
        var param ={"dict_type_code":"006"};
        //alert(param.dict_type_code);
        $.post(url,param,function(data){
            //遍历
             $(data).each(function(i,n){
                 //alert(i+":"+n);
                //alert(i+":"+n.dict_item_name);
                //alert(this.dict_item_name);
                //先获取值栈中的值,使用EL表达式
                var vsId = "${model.level.dict_id}";
                //值栈中的id值和变量的id值相同,让其选中
                if(vsId == n.dict_id){
                //jq的dom操作
                    $("#levelId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
                }else{
                    $("#levelId").append("<option value='"+n.dict_id+"' >"+n.dict_item_name+"</option>");

                }
             });         
        },"json");

    DictAction的代码
        public String findByCode(){
            //调用业务层
            //      System.out.println("--------"+dict.getDict_type_code());
            List<Dict> list = dictService.findByCode(dict.getDict_type_code());
    //      List<Dict> list = dictService.findByCode("006");
            //使用fastjson把list转换成json字符串
            String jsonString = FastJsonUtil.toJSONString(list);
            //把json字符串写到浏览器
            HttpServletResponse response = ServletActionContext.getResponse();
            //输出
            FastJsonUtil.write_json(response, jsonString);

            return NONE;
        }

    CustomerAction的分页查询的代码
        public String findByPage(){
            //调用service业务层
            DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
            //拼接查询的条件
            String cust_name = customer.getCust_name();
            if(cust_name !=null && !cust_name.trim().isEmpty()){
                //说明,客户的名称输入值了
                criteria.add(Restrictions.like("cust_name", "%"+cust_name+"%"));
            }
            //拼接客户级别
            Dict level = customer.getLevel();
            if(level!=null && !level.getDict_id().trim().isEmpty()){
                //说明,客户的级别肯定选择了一个
                criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
            }
            Dict source = customer.getSource();
            if(source!=null && !source.getDict_id().trim().isEmpty()){
                //说明,客户的级别肯定选择了一个
                criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
            }

            //查询
            PageBean<Customer> page = customerService.findByPage(pageCode,pageSize,criteria);
            //压栈
            ValueStack vs = ActionContext.getContext().getValueStack();
            //栈顶是map<"page",page对象>
            vs.set("page", page);
            return "page";
        }

添加客户功能(文件上传)
1、跳转到客户的添加页面,需要通过ajax来显示客户的级别,客户的来源和客户的行业
2、添加文件上传的选择项
3、客户端三个注意事项
    method="post"
    enctype="multipart/form-data"
    <INPUT type="file" name="upload"/>
4、Struts2框架使用拦截器完成文件上传,并且底层使用也是FileUpload开源的组件
    提供FileUpload拦截器,用于解析multipart/form-data编码格式请求,解析上传文件的内容
    fileUpload拦截器默认在defaultStack栈中,默认会执行的

    在Action中编写文件上传,需要定义三个属性
        文件类型File,属性名与表单中file的name属性名一致
        字符串类型String,属性名:前段是name属性名一致+ContentType
        字符串类型String,属性名:前段是name属性名一致+FileName

        最后需要为上述的三个属性通过set方法
        可以通过FileUtils提供copyFile进行文件复制,将上传文件,保存到服务器端

5、文件上传中的问题
    先配置input逻辑视图
    在页面中显示错误信息
    文件上传的总大小默认值是2M,如果超过了2M,程序会报出异常,可以使用<s:actionError>来查看具体信息
        解决总大小的设置,找到常量
            struts.multipart.parser = jakarta   默认文件上传解析器,就是FileUpload组件
            struts.multipart.saveDir= 文件上传的临时文件存储目录
            struts.multipart.maxSize=2097152 文件上传的最大值(总大小),默认是2M

        可以在struts.xml中设置常量,修改文件上传的默认总大小
            <constant name="struts.multipart.maxSize" value="20971520"></constant>

    5、还可以通过配置拦截器来设置文件上传的一些属性
        先在<action>标签中引入文件上传的拦截器
            <interceptor-ref name="defaultStack">
                <!-- 设置单个上传文件的大小 -->
                <param name="fileUpload.maximumSize">2097152</param>
                <!-- 决定上传文件的类型 -->
                <param name="fileUpload.allowedExtensions">.jpg,.txt</param>
            </interceptor-ref>

FastJsonUtil.java

package my.utils;

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

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJsonUtil {

    /**
     * 将对象转成json串
     * @param object
     * @return
     */
    public static String toJSONString(Object object){
        //DisableCircularReferenceDetect来禁止循环引用检测
        return JSON.toJSONString(object,SerializerFeature.DisableCircularReferenceDetect);
    }
    //输出json
    public static void write_json(HttpServletResponse response,String jsonString)
    {
        response.setContentType("application/json;utf-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(jsonString);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
    /**
     * ajax提交后回调的json字符串
     * @return
     */
    public static String ajaxResult(boolean success,String message)
    {
        Map map=new HashMap();
        map.put("success", success);//是否成功
        map.put("message", message);//文本消息
        String json= JSON.toJSONString(map);        
        return json;
    }


    /**
     * JSON串自动加前缀
     * @param json 原json字符串
     * @param prefix 前缀
     * @return 加前缀后的字符串
     */

    public static String JsonFormatterAddPrefix(String json,String prefix,Map<String,Object> newmap)
    {
        if(newmap == null){
            newmap = new HashMap();
        }
        Map<String,Object> map = (Map) JSON.parse(json);

        for(String key:map.keySet())
        {
            Object object=map.get(key);
            if(isEntity(object)){
                String jsonString = JSON.toJSONString(object);
                JsonFormatterAddPrefix(jsonString,prefix+key+".",newmap);

            }else{
                newmap.put(prefix+key, object);
            }

        }
        return JSON.toJSONString(newmap);       
    }
    /**
     * 判断某对象是不是实体
     * @param object
     * @return
     */
    private static boolean isEntity(Object object)
    {
        if(object instanceof String  )
        {
            return false;
        }
        if(object instanceof Integer  )
        {
            return false;
        }
        if(object instanceof Long  )
        {
            return false;
        }
        if(object instanceof java.math.BigDecimal  )
        {
            return false;
        }
        if(object instanceof Date  )
        {
            return false;
        }
        if(object instanceof java.util.Collection )
        {
            return false;
        }
        return true;

    }
}

UploadUtils.java

/**
 * 文件上传的工具类
 * @author Administrator
 *
 */
public class UploadUtils {
    /**
     * 传入文件的名称,返回的唯一的名称
     * 例如:a,jpg 返回xdjfgdhjksda.jsp
     * @param filename
     * @return
     */
    public static String getUUIDName(String filename){
        //先查找
        int index = filename.lastIndexOf(".");
        //截取
        String lastname = filename.substring(index, filename.length());

        //唯一字符串
        String uuid = UUID.randomUUID().toString().replace("-", "");
        System.out.println(filename);
        return uuid+lastname;
    }
    public static void main(String[] args) {
        String filename = "a.jpg";
        String uuid = getUUIDName(filename);
        System.out.println(uuid);
    }
}

CustomerAction

public class CustomerAction extends ActionSupport implements
        ModelDriven<Customer> {

    private static final long serialVersionUID = 1L;
    private Customer customer = new Customer();

    @Override
    public Customer getModel() {
        return customer;
    }

    private CustomerService customerService;

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    /**
     * 初始化到添加页面
     * 
     * @Title: initAdd
     * @return String
     * @author lvc
     * @since 2018年12月5日 V 1.0
     */
    public String initAdd() {
        return "add";

    }

    /**
     * 文件的上传 需要在CustomerAction中定义成员的属性,命名是有规范的 private File upload; // 表示要上传的文件
     * private String uoloadFileName; // 表示上传文件的名称(没有中文乱码) private String
     * uploadContentType // 表示上传文件的MIME类型 提供set方法,拦截器就注入值了
     * 
     */
    private File upload;
    private String uploadFileName;
    private String uploadContentType;

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    /**
     * 添加客户
     * 
     * @Title: add
     * @return String
     * @author lvc
     * @throws IOException
     * @since 2018年11月30日 V 1.0
     */
    public String add() throws IOException {
        // 做文件的上传,说明用户选择了上传的文件了
        if (uploadFileName != null) {
            // 打印
            System.out.println("文件类型:" + uploadContentType);
            // 把文件的名称处理一下
            String uuidname = UploadUtils.getUUIDName(uploadFileName);
            // 把文件上传到D:\\develop_tools\\apache-tomcat-7.0.92\\webapps\\upload\\
            String path = "D:\\develop_tools\\apache-tomcat-7.0.92\\webapps\\upload\\";
            // 创建file对象
            File file = new File(path + uuidname);
            // 简单方式
            FileUtils.copyFile(upload, file);

            // 把上传的文件的路径,保存到客户表中
            customer.setFilePath(path + uuidname);
        }
        if (customer.getCust_name() != null
                && !customer.getCust_name().trim().isEmpty()) {
            customerService.add(customer);
            return "save";
        } else {
            return "add";
        }
    }

    // 属性驱动的方式
    // 当前页,默认值就是1
    private Integer pageCode = 1;

    public void setPageCode(Integer pageCode) {
        if (pageCode == null) {
            pageCode = 1;
        }
        this.pageCode = pageCode;
    }

    // 每页显示的数据的条数
    private Integer pageSize = 5;

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 分页的查询方法
     * 
     * @return
     */
    public String findAll() {
        // 调用service业务层
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);

        String cust_name = customer.getCust_name();
        if (cust_name != null && !cust_name.trim().isEmpty()) {
            // 说明客户的名称输入值了
            criteria.add(Restrictions.like("cust_name", "%" + cust_name + "%"));
        }
        // 拼接客户的级别
        Dict level = customer.getLevel();
        if (level != null && !level.getDict_id().trim().isEmpty()) {
            // 说明客户肯定选择了一个级别
            criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
        }

        // 拼接客户的来源
        Dict source = customer.getSource();
        if (source != null && !source.getDict_id().trim().isEmpty()) {
            // 说明客户肯定选择了一个级别
            criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
        }
        // 查询
        PageBean<Customer> page = customerService.findAll(pageCode, pageSize,
                criteria);
        // 压栈
        ValueStack vs = ActionContext.getContext().getValueStack();
        // 栈顶是map<"page",page对象>
        vs.set("page", page);
        return "page";
    }

    /**
     * 删除客户
     * 
     * @Title: delete
     * @return String
     * @author lvc
     * @since 2018年11月30日 V 1.0
     */
    public String delete() {
        System.out.println("WEB层,删除客户...");
        customer = customerService.findById(customer.getCust_id());
        // 获取上传文件路径
        String path = customer.getFilePath();
        // 先删除客户
        customerService.delete(customer);
        // 再删除文件
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        return "delete";
    }

    /**
     * 加载客户信息跳转到修改页面
     * 
     * @Title: preEdit
     * @return String
     * @author lvc
     * @since 2018年12月5日 V 1.0
     */
    public String preEdit() {
        // 默认customer压栈的了,Action默认压栈,model是Action类的书写 getModel(返回customer对象)
        customer = customerService.findById(customer.getCust_id());
        System.out.println(customer);
        return "initUpdate";
    }

    /**
     * 更新客户信息
     * 
     * @Title: update
     * @return String
     * @author lvc
     * @throws IOException
     * @since 2018年12月5日 V 1.0
     */
    public String update() throws IOException {
        // 判断说明客户上传了新图片
        if (uploadFileName != null) {
            // 先删除旧照片
            String oldFilePath = customer.getFilePath();
            if (oldFilePath != null && !oldFilePath.trim().isEmpty()) {
                File file = new File(oldFilePath);
                file.delete();
            }
        }
        // 上传新图片
        String uuidname = UploadUtils.getUUIDName(uploadFileName);
        // 把文件上传到D:\\develop_tools\\apache-tomcat-7.0.92\\webapps\\upload\\
        String path = "D:\\develop_tools\\apache-tomcat-7.0.92\\webapps\\upload\\";
        // 创建file对象
        File file = new File(path + uuidname);
        // 简单方式
        FileUtils.copyFile(upload, file);
        // 把新图片路径保存到数据库
        customer.setFilePath(path + uuidname);
        customerService.update(customer);
        return "update";
    }
}
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script>
<SCRIPT language=javascript>
	function to_page(page) {
		if (page) {
			$("#page").val(page);
		}
		document.customerForm.submit();

	}
	// 页面的加载
	$(function() {
		// 发送ajax的请求
		var url = "${ pageContext.request.contextPath }/dict_findByCode.action";
		var param = {
			"dict_type_code" : "006"
		};
		$.post(url, param, function(data) {
			// 遍历
			$(data).each(
					function(i, n) {
						// 先获取值栈中的值,使用EL表达式
						var vsId = "${model.level.dict_id}";
						// 值栈中的id值和遍历的id值相同,让被选中
						if (vsId == n.dict_id) {
							// JQ的DOM操作
							$("#levelId").append(
									"<option value='"+n.dict_id+"' selected>"
											+ n.dict_item_name + "</option>");
						} else {
							$("#levelId").append(
									"<option value='"+n.dict_id+"'>"
											+ n.dict_item_name + "</option>");
						}
					});
		}, "json");

		// 获取来源
		var param = {
			"dict_type_code" : "002"
		};
		$.post(url, param, function(data) {
			// 遍历
			$(data).each(
					function(i, n) {
						var vsId = "${model.source.dict_id}";
						if (vsId == n.dict_id) {
							// JQ的DOM操作
							$("#sourceId").append(
									"<option value='"+n.dict_id+"' selected>"
											+ n.dict_item_name + "</option>");
						} else {
							$("#sourceId").append(
									"<option value='"+n.dict_id+"'>"
											+ n.dict_item_name + "</option>");
						}
					});
		}, "json");
	});
</SCRIPT>

<META content="MSHTML 6.00.2900.3492" name=GENERATOR>
</HEAD>
<BODY>
	<FORM id="customerForm" name="customerForm"
		action="${pageContext.request.contextPath }/customer_findAll.action"
		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>
													<TD>客户名称:</TD>
													<TD><INPUT class=textbox id=sChannel2
														style="WIDTH: 80px" maxLength=50 name="cust_name"
														value="${ model.cust_name }"></TD>

													<td>客户级别</td>
													<td><select name="level.dict_id" id="levelId">
															<option value="">--请选择--</option>
													</select></td>

													<td>客户来源</td>
													<td><select name="source.dict_id" id="sourceId">
															<option value="">--请选择--</option>
													</select></td>
													<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>
												<c:forEach items="${page.beanList }" var="customer">
													<TR
														style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
														<TD>${customer.cust_name }</TD>
														<TD>${customer.level.dict_item_name }</TD>
														<TD>${customer.source.dict_item_name }</TD>
														<TD>${customer.cust_linkman }</TD>
														<TD>${customer.cust_phone }</TD>
														<TD>${customer.cust_mobile }</TD>
														<TD><a
															href="${pageContext.request.contextPath }/customer_preEdit.action?cust_id=${customer.cust_id}">修改</a>
															&nbsp;&nbsp; <a
															href="${pageContext.request.contextPath }/customer_delete.action?cust_id=${customer.cust_id}"
															onclick="return window.confirm('确认删除吗?')">删除</a></TD>
													</TR>

												</c:forEach>

											</TBODY>
										</TABLE>
									</TD>
								</TR>

								<TR>
									<TD><SPAN id=pagelink>
											<DIV
												style="LINE-HEIGHT: 20px; HEIGHT: 20px; TEXT-ALIGN: right">
												共[<B>${page.totalCount}</B>]条记录,共[<B>${page.totalPage}</B>]页
												,每页显示 <select name="pageSize">

													<option value="2"
														<c:if test="${page.pageSize==2 }">selected</c:if>>2</option>
													<option value="5"
														<c:if test="${page.pageSize==5 }">selected</c:if>>5</option>

												</select> 条
												<c:if test="${page.pageCode > 1 }">
												[<A href="javascript:to_page(${page.pageCode-1})">前一页</A>]
												</c:if>
												<B>${page.pageCode}</B>
												<c:if test="${page.pageCode < page.totalPage }">
												[<A href="javascript:to_page(${page.pageCode+1})">后一页</A>] 
												</c:if>
												到 <input type="text" size="3" id="page" name="pageCode" />
												页 <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>

猜你喜欢

转载自blog.csdn.net/Entermomem/article/details/84839176