IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> EasyUI项目之门户书籍类别查询+图片上传 -> 正文阅读

[JavaScript知识库]EasyUI项目之门户书籍类别查询+图片上传

目标功能:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
目标:

1,门户书籍类别的显示

2,点击类别跳转到对象的类别界面

3,后台图片上传功能

一,门户书籍类别的显示

1.1 类别实体类
在这里插入图片描述1.2 CategoryDao


package com.zking.dao;
 
import java.util.List;
 
import com.zking.entity.Category;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
 
public class CategoryDao extends BaseDao<Category>{
 
	//查询类别
	public List<Category> list( Category category, PageBean pageBean) throws Exception {
		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);
	}
	
}

1.3 CategoryAction

package com.zking.web;
 
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.zking.dao.CategoryDao;
import com.zking.entity.Category;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
 
public class CategoryAction extends ActionSupport implements ModelDriver<Category> {
 
	private Category category = new Category();
	private CategoryDao categoryDao = new CategoryDao();
 
	public Category getModel() {
		return category;
	}
 
	// 类别下拉框
	public String combobox(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//		获取下拉框值
		List<Category> list = categoryDao.list(category, null);
		ResponseUtil.writeJson(resp, list);
		return null;
	}
 
}

1.4 配置mvc文件

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

1.5 前端js


$(function(){
	$.ajax({
		url:$("#ctx").val()+"/category.action?methodName=combobox",
		success:function(data){
            //eval();可将json数组转换为json对象
            //jsonArr[i].id 为每个类别的id
	    	var jsonArr = eval("("+data+")");
	    	var html = '';
	    	for(var i in jsonArr){
	    		html += '<li class="list-group-item" οnclick="searchByType('+jsonArr[i].id+')">'+jsonArr[i].name+'</li>';
	    	}
	    	$(".list-group").append(html);
		}
	});
	
})

1.6 门户界面代码


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <meta charset="utf-8">
    <title>网上书城首页</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/css/fg.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/index.js"></script>
</head>
<body class="text-center">
<div class="container">
    <div class="row head">
        <div class="col-md-12">
            <i>
                您好,欢迎来到飞凡网上书店!
            </i>
            <b>
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/login.jsp">登录</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/register.jsp">注册</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/shopping.action?methodName=list">我的购物车</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/">网站首页</a>
            </b>
        </div>
    </div>
    <!-- 横幅搜索栏 start -->
    <div class="row banner">
        <div class="img1"></div>
        <div class="col-md-12">
            <form class="form" action="${pageContext.request.contextPath}/book.action?methodName=findByName" method="post">
                <%--<input type="hidden" name="methodName" value="findByName">--%>
                <input type="text" name="name" value="" id="input" class="search">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>
    <!-- 横幅搜索栏 end -->
    <!-- 页面主体内容 start -->
    <div class="row content">
        <div class="col-md-3 float-left c-left">
            <ul class="list-group">
                <li class="list-group-item">书籍分类</li>
            </ul>
        </div>
        <%--${books}--%>
        <div class="col-md-9 float-right c-right">
            <c:forEach var="b" items="${books}">
                <div class="media">
                    <img style="width: 100px;height: 140px;" src="http://localhost:8080${b.image}" class="align-self-center mr-3" alt="...">
                    <div class="media-body text-left">
                        <p>${b.name}</p>
                        <p>作者:${b.author}</p>
                        <p>价格:${b.price}</p>
                        <p>出版社:${b.publishing}</p>
                        <p>书籍简介:${b.description}</p>
                        <span>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=pay">去结算</a>
							</span>
                    </div>
                </div>
                <hr>
            </c:forEach>
 
            <%--<div class="media">--%>
            <%--<img src="imgs/2.png" class="align-self-center mr-3" alt="...">--%>
            <%--<div class="media-body text-left">--%>
            <%--<p>第一商会</p>--%>
            <%--<p>作者:寒川子</p>--%>
            <%--<p>价格:¥24.80</p>--%>
            <%--<p>出版社:北京联合出版公司</p>--%>
            <%--<p>书籍简介:超级畅销书作家寒川子创作历时三年全新力作!讲述财富与权力“离不开,靠不住”的明暗法则</p>--%>
            <%--<span>--%>
            <%--<button type="button" class="btn btn-danger">加入购物车</button>--%>
            <%--<button type="button" class="btn btn-danger">去结算</button>--%>
            <%--</span>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<hr>--%>
 
            <xl:page pageBean="${pageBean}"></xl:page>
        </div>
    </div>
    <!-- 页面主体内容 end -->
    <!-- 网站版权 start -->
    <div class="row footer">
        <div class="col-md-12">
            Copyright ?2014 飞凡教育,版权所有
        </div>
    </div>
    <!-- 网站版权 end -->
</div>
<script type="text/javascript">
    function searchByType(cid){
        location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
    };
</script>
 
</body>
</html>

效果展示:
在这里插入图片描述

二,点击类别跳转到对象的类别界面

2.1 给左边类别添加点击事件并传递id到前台

<li class="list-group-item" onclick="searchByType('+jsonArr[i].id+')">'+jsonArr[i].name+'</li>';

2.2 BookDao

//  查询
	public List<Book> list(Book book, PageBean pageBean) throws Exception {
		String sql = "select * from t_easyui_book where 1=1 ";
		String name = book.getName();
		int state = book.getState();
		long cid = book.getCid();
		
		if(StringUtils.isNotBlank(name)) {
			sql += " and name like '%"+name+"%'";
		}
		
//		书籍状态
		if(state != 0) {
			sql+=" and state="+state;
		}
		
//		类别
		if(cid != 0) {
			sql+=" and cid="+cid;
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}

2.3 BookAction

  //分类显示页面
	//按照书籍类别查询书籍信息
	//前端:从首页传递类别id到后台
	//后端:通过类别id查询到对应数据集合,到前台遍历(对应前台,不是发生ajax请求,在后台要有返回值)
	public String findByType(HttpServletRequest req, HttpServletResponse resp) throws Exception {
			PageBean pageBean = new PageBean();
			pageBean.setRequest(req);
			List<Book> list = bookDao.list(book, pageBean);
			req.setAttribute("books", list);
			req.setAttribute("pagebean", pageBean);
			return "findBook";
	}

2.4 配置xml文件

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

2.5 前台js代码


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

效果展示:
在这里插入图片描述

三,后台的图片上传

3.1 导入相应jar包
在这里插入图片描述
3.2 BookDao


	//修改图片
	public void editImgUrl(Book book) throws Exception {
		String sql = "update t_easyui_book set image=? where id=?";
		super.executeUpdate(sql, book, new String[] {"image","id"});
	}

3.3 BookAction

//图片上传
	public String upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(req);
        Iterator<FileItem> itr = items.iterator();
 
        HttpSession session = req.getSession();
 
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                System.out.println("普通字段处理");
                book.setId(Long.valueOf(req.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(resp, 1);
            }
        }
        return null;
	}

PropertiesUtil


package com.zking.web;
 
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);
	}
 
}

DateUtil


package com.zking.util;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateUtil {
	//设置时间戳格式
	public static String getCurrentDateStr() {
//		20200909xxxx
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}
	
}

ResponseUtil


package com.zking.util;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateUtil {
	//设置时间戳格式
	public static String getCurrentDateStr() {
//		20200909xxxx
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}
	
}

3.4 到eclipse内部服务器中配置好图片映射和浏览器读取地址
selver.xml
在这里插入图片描述
效果展示:
在这里插入图片描述

四,数据表格列之数字与对应内容的显示优化

方法一:
CategoryDao

package com.zking.dao;
 
import java.util.List;
 
import com.zking.entity.Category;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
 
public class CategoryDao extends BaseDao<Category>{
 
	//查询类别
	public List<Category> list( Category category, PageBean pageBean) throws Exception {
		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);
	}
	
}

CategoryAction


package com.zking.web;
 
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.zking.dao.CategoryDao;
import com.zking.entity.Category;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
 
public class CategoryAction extends ActionSupport implements ModelDriver<Category> {
 
	private Category category = new Category();
	private CategoryDao categoryDao = new CategoryDao();
 
	public Category getModel() {
		return category;
	}
 
	public String load(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//		传递id到后台,只会查出一个类别
		Category c = categoryDao.list(category, null).get(0);
		ResponseUtil.writeJson(resp, c);
		return null;
	}
	
}

前台js代码
在这里插入图片描述
根据id查询,弊端:
1.1、性能差(每条数据都要跑一次数据库)
1.2、同步异步问题
1.3、json字符串转json对象问题

方法二:连表查询

select b.*,c.name as cname from t_easyui_book b,t_easyui_category c where b.cid = c.id

BookVo(将连表查询需要字段写入实体类)

package com.zking.entity;
 
import java.util.Date;
 
import com.fasterxml.jackson.annotation.JsonFormat;
 
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;
	}
 
	@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 + "]";
	}
 
	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;
	}
 
	public BookVo() {
		// TODO Auto-generated constructor stub
	}
 
}

BookVoDao

package com.zking.dao;
 
import java.util.List;
 
import com.zking.entity.BookVo;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
 
public class BookVoDao extends BaseDao<BookVo>{
 
//  查询
	public List<BookVo> list(BookVo bookVo, PageBean pageBean) throws Exception {
		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.dao.BookVoDao;
import com.zking.entity.Book;
import com.zking.entity.BookVo;
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;
 
public class BookVoAction extends ActionSupport implements ModelDriver<BookVo>{
 
	private BookVo bookVo = new BookVo();
	private BookVoDao bookVoDao = new BookVoDao();
	
	public BookVo getModel() {
		return bookVo;
	}
 
	public void list(HttpServletRequest req, HttpServletResponse resp) {
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		try {
			List<BookVo> list = bookVoDao.list(bookVo, pageBean);
			System.out.println(list);
			ResponseUtil.writeJson(resp, new R()
					.data("total", pageBean.getTotal())
					.data("rows", list));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

配置xml文件

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

前台js代码,不用加formatter(格式化属性),直接新加一类就可显示
在这里插入图片描述
到这里就结束了,有不对或补充的地方欢迎大家评论,谢谢!

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章           查看所有文章
加:2021-10-09 16:11:30  更:2021-10-09 16:14:04 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/29 5:24:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计