mvc&EasyUI图片上传 书籍类别查询

1用户首页类别显示

类别实体类

package com.wyy.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;
	}
	@Override
	public String toString() {
		return "Category [id=" + id + ", name=" + name + "]";
	}
	public Category(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public Category() {
		// TODO Auto-generated constructor stub
	}
}

CategoryDao

package com.wyy.dao;

import java.util.List;

import com.wyy.entity.Category;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;

public class CategoryDao extends BaseDao<Category>{

	public List<Category> categoryList(Category c, PageBean pageBean) throws Exception {
		String sql="select * from t_easyui_category where 1=1";
		return super.executeQuery(sql, Category.class, pageBean);
	}
	
}

子控制器(CategoryAction)

package com.wyy.Action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wyy.dao.CategoryDao;
import com.wyy.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 c=new Category();
	private CategoryDao cdao=new CategoryDao();
	
	public Category getModel() {
		// TODO Auto-generated method stub
		return c;
		
		
	}
	
	public String Categorylist(HttpServletRequest req, HttpServletResponse resp) throws Exception {
			List<Category> categoryList = cdao.categoryList(c, null);
			ResponseUtil.writeJSON(resp, categoryList);
		
		return null;
	}
}

配置mvc.xml

<action path="/Category" type="com.wyy.Action.CategoryAction">
   </action>

页面js使用拼接

$(function () {

    //分类
    $.ajax({
        url: '${pageContext.request.contextPath}/Category.action?methodName=Categorylist',
        success: function (data) {
        	/*将json数组转成数组*/
            data = eval(data);
            
            for (i of data) {
                $(".list-group").append('<li onclick="searchByType('+ i.id+')" class="list-group-item">' + i.name + '</li>');
            }
        }
    });


})

 

2 书籍类别查询

 需求:点击左侧类别,右侧显示对应类别书籍并且带分页

BookDao

/**
	 * 查询书籍 当前台传值再根据条件查询
	 * @param b
	 * @param pageBean
	 * @return
	 * @throws Exception
	 */
	public List<EasyuiBook> list(EasyuiBook b, PageBean pageBean) throws Exception {
		String sql = "select * from t_easyui_book where 1=1 ";
		int state = b.getState();
		String name = b.getName();
		long cid = b.getCid();
		if (StringUtils.isNotBlank(name)) {
			sql += " and name like '%" + name + "%'";
		}
        //书籍状态
		if (state != 0) {
			sql += " and state=" + state;
		}
        //类别ID
		if (cid != 0) {
			sql += " and cid=" + cid;
		}
		return super.executeQuery(sql, EasyuiBook.class, pageBean);

	}

子控制器(EasyuibookAction)

当前台点击类别时,将类别ID传到后台,查出数据后,将数据返回到页面

/**
	 * 按照数据类别查询对应书籍
	 * 从首页index.JSP传递书籍类别到后台查询
	 * 通过类别ID查询到对应书籍集合到前台遍历
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String findByType(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		PageBean p=new PageBean();
		p.setRequest(req);
		List<EasyuiBook> list = bdao.list(b, p);
		req.setAttribute("books", list);
		req.setAttribute("pagebean", p);
		return "findbook";
	}

配置mvc.xml

<action path="/EasyuiBook" type="com.wyy.Action.EasyuibookAction">
        <forward name="findbook" path="/fg/findBook.jsp" redirect="false" />
    </action>

书籍展示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="x" uri="http://zking.sum" %>
<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}/EasyuiBook.action?methodName=findByType" 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="${pageContext.request.contextPath}${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>--%>

          <x:page p="${pagebean}"></x: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}/EasyuiBook.action?methodName=findByType&cid='+cid;
    };
</script>

</body>
</html>

 

3 图片上传

图片上传方法 (EasyuibookAction)

public String upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		 try {
	            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("普通字段处理");
	                    b.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];

	                    b.setImage(serverDir + imageName + "." + subfix);
	                    item.write(new File(diskDir + imageName + "." + subfix));
	                   this.bdao.editImgUrl(b);
	                    ResponseUtil.writeJSON(resp, 1);
	                }
	            }

	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return null;
	    }
	

图片上传工具类 

package com.zking.util;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

	public static String getCurrentDateStr() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}

}

文件解析类 

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) {
		InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
		Properties p=new Properties();
		try {
			p.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return p.getProperty(key);
	}

}

resource.properties文件内容 

serverDir=/uploadImages/    图片映射地址
diskDir=D:/EasyUI/upload/   图片存放真实地址

servlet.xml

<Context path="/uploadImages" docBase="D:/EasyUI/upload"/> 

js图片上传提交

//图片上传
    function upload() {
        $('#dd2').dialog('open');
    }

    //图片上传表单提交
    function submitForm2() {
        var row = $('#dg').datagrid('getSelected');
        $('#ff2').form('submit', {
            url: '${pageContext.request.contextPath}/EasyuiBook.action?methodName=upload&id=' + row.id,
            success: function (param) {
                $('#dd2').dialog('close');
                $('#dg').datagrid('reload');
                $('#ff2').form('clear');
            }
        })
    }

4bookvo使用 

package com.wyy.entity;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;

/**
 * 视图模型对象
 * 用于一个页面显示多张表数据
 * @author T440s
 *
 */
public class BookVo {

	private long id;
    private String name;
    private String pinyin;
    private String author;
    private float price;
    private  String image;
    private String publishing;
    private String description;
    private int state;
    //注解
    @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    private Date deployTime;
    private int sales;
    // private int cid; 类别id 使用连表查询将类别ID替换成名字
    //类别名字
    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 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 + ", 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, 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.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

 之所以实体类需要将显示数据的属性全部写出,是因为在我们的MVC中,反射封装属性值时,会通过值对应的名字与类对象中的属性名进行比较,属性名一致时,才会将值封装

package com.wyy.dao;

import java.util.List;

import com.wyy.entity.BookVo;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;

public class BookVoDao extends BaseDao<BookVo> {

	
	public List<BookVo> listvo(BookVo bv,PageBean p) throws Exception{
		String sql="select b.id id,b.name name ,b.pinyin pinyin,b.author author, b.price price,b.image image,b.publishing publishing,\r\n"
				+ "b.description description,b.state state,b.deployTime deployTime,b.sales sales\r\n"
				+ ",c.name cname from t_easyui_book b,t_easyui_category c where b.cid=c.id";
			return super.executeQuery(sql, BookVo.class, p);
	} 
}

 

package com.wyy.Action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wyy.dao.BookVoDao;
import com.wyy.entity.BookVo;
import com.wyy.entity.EasyuiBook;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
import com.zking.util.ResponseUtil;

public class BookVoAction extends ActionSupport implements ModelDriver<BookVo>  {

	private BookVo b=new BookVo();
	private BookVoDao bvdao=new BookVoDao();
	
	@Override
	public BookVo getModel() {
		// TODO Auto-generated method stub
		return b;
	}
	public String bookvo(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		PageBean p=new PageBean();
		p.setRequest(req);
		List<BookVo> list =bvdao.listvo(b, p);
		Map<String , Object> map=new HashMap<String, Object>();
		map.put("total", p.getTotal());
		map.put("rows", list);
		ResponseUtil.writeJSON(resp, map);
		return null;
	}

	
}

 前台发送请求即可

​​​​​​​

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值