本篇博客完成首页展示以及买家购买界面数据展示,书籍封面图片上传
一、动态显示数据表格列数字对应内容
方式一:利用ajax
注意点:
1、同步异步
解决方法: async:false,
2、数据库查询次数多,查询慢,性能差。
3、返回的数据json对象转换成json字符串
field: 'cid', title: '书籍类别', width: 50, formatter: function (value, row, index) {
// 书籍类别id
var cid=row.cid;
var typeName="";
$.ajax({
url:'${pageContext.request.contextPath}/category.action?methodName=load&&id'+cid,
//同步异步
async:false,
success:function(data){
//json对象
var jsonObj=eval("("+data+")");
//返回Json串
// typeName=data.name;
}
});
/* if (row.cid == 1) {
return "文艺";
} else if (row.cid == 2) {
return "小说";
} else if (row.cid == 3) {
return "青春";
} else {
return value;
} */
return typeName;
}
方式二:Vo(推荐使用)
vo:view object视图模型对象
用于在同一个界面显示多张表的数据
BookVo
package com.zking.Vo;
import java.util.Date;
import com.dhm.entity.Book;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* vo:view object视图模型对象
* 用于在同一个界面显示多张表的数据
* @author zjjt
*
*/
public class BookVo extends 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;
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 + "]";
}
}
BookVoDao
package com.dhm.dao;
import java.util.List;
import com.zking.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.dhm.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dhm.dao.BookVoDao;
import com.zking.Vo.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);
ResponseUtil.writeJson(resp, new R()
.data("total", pageBean.getTotal())
.data("rows", list)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、首页书籍类别显示
index.js
$(function(){
$.ajax({
url:$("#ctx").val()+"/category.acton?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);
}
});
})
Action
public String combobox(HttpServletRequest req, HttpServletResponse resp) {
try {
List<Category> list = categoryDao.list(category, null);
ResponseUtil.writeJson(resp, list);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
效果图:
三、按照书籍类别查询书籍信息
index.jsp
function searchByType(cid){
location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
};
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("book", list);
req.setAttribute("pagebean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}
return "findBook";
}
mvc.xml
<action path="/bookVo" type="com.dhm.web.BookVoAction">
</action>
效果图:
四、网络图片上传
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" });
}
BookAction
public String upload(HttpServletRequest request, HttpServletResponse resp) throws Exception {
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();
ResponseUtil.writeJson(resp, 2);
}
return null;
}
DateUtil
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());
}
}
resource.properties(图片路径
disDir=E:/temp/2021/mvc/upload/
serverDir=/uploadImages/
PropertiesUtil
package com.zking.util;
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);
}
}
在servers.xml中配置图片路径
<Context path="/uploadImages" docBase="E:/temp/2021/mvc/upload/"/>
效果图