package com.zking.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static String getCurrentDateStr() {
//20210927xxx
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(new Date());
}
}
思维导图
将书籍类别死数据变活
两种方案:
1、数据遍历,发送ajax请求
注意点:
1.同步异步问题
2.json字符串转json对象问题
3.性能非常差
①修改CategroyDao
package com.lsy.dao;
import java.util.List;
import com.lsy.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增加load
public String load(HttpServletRequest req, HttpServletResponse resp) {
try {
//传递id到后台,只会查出一个类别
Category c = categoryDao.list(category, null).get(0);
ResponseUtil.writeJson(resp, c);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}listBook1.jsp页面(以下是死数据,我们要将它变活)
/* if (row.cid == 1) { return "文艺"; } else if (row.cid == 2) { return "小说"; } else if (row.cid == 3) { return "青春"; } else { return value; } */
改为(调用action中的load方法,进行转变)
var cid=row.cid; var typeName=""; $.ajax({ url:'${pageContext.request.contextPath}/category.action?methodName=load&&id='+cid, async:false, success:function(data){ var jsonObj=eval("("+data+")"); typeName=jsonObj.name; } });
2、Vo类性能优化
①增加实体类,书写dao包以及web包
Vo实体类
注意:BookVo实体类继承了Book,但是只是继承了Book中的方法,并没有继承到属性,所以要把Book的属性也添加进去
package com.lsy.vo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lsy.entity.Book;
/**
* vo: view object视图模型对象
* 用在哪里:在同一个页面显示多张表的数据
* @author zjjt
*
*/
public class BookVo extends Book{
private String cname;
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 String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
BookVoDao(sql语句中进行了连表查询)
package com.lsy.dao;
import java.util.List;
import com.lsy.entity.Book;
import com.lsy.vo.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.lsy.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.lsy.dao.BookDao;
import com.lsy.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() {
return book;
}
public void list(HttpServletRequest req, HttpServletResponse resp) {
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) {
e.printStackTrace();
}
}
配置xml文件
<action path="/bookVo" type="com.lsy.web.BookVoAction">
</action>
listBook1.jsp界面
$('#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},
{
界面展示
一、门户首页类别
①直接调用CategoryDao的list方法;
②调用CategoryAction的combobox方法;
③index.jsp增加<input>输入框,并隐藏
<input type="hidden" id="ctx" value="${pageContext.request.contextPath}">
index.js界面
$(function(){
$.ajax({
url:$("#ctx").val()+"/category.action?methodName=combobox",
success:function(data){
var jsonArr=eval("("+data+")");
var html='';
for(var i in jsonArr){
html+='<li class="list-group-item" onclick="searchByType('+jsonArr[i].id+')">'+jsonArr[i].name+'</li>';
}
$(".list-group").append(html);
}
})
})
结果展示
二、类别分类查询
1.在index.js文件中增加点击事件onclick
html+='<li class="list-group-item" οnclick="searchByType('+jsonArr[i].id+')">'+jsonArr[i].name+'</li>';
2.index.jsp页面中的searchType方法
function searchByType(cid){
location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
};
3.BookAction增加findByType方法,BookDao修改list方法
①BookAction
-
/** * 按照书籍的类别查询出对应的书籍信息 * 前端: * 从首页index.jsp传递书籍类别id到后台来查询 * 不是发送ajax请求 * 后端: * 通过类别id查询到对应书籍集合,到前台遍历 * 后台是有返回值 * @param req * @param resp * @return */ public String findByType(HttpServletRequest req, HttpServletResponse resp) { 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) { e.printStackTrace(); } return "findBook"; }
②BookD
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); }
结果展示
三.图片上传
一.导入相关jar包
1、listBook1.jsp图片表单提交方法
/图片上传表单提交 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) { $('#dd2').dialog('close'); $('#dg').datagrid('reload'); $('#ff2').form('clear'); } }) }
2、增加 resource.properties文件、DateUtil类、PropertiesUtil类
resource.properties文件diskDir=F:/temp1/
serverDir=/uploadImages/DateUtil类(转换格式)
package com.zking.util; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static String getCurrentDateStr() { //20210927xxx SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); return sdf.format(new Date()); } }
PropertiesUtil类(读取properties文件,注意不要写错了)
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 Exception{ Properties p=new Properties(); InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties"); p.load(in); return p.getProperty(key); } }
三.dao 以及 action
BookDao(editImgUrl方法)
public void editImgUrl(Book t) throws Exception { super.executeUpdate("update t_easyui_book set image=? where id=?", t, new String[] {"image","id"}); }public String upload(HttpServletRequest req, HttpServletResponse resp) { 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("普通字段处理"); 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); } } } catch (Exception e) { e.printStackTrace(); } return null; }
配置xml文件
注意:这次是在servers文件夹中的server.xml文件中配置
其中docBase要与你自己填的路径一致
<Context path="/uploadImages" docBase="F:/temp1/"/>
结果展示