easyUI之门户书籍类别查询

本文介绍了Java Web开发中动态显示数据表格的两种方法:一种是通过Ajax请求逐条查询,另一种是使用VO类进行连表查询以提高性能。详细展示了实体类、DAO方法、子控制器和JSP页面的实现,并讨论了图片上传和门户首页书籍类别显示的功能。同时,文章还涉及到了前端JS交互和后端服务的配合,以及图片上传的处理流程。
摘要由CSDN通过智能技术生成

一、1.动态显示数据表格列数字对应内容(vo类&性能优化)

1.第一种方法:

  根据id查询类别,使用ajax请求这样做的弊端:

 ①.同步异步问题

 ②.性能差(每条数据都要跑一次数据库)

 ③.json字符串转json对象问题

	public String load(HttpServletRequest req, HttpServletResponse resp) {
			try {
				Category c = categoryDao.list(category,null).get(0);
				ResponseUtil.writeJson(resp, c);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

2.第二种方法使用vo类(连表查询): 

①实体类

package vo;
 
import java.util.Date;
 
import com.fasterxml.jackson.annotation.JsonFormat;
 
/**
 * VO:view object 视图模型对象
 * 在同一个页面显示多张表的数据
 * @author zjjt
 *
 */
public class BookVo {
	private long id;
	private String name;
	private String pinyin;
	private long cid;
	private String author;
	private float price;
	private String image;
	private String publishing;
	private String description;
	private int state;
	@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
	private Date deployTime;
	private int sales;
	private String cname;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPinyin() {
		return pinyin;
	}
	public void setPinyin(String pinyin) {
		this.pinyin = pinyin;
	}
	public long getCid() {
		return cid;
	}
	public void setCid(long cid) {
		this.cid = cid;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getPublishing() {
		return publishing;
	}
	public void setPublishing(String publishing) {
		this.publishing = publishing;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public Date getDeployTime() {
		return deployTime;
	}
	public void setDeployTime(Date deployTime) {
		this.deployTime = deployTime;
	}
	public int getSales() {
		return sales;
	}
	public void setSales(int sales) {
		this.sales = sales;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public BookVo() {
		// TODO Auto-generated constructor stub
	}
	
	public BookVo(long id, String name, String pinyin, long cid, String author, float price, String image,
			String publishing, String description, int state, Date deployTime, int sales, String cname) {
		super();
		this.id = id;
		this.name = name;
		this.pinyin = pinyin;
		this.cid = cid;
		this.author = author;
		this.price = price;
		this.image = image;
		this.publishing = publishing;
		this.description = description;
		this.state = state;
		this.deployTime = deployTime;
		this.sales = sales;
		this.cname = cname;
	}
	@Override
	public String toString() {
		return "BookVo [id=" + id + ", name=" + name + ", pinyin=" + pinyin + ", cid=" + cid + ", author=" + author
				+ ", price=" + price + ", image=" + image + ", publishing=" + publishing + ", description="
				+ description + ", state=" + state + ", deployTime=" + deployTime + ", sales=" + sales + ", cname="
				+ cname + "]";
	}
	
}

②.dao方法

package com.zking.dao;
 
import java.util.List;
 
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
 
import vo.BookVo;
 
public class BookVoDao extends BaseDao<BookVo>{
	
 
	public List<BookVo> list(BookVo bookVo, PageBean pageBean) throws Exception {
		// TODO Auto-generated method stub
		String sql="select b.*,c.name as cname from t_easyui_book b,t_easyui_category c where b.cid=c.id";
		String name = bookVo.getName();
		int state = bookVo.getState();
		if(StringUtils.isNotBlank(name)) {
			sql +=" and name like '"+name+"'";
		}
		if(state !=0) {
			sql +=" and state ="+state;
		}
		return super.executeQuery(sql, BookVo.class, pageBean);
	}
 
}

③.BookVoAction子控制器

package com.zking.web;
 
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
import com.zking.util.R;
import com.zking.util.ResponseUtil;
import com.zking.dao.BookVoDao;
import com.zKing.entity.Book;
 
import vo.BookVo;
 
public class BookVoAction extends ActionSupport implements ModelDriver<BookVo> {
 
	private BookVo bookVo=new BookVo();
	private BookVoDao  bookVoDao=new BookVoDao(); 
	@Override
	public BookVo getModel() {
		// TODO Auto-generated method stub
		return bookVo;
	}
	
	public String list(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		PageBean pageBean= new PageBean();
		pageBean.setRequest(req);
		try {
              List<BookVo> list = bookVoDao.list(bookVo, pageBean);
			ResponseUtil.writeJson(resp, new R().data("total",pageBean.getTotal()).data("rows", list));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

④.jsp代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>未上架书籍</title>
    <link rel="stylesheet" type="text/css"
          href="${pageContext.request.contextPath}/static/js/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/easyui/themes/icon.css">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/static/js/easyui/jquery.easyui.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/main.js"></script>
</head>
<body>
 
<%--未上架书籍--%>
<table id="dg" style="style=" width:400px;height:200px;
"></table>
 
<div id="tb">
    <input class="easyui-textbox" id="name" name="name" style="width:20%;padding-left: 10px" data-options="label:'书名:',required:true">
    <a id="btn-search" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">搜索</a>
</div>
 
<!-- 弹出框提交表单所用 -->
<div id="dd" class="easyui-dialog" title="编辑窗体" style="width:600px;height:450px;"
     data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#bb'">
 
    <form id="ff" action="${pageContext.request.contextPath}/book.action?methodName=edit" method="post">
        <div style="margin-bottom:20px">
            <input class="easyui-textbox" name="name" style="width:100%" data-options="label:'书名:',required:true">
        </div>
        <div style="margin-bottom:20px">
            <input id="cid" name="cid" value="" label="类别" >
            <%--<select class="easyui-combobox" name="cid" label="类别" style="width:100%">--%>
                <%--<option value="1">文艺</option>--%>
                <%--<option value="2">小说</option>--%>
                <%--<option value="3">青春</option>--%>
            <%--</select>--%>
        </div>
        <div style="margin-bottom:20px">
            <input class="easyui-textbox" name="author" style="width:100%" data-options="label:'作者:',required:true">
        </div>
        <div style="margin-bottom:20px">
            <input class="easyui-textbox" name="price" style="width:100%"
                   data-options="label:'价格:',required:true">
        </div>
        <div style="margin-bottom:20px">
            <input class="easyui-textbox" name="publishing" style="width:100%"
                   data-options="label:'出版社:',required:true">
        </div>
        <div style="margin-bottom:20px">
            <input class="easyui-textbox" name="description" style="width:100%;height:60px"
                   data-options="label:'简介:',required:true">
        </div>
        <%--默认未上架--%>
        <input type="hidden" name="state" value="">
        <%--默认起始销量为0--%>
        <input type="hidden" name="sales" value="">
        <input type="hidden" name="id" value="">
        <input type="hidden" name="image" value="">
    </form>
 
    <div style="text-align:center;padding:5px 0">
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">Submit</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">Clear</a>
    </div>
 
</div>
 
<!-- 图片上传 -->
<div id="dd2" class="easyui-dialog" title="书籍图标上传" style="width:600px;height:450px;"
     data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#bb'">
 
    <form id="ff2" action="" method="post" enctype="multipart/form-data">
        <div style="margin-bottom:20px">
            <input type="file" name="file">
        </div>
    </form>
 
    <div style="text-align:center;padding:5px 0">
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm2()" style="width:80px">Submit</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">Clear</a>
    </div>
 
</div>
 
</body>
<script>
    function shangjia() {
        $.messager.confirm('确认','您确认想要上架此书籍吗?',function(r){
            if (r){
                var row = $('#dg').datagrid('getSelected');
                if (row){
                    $.ajax({
                        url:'${pageContext.request.contextPath}/book.action?methodName=editStatus&state=2&id=' + row.id,
                        success:function (data) {
                            
                        }
                    })
                } 
            }
        });
 
    }
 
    //修改
    function edit() {
        $('#cid').combobox({
            url:'${pageContext.request.contextPath}/category.action?methodName=combobox',
            valueField:'id',
            textField:'name'
        });
 
        var row = $('#dg').datagrid('getSelected');
        if (row) {
            $('#ff').form('load', row);
            $('#dd').dialog('open');
        }
    }
 
    //提交编辑信息的表单
    function submitForm() {
        $('#ff').form('submit',{
            success: function (param) {
                $('#dd').dialog('close');
                $('#dg').datagrid('reload');
                $('#ff').form('clear');
            }
        });
    }
 
    function clearForm() {
        $('#ff').form('clear');
    }
 
    //图片上传
    function upload() {
        $('#dd2').dialog('open');
    }
 
    //图片上传表单提交
    function submitForm2() {
        var row = $('#dg').datagrid('getSelected');
        console.log(row);
        // if (row) {
        //     $('#ff2').attr("action", $('#ff2').attr("action") + "&id=" + row.id);
        // }
        $('#ff2').form('submit', {
            url: '${pageContext.request.contextPath}/book.action?methodName=upload&id=' + row.id,
            success: function (param) {
            	alert(param)
                $('#dd2').dialog('close');
                $('#dg').datagrid('reload');
                $('#ff2').form('clear');
            }
        })
    }
 
    $(function () {
 
        $("#btn-search").click(function () {
            $('#dg').datagrid('load', {
                name: $("#name").val()
            });
        });
        $('#dg').datagrid({
            url: '${pageContext.request.contextPath}/bookVo.action?methodName=list&&state=1',
            fit: true,
            fitColumns: true,
            pagination: true,
            singleSelect: true,
            toolbar:'#tb',
            columns: [[
                // {field:'id',title:'id',width:100},
                {field: 'id', title: '书籍名称', hidden: true},
                {field: 'name', title: '书籍名称', width: 50},
                {field: 'pinyin', title: '拼音', width: 50},
                {field: 'cname', title: '连表类别', width: 50},
                {field: 'author', title: '作者', width: 50},
                // {field:'price',title:'价格',width:100},
                {
                    field: 'image', title: '图片路径', width: 100, formatter: function (value, row, index) {
                        return '<img style="width:80px;height: 60px;" src="' + row.image + '"></img>';
                    }
                },
                {field: 'publishing', title: '出版社', width: 50},
                // {field:'desc',title:'描述',width:100},
                // {field:'state',title:'书籍状态',width:100},
                {field: 'sales', title: '销量', width: 50},
                {field: 'deployTime', title: '上架时间', width: 50, align: 'right'},
                {
                    field: 'xxxx', title: '操作', width: 100, formatter: function (value, row, index) {
                        return '<a href="#" onclick="upload()">图片上传</a>&nbsp;&nbsp;' +
                            '<a href="#" onclick="shangjia()">上架</a>&nbsp;&nbsp;' +
                            '<a href="#" onclick="edit();">修改</a>';
                    }
                }
            ]]
        });
 
    })
 
 
</script>
</html>

⑤.配置mvc文件

</action>
		<action path="/bookVo" type="com.zking.web.BookVoAction">
	</action>

二.门户首页书籍类别显示

①.实体类

package com.zking.entity;
 
public class Category {
	private long id;
	private String name;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Category() {
		// TODO Auto-generated constructor stub
	}
	public Category(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Category [id=" + id + ", name=" + name + "]";
	}
	
 
}

②.index.jsp

<input type="hidden" id="ctx" value="${pageContext.request.contextPath}">

③.index.js

$(function(){
	$.ajax({
		url:$("#ctx").val()+"/category.action?methodName=combobox",
		success:function(data){
			//alert(data)
			var jsonArr=eval("("+data+")");
			var html='';
			for(var i in jsonArr){
				html+='<li class="list-group-item" >'+jsonArr[i].name+'</li>';
			}
			$(".list-group").append(html);
		}
	})
	
})

④.dao方法

package com.zking.dao;
 
import java.util.List;
 
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zy.entity.Category;
 
public class CategoryDao extends BaseDao<Category> {
	
	
	public List<Category> list(Category category, PageBean pageBean) throws Exception {
		// TODO Auto-generated method stub
		String sql="select * from t_easyui_category where 1=1";
		long id = category.getId();
		if(id!=0) {
			sql +=" and id="+id;
		}
		return super.executeQuery(sql, Category.class, pageBean);
	}
 
}

⑤.子控制器

public String combobox(HttpServletRequest req, HttpServletResponse resp) {
			try {
				List<Category> list = categoryDao.list(category,null);
				ResponseUtil.writeJson(resp, list);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

⑥.配置mvc文件

<action path="/category" type="com.zking.web.CategoryAction">
	
	</action>

⑦.效果:

  2.点击左侧类别,右侧显示相对应的数据

1.给类别添加点击事件,将类别id传过去

  2.前台js代码

<script type="text/javascript">
    function searchByType(cid){
        location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
    };
</script>

3.bookAction

	public String findByType(HttpServletRequest req, HttpServletResponse resp) {
			try {
				PageBean pageBean=new PageBean();
				pageBean.setRequest(req);
				List<Book> lists = bookDao.list(book, pageBean);
				req.setAttribute("books", lists);
				req.setAttribute("pageBean",pageBean);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "findBook";
		}

4.配置mvc

 
	<action path="/book" type="com.zking.web.BookAction">
	<forward name="findBook" path="/fg/findBook.jsp" redirect="false" />
	</action>

5.效果:

 三.图片上传

1.前台js代码

  <script>
function submitForm2() {
        var row = $('#dg').datagrid('getSelected');
        console.log(row);
        // if (row) {
        //     $('#ff2').attr("action", $('#ff2').attr("action") + "&id=" + row.id);
        // }
        $('#ff2').form('submit', {
            url: '${pageContext.request.contextPath}/book.action?methodName=upload&id=' + row.id,
            success: function (param) {
            	alert(param)
                $('#dd2').dialog('close');
                $('#dg').datagrid('reload');
                $('#ff2').form('clear');
            }
        })
    }
</script>

2.bookAction

public String upload(HttpServletRequest request, HttpServletResponse response) {
			 try {
		            FileItemFactory factory = new DiskFileItemFactory();
		            ServletFileUpload upload = new ServletFileUpload(factory);
		            List<FileItem> items = upload.parseRequest(request);
		            Iterator<FileItem> itr = items.iterator();
 
		            HttpSession session = request.getSession();
 
		            while (itr.hasNext()) {
		                FileItem item = (FileItem) itr.next();
		                if (item.isFormField()) {
		                    System.out.println("普通字段处理");
		                    book.setId(Long.valueOf(request.getParameter("id")));
		                } else if (!"".equals(item.getName())) {
		                	// 图片格式/年/月/日
		                    String imageName = DateUtil.getCurrentDateStr();
		                    // 存入数据的的数据,以及浏览器访问图片的映射地址
		                    String serverDir = PropertiesUtil.getValue("serverDir");
		                    // 图片真实的存放位置
		                    String diskDir = PropertiesUtil.getValue("diskDir");
		                    // 图片的后缀名
		                    String subfix = item.getName().split("\\.")[1];
 
		                    book.setImage(serverDir + imageName + "." + subfix);
		                    item.write(new File(diskDir + imageName + "." + subfix));
		                  this.bookDao.editImgUrl(book);
		                    ResponseUtil.writeJson(response, 1);
		                }
		            }
 
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        return null;
		}

3.bookDao

 
	public void  editImgUrl(Book t) throws Exception{
	
		super.executeUpdate("update t_easyui_book set image=? where id=?", t, new String[] {"image","id"});
	}

4.工具类

DateUtil

package com.zking.util;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateUtil {
 
	public static String getCurrentDateStr() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHss");
		
		return sdf.format(new Date());
	}
	
 
}

PropertiesUtil

package com.zking.util;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropertiesUtil {
 
	public static String getValue(String key) throws IOException {
		Properties p=new Properties();
		InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
		p.load(in);
		return p.getProperty(key);
	}
}

5 .添加resource.properties文件

diskDir=E:/temp/2021/mvc/upload/
serverDir=/uploadImages/

6.修改服务Servers中的server.xml

7.效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值