Easyui项目:新增书籍,上架书籍,下架书籍

思路分析: 

在上篇博客的基础上新增新增书籍,上架书籍,下架书籍的功能

思路分析

一:应该为左侧树形图添加打开选项卡的方法

二:新增书籍---编写一个新增书籍的方法,当点击新增书籍时调用该方法就行了

三:上架/下架书籍---上架还是下架就是改变该书籍的状态,数据库中的state的属性就是存放该书籍的状态(1 未上架 2 已上架 3 已下架 默认值1 )

一:新增选项卡 

只需写一个新增选项卡的js文件

$(function () {
   $("#bookMenus").tree({
	   url:$("#ctx").val()+"/permission.action?methodName=tree",
	   onClick: function(node){
		   var exists=$("#bookTabs").tabs('exists',node.text);
		   if(exists){
			   $("#bookTabs").tabs('select',node.text);
		   }else{
			   $('#bookTabs').tabs('add',{    
				    title:node.text,    
				    content:'<iframe width="100%" height="100%" src="'+$("#ctx").val()+node.attributes.self.url+'">',    
				    closable:true
				});  

		   }
	   }
   })
});

二:新增书籍

第一步:创建一个书籍的实体类

package com.sg.entity;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;

public class Book {
	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;
	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 Book() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", pinyin=" + pinyin + ", cid=" + cid + ", author=" + author
				+ ", price=" + price + ", image=" + image + ", publishing=" + publishing + ", description="
				+ description + ", state=" + state + ", deployTime=" + deployTime + ", sales=" + sales + "]";
	}
}

第二步:新增一个BookDao用于编辑book的dao方法

public void add(Book t) throws Exception {
		// TODO Auto-generated method stub
		t.setPinyin(PinYinUtil.getAllPingYin(t.getName()));
		t.setDeployTime(new Date());
		super.executeUpdate("insert into t_easyui_book(name,pinyin,cid,author,price,image,publishing,description,state,deployTime,sales) values(?,?,?,?,?,?,?,?,?,?,?) ", t, new String[] {"name","pinyin","cid","author","price","image","publishing","description","state","deployTime","sales"});
	}

这里还会调用拼音工具类

package com.zking.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音工具类,能将汉字转换成拼音的首字母
 */
public class PinYinUtil {
	// 名字长度
	private static int NAME_LENGTH = 3;

	/**
	 * 将首个汉字转换为全拼
	 * 其他是汉字首字母
	 * @param src
	 * @return
	 */
	public static String getPingYin(String src) {

		char[] name = src.toCharArray();
		String[] newName = new String[name.length];
		HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();
		pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
		String account = "";
		int length = name.length;
		try {
			// 名字大于等于3个字的时候,姓取全称,名取首字母。
			if(length>=NAME_LENGTH){
				for (int i = 0; i < length; i++) {
					// 截取姓
					if(i==0){
						// 判断是否为汉字字符
						if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) {
							newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat);
							account += newName[0];
						} else
							account += Character.toString(name[i]);
					}else{
						account += getPinYinHeadChar(Character.toString(name[i]));
					}

				}
			}else{
				// 只有2个字的名字,账号是名字的拼音全称
				for (int i = 0; i < length; i++) {
					// 判断是否为汉字字符
					if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) {
						newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat);
						account += newName[0];
					} else
						account += Character.toString(name[i]);
				}
			}
			return account;
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		return account;
	}

	/**
	 * 全部汉字转换成拼音
	 * @param src
	 * @return
	 */
	public static String getAllPingYin(String src) {
		StringBuffer sb = new StringBuffer();
		String [] arr = src.split("");
		for (String s : arr) {
			sb.append(PinYinUtil.getPingYin(s));
		}
		return sb.toString();
	}

	/**
	 * 返回中文的首字母
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {

		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}

	public static void main(String[] args) {
		String cn = "保存并插入数据库";
		System.out.println(PinYinUtil.getAllPingYin(cn));
		System.out.println(PinYinUtil.getPingYin(cn));
		System.out.println(PinYinUtil.getPinYinHeadChar(cn));
	}
}

第三步:新增一个BookAction编写book的web层

public void add(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		try {
			bookDao.add(book);
			ResponseUtil.writeJson(resp, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, 0);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

第四步:填写配置文件

<action path="/book" type="com.sg.web.BookAction">
	
	</action>

第五步:填写js文件

$(function () {
       $('#cid').combobox({
    	   url:'${pageContext.request.contextPath}/category.action?methodName=combobox',
    	   valueField:'id',
    	   textField:'name'
       })
    });

    function submitForm() {
    	$('#ff').form('submit', {    
    	    url:'${pageContext.request.contextPath}/book.action?methodName=add',    
    	    success:function(data){ 
    	    	if(data==1){
    	    		$('#ff').form('clear');
    	    	}
    	    }    
    	}); 
    }

    function clearForm() {
    	$('#ff').form('clear');
    }

结果展示:

三:上架/下架书籍

第一步:编写dao方法(具体方法看代码里面有注释)

package com.sg.dao;

import java.util.Date;
import java.util.List;

import com.sg.entity.Book;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.PinYinUtil;
import com.zking.util.StringUtils;

public class BookDao extends BaseDao<Book>{
	/**
	 * 查询所有书籍
	 * @param book
	 * @param pageBean
	 * @return
	 * @throws Exception
	 */
	public List<Book> list(Book book, PageBean pageBean) throws Exception {
		// TODO Auto-generated method stub
		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);
	}
	/**
	 * 修改
	 * @param t
	 * @throws Exception
	 */
	public void edit(Book t) throws Exception {
		// TODO Auto-generated method stub
		super.executeUpdate("update t_easyui_book set name=?,pinyin=?,cid=?,image=?,state=?,sales=? where id=?", 
				t, new String[] {"name","pinyin","cid","image","state","sales","id"});
	}
	/**
	 * 新增书籍
	 * @param t
	 * @throws Exception
	 */
	public void add(Book t) throws Exception {
		// TODO Auto-generated method stub
		t.setPinyin(PinYinUtil.getAllPingYin(t.getName()));
		t.setDeployTime(new Date());
		super.executeUpdate("insert into t_easyui_book(name,pinyin,cid,author,price,image,publishing,description,state,deployTime,sales) values(?,?,?,?,?,?,?,?,?,?,?) ", t, new String[] {"name","pinyin","cid","author","price","image","publishing","description","state","deployTime","sales"});
	}
	/**
	 * 上架/下架通用
	 * @param t
	 * @throws Exception
	 */
	public void editStatus(Book t) throws Exception {
		// TODO Auto-generated method stub
		super.executeUpdate("update t_easyui_book set state=? where id=?", 
				t, new String[] {"state","id"});
	}
	
	public void editImgUrl(Book book)throws Exception {
		// TODO Auto-generated method stub
		String sql="update t_easyui_book set image=? where id=?";
		super.executeUpdate(sql, book, new String[] {"image","id"});
	}
}

第二步:编写web层

package com.sg.web;

import java.io.File;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sg.dao.BookDao;
import com.sg.entity.Book;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.DateUtil;
import com.zking.util.PageBean;
import com.zking.util.PropertiesUtil;
import com.zking.util.R;
import com.zking.util.ResponseUtil;

public class BookAction extends ActionSupport implements ModelDriver<Book>{
	private Book book=new Book();
	private BookDao bookDao=new BookDao();
	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}
	/**
	 * 查询所有书籍
	 * @param req
	 * @param resp
	 */
	public void list(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = bookDao.list(book, pageBean);
			ResponseUtil.writeJson(resp, new R()
					.data("total", pageBean.getTotal())
					.data("rows", list));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 新增书籍
	 * @param req
	 * @param resp
	 */
	public void add(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		try {
			bookDao.add(book);
			ResponseUtil.writeJson(resp, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, 0);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	/**
	 * 修改
	 * @param req
	 * @param resp
	 */
	public void edit(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		try {
			bookDao.edit(book);
			ResponseUtil.writeJson(resp, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, 0);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	/**
	 * 上架/下架通用
	 * 如果上架则传2
	 * 如果下架则改为3
	 * @param req
	 * @param resp
	 */
	public void editStatus(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		try {
			bookDao.editStatus(book);
			ResponseUtil.writeJson(resp, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, 0);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 前台获取所有类别
	 * @param req
	 * @param resp
	 * @return
	 */
	public String findByType(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		try {
			PageBean pageBean=new PageBean();
			pageBean.setRequest(req);
			List<Book> list = bookDao.list(book, pageBean);
			req.setAttribute("books", list);
			req.setAttribute("pagebean", pageBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "findBook";
	}
	
	/**
	 * 图片上传
	 * @param request
	 * @param resp
	 * @return
	 */
	public String upload(HttpServletRequest request, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		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(resp, 1);
                }
            }

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

第三步:配置xml文件

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

第四步:编写js代码

function edit() {
        $('#cid').combobox({
            url:'${pageContext.request.contextPath}/category.action?methodName=list',
            valueField:'id',
            textField:'name'
        });

        var row = $('#dg').datagrid('getSelected');
        if (row) {
            $('#ff').form('load', row);
            $('#dd').dialog('open');
        }
    }

结果展示:

上架最后一个

 然后再下架

拜拜了各位!!!晚安

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值