hooyantsing's Blog

第76次课程-J2EE_项目案例

字数统计: 2.5k阅读时长: 13 min
2019/11/03

源辰76班

第76次课程

2019.11.03

内容

J2EE_项目案例[廖彦]

1.格式化

95f46ae4ba6fd6175d95dac2411dd713.png

6b505d7ef3bcd8998f375a9a2c2358d8.png

1
2
3
4
5
6
7
8
9
10
11
<script>
    function fmtHot(value,row,index){
        return value == 0 ? "非热卖" : "热卖";
    }
    function fmtImage(value,row,index){
        return "<img src='../" + value +"'  height='40px'>";
    }
</script>

<th  data-options="field:'image',width:100,formatter:fmtImage">图片</th>
<th  data-options="field:'is_hot',width:100,formatter:fmtHot">热卖标志</th>

2.代码仓库

product.jsp

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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01  Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=utf-8">
<title>商品管理</title>
    <!-- 相对路径 -->
    <link rel="stylesheet" type="text/css"  href="../js/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css"  href="../js/easyui/themes/icon.css">
    <!-- 绝对路径 -->
    <script type="text/javascript"  src="/191026_Servlet/js/easyui/jquery.min.js"></script>
    <script type="text/javascript"  src="/191026_Servlet/js/easyui/jquery.easyui.min.js"></script>
    <!-- 国际化js文件 -->
    <!-- 改进绝对路径:工程名可以任意变化 -->
    <script type="text/javascript"  src="<%=application.getContextPath()  %>/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
function edit(){
    // 获取表格当前选中的行  row 就是  Product  实体对象   ===》 json 对象
    var row =  $("#dg").datagrid("getSelected");
    if(row == null){
       $.messager.alert('系统提示','请选择要编辑的服装','error');
       return;
    }
    $('#dlg').dialog('open');
    
    // 清空表单中的值
    $("#editForm").form('clear');
    
    // 补丁
    $("#op").val("save");
    $("#productImage").val(row.image);
    
    // 将改行数据填写到表单控件中
    $("#editForm").form('load',row);
    
}
function add(){
    // 获取表格当前选中的行  row 就是  Product  实体对象   ===》 json 对象
    $('#dlg').dialog('open');
    // 清空表单中的值
    $("#editForm").form('clear');
    // 补丁
    $("#op").val("save");
    $("#productImage").val("");
}
function save(){
    $('#editForm').form('submit', {
       //  get 请求会删除 url 地址里面的请求参数
       url: "../product.s",
       success: function(json){
           eval("var result = " + json);
           if(result.code == 1){
               // 冒泡提示信息
               $.messager.show({
                  title:'系统提示',
                  msg:result.msg,
                  timeout:3000,
                  showType:'slide'
               });
               $('#dlg').dialog('close');
               // 表格重新加载数据(查询)
               $("#dg").datagrid("reload");
           } else {
               $.messager.alert('系统提示',result.msg,'error');
           }
       }
    });
    
}
function selectCsid(category){
    $('#csid').combobox('reload','../categorysecond.s?op=queryByCid&cid=' + category.cid );
}
function fmtHot(value,row,index){
    return value == 0 ? "非热卖" : "热卖";
}
function fmtImage(value,row,index){
    return "<img src='../" + value +"'  height='40px'>";
}
//easyui 的表单提交不能上传文件
function save(){
    // 创建表单对象(实现文件上传)  传入 html  表单元素
    var formData = new  FormData($('#editForm')[0]);
    $.ajax({
        url:'../product.s?op=save',
        type:'post',
        data: formData,
        contentType: false,
        processData: false,
        success:function(result){
            //eval("var result = " + json);
           if(result.code == 1){
               // 冒泡提示信息
               $.messager.show({
                  title:'系统提示',
                  msg:result.msg,
                  timeout:3000,
                  showType:'slide'
               });
               $('#dlg').dialog('close');
               // 表格重新加载数据(查询)
               $("#dg").datagrid("reload");
           } else {
               $.messager.alert('系统提示',result.msg,'error');
           }
        }
    })
}
</script>
</head>
<body>
<table id="dg" class="easyui-datagrid"  title="DataGrid Complex Toolbar"
       data-options="
           fit:true,
           rownumbers:true,
           singleSelect:true,
           url:'../product.s?op=query',
           method:'get',
           toolbar:'#tb'">
    <thead>
       <tr>
           <th  data-options="field:'pid',width:80">ID</th>
           <th  data-options="field:'pname',width:100">名称</th>
           <th  data-options="field:'shop_price',width:100">商场价</th>
           <th  data-options="field:'image',width:100,formatter:fmtImage">图片</th>
           <th  data-options="field:'pdate',width:100">日期</th>
           <th  data-options="field:'is_hot',width:100,formatter:fmtHot">热卖标志</th>
       </tr>
    </thead>
</table>
<div id="tb"  style="padding:5px;height:auto">
    <div style="margin-bottom:5px">
       <a href="#"  class="easyui-linkbutton" iconCls="icon-add"  plain="true"></a>
       <a href="#"  class="easyui-linkbutton"  iconCls="icon-edit" plain="true"></a>
       <a href="#"  class="easyui-linkbutton"  iconCls="icon-save" plain="true"></a>
       <a href="#"  class="easyui-linkbutton" iconCls="icon-cut"  plain="true"></a>
       <a href="#"  class="easyui-linkbutton"  iconCls="icon-remove" plain="true"></a>
    </div>
    <div>
       Date From: <input  class="easyui-datebox" style="width:80px">
       To: <input class="easyui-datebox"  style="width:80px">
       Language:
       <select class="easyui-combobox"  panelHeight="auto" style="width:100px">
           <option  value="java">Java</option>
           <option value="c">C</option>
           <option  value="basic">Basic</option>
           <option  value="perl">Perl</option>
           <option  value="python">Python</option>
       </select>
       <a href="#"  class="easyui-linkbutton"  iconCls="icon-search">Search</a>
       <a href="javascript:void(0)"  class="easyui-linkbutton"  onclick="edit()">编辑</a>
       <a href="javascript:void(0)"  class="easyui-linkbutton" onclick="add()">新增</a>
    </div>
</div>
<!-- 对话框:商品信息编辑 -->
<div id="dlg" class="easyui-dialog"  title="Basic Dialog"
    data-options="
       iconCls:'icon-save',
       closed:true,
       buttons: [{
                  text:'保存',
                  iconCls:'icon-ok',
                  handler:function(){
                      save();
                  }
               },{
                  text:'放弃',
                  iconCls:'icon-cancel',
                  handler:function(){
                      $('#dlg').dialog('close');
                  }
               }]
       "
    style="width:400px;height:400px;padding:10px">
    <form action="????" id="editForm">
    <input id="op" name="op" value="save"  type="hidden">
    <input id="productImage" name="image"  type="hidden">
    <input class="easyui-textbox" name="pid"  style="width:300px"
       data-options="label:'商品ID:'">
    <input class="easyui-textbox"  name="pname" style="width:300px"
       data-options="label:'名称:'">
    <input class="easyui-textbox"  name="shop_price" style="width:300px"  type="number"
       data-options="label:'商城价:'">
    <input class="easyui-radiobutton"  name="is_hot" value="1" label="热卖:">
    <input class="easyui-radiobutton"  name="is_hot" value="0" label="非热卖:">

    <!-- 下拉框 -->
    <!--
       data-options
       label:'显示在框前字符串',
       url:'从远程加载列表数据的 URL',
       valueField:'绑定到该组合框(ComboBox)的 value 上的基础数据的名称',
       onSelect:'当用户选择一个列表项时触发'
     -->
    <input class="easyui-combobox"  name="cid" style="width:300px"
       data-options="label:'主类别:',
           url:'../category.s?op=queryAll',
           textField:'cname',
           valueField:'cid',
           onSelect:selectCsid">
    <input id="csid" class="easyui-combobox"  name="csid" style="width:300px"
       data-options="label:'子类别:',
           url:'../categorysecond.s?op=queryByCid',
           textField:'csname',
           valueField:'csid'
       ">
       
    <input class="easyui-textbox"  name="pdesc" style="width:300px"  type="number"
       data-options="label:'描述:',multiline:true">
       
    <input class="easyui-filebox"  style="width:300px" name="imageFile"
       data-options="label:'上传图片:'">
    </form>
</div>
<!--
    11.01 作业:实现商品的增删改查操作
    1、实现商品信息的修改,保存至数据库
    2、实现商品信息的新增,添加至数据库
    3、实现商品删除
    4、请使用 ajax 方式进行以上操作
    5、成功完成之后,请刷新表格(重新查询,请查api)
-->
</body>
</html>

ProductServlet.java

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
package com.yc.damai.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.google.gson.Gson;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.yc.damai.bean.Product;
import com.yc.damai.bean.Result;
import com.yc.damai.biz.BizException;
import com.yc.damai.biz.ProductBiz;

@WebServlet("/product.s")
public class ProductServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    private ProductBiz biz = new ProductBiz();

    public void query(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        List<Product> list = biz.query();
        // 引出out.print
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        // 动态数组转成json格式
        out.print(gson.toJson(list));
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws IOException,
            IllegalAccessException, InvocationTargetException, SmartUploadException, ServletException {
        // 创建文件上传对象
        SmartUpload su = new SmartUpload();
        // 初始化,传入页面上下文对象
        su.initialize(getServletConfig(), request, response);
        // 设置上传的配置信息
        // 限定文件名后缀
        su.setAllowedFilesList("jpg,png,gif,bmp");
        // 限定大小
        su.setMaxFileSize(1024 * 1024 * 10);
        // 执行上传
        su.upload();

        //判断是否有上传文件
        String webPath = null;
        if(su.getFiles().getSize()>0) {
            Files files = su.getFiles();
            String filename = files.getFile(0).getFileName();
    
            // 使用application(应用上下文对象) web路径 转换成 磁盘路径
            // getServletContext() === application
            String diskPath = getServletContext().getRealPath("/products/upload");
            files.getFile(0).saveAs(diskPath + "/" + filename);
            webPath = "products/upload/" + filename;
        }
        Product p = new Product();

        // smartupload 对请求对象进行了封装
        HashMap<String, String> paramMap = new HashMap<>();
        @SuppressWarnings("unchecked")
        Enumeration<String> es = su.getRequest().getParameterNames();
        while (es.hasMoreElements()) {
            String paramName = es.nextElement();
            String paramValue = su.getRequest().getParameter(paramName);
            /**
          * smartupload 会对表单数据使用gbk格式编码,当前工程是utf-8编码,要手动转
          * 不过,即使是手动转了也还是会出现少量乱码,是 gbk 与 utf-8 两个字符集的兼容性问题,小问题忽略
          * 另外,smartupload 提供的 setCharset 方法(设置字符集方法)执行会直接报错,应该是bug
          */
            paramMap.put(paramName, new String(paramValue.getBytes("gbk"),"utf-8"));
        }

        BeanUtils.populate(p, paramMap);
        if(webPath!=null) {
            p.setImage(webPath);
        }
        Result result;
        try {
            biz.save(p);
            result = Result.success("保存商品成功!");
        } catch (BizException e) {
            e.printStackTrace();
            result = Result.success(e.getMessage());
        }
        Gson gson = new Gson();
        String json = gson.toJson(result);
        // 返回json格式数据
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(json);
    }
}
CATALOG