自定义mvc项目之首页类别查询,模糊查询,及图片上传

一、课程目标

        1、左侧没有菜单栏,要显示菜单栏

        2、根据点击左侧菜单栏,要出现相应的书籍

        3、最后就是图片上传

二、具体思路、代码以及效果显示

一、显示菜单栏:   

                         1、要写一个查询书籍类别的方法

                         2、在index.js中运用ajax技术,定义一个jsonarr来接收数据

                         3、定义一个html来拼接数据

                         4、最后显示

  2、代码:

1.Category实体类:(类别)

package com.csf.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() {
        super();
        // TODO Auto-generated constructor stub
    }
 
}

2.CategoryDao:

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


3.CategoryAction

package com.csf.web;
 
import com.csf.dao.CategoryDao;
import com.csf.entity.Category;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
 
 
public class CategoryAction extends ActionSupport implements ModelDriver<Category> {
    private Category category = new Category();
    private CategoryDao categoryDao = new CategoryDao();
 
    /**
     * 加载书籍类别下拉框
     * @param req
     * @param resp
     * @return
     */
    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;
    }
    
    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;
    }
 
    @Override
    public Category getModel() {
        return category;
    }
      
}


4.配置mvc.xml

<action type="com.csf.web.CategoryAction" path="/Category">
</action> 

5.js拼接

//门户首页类别
$(function(){
    $.ajax({
    url:$("#ctx").val()+"/Category.action?methodName=combobox",
    success:function(data){
//        var jsonstr='[{"id":1,"name":"文艺"},{"id":2,"name":"小说"},{"id":3,"name":"生活"}]'
        alert(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、思路:

1、在index.js中要给对应的方法添加点击事件,并附带id传到index.jsp界面

 2、当点击左侧菜单栏时要附带改类别的id传到搜索书籍的方法

 3、最后查询出改类别所有的书籍,先是在bookdao加上cid的条件,最后在  bookAction中调用。                    

代码: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);
		 }
	});
})

 index界面代码

 <div class="col-md-3 float-left c-left">
            <ul class="list-group">
                <li class="list-group-item">书籍分类</li>
            </ul>
        </div>

只需要具备这个就可以

还需要具备相关的后台结构,由于简单且多,就不做演示。(dao,web,配置)

效果图

文艺:

 小说:

 等等。。。

三、图片上传:

            1、思路:                       

 1、导入图片上传需要的jar包

 2、到BookDao中写好修改image路径的方法

 3、BookAction中写好上传图片的方法,名为upload。

 4、到eclipse内部服务器中配置好图片映射

             2、代码:

 1、导入图片上传需要的jar包

 2、到BookDao中写好修改image路径的方法

    public void editImgUrl(Book t) throws Exception {
        super.executeUpdate("update t_easyui_book set image=? where id=?", t, 
                new String[] {"image","id"});
    }

 3、BookAction中写好上传图片的方法,名为upload。

工具类:

package com.zking.util;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * 日期处理工具包
 * @author Administrator
 *
 */
public class DateUtil {
 
    */
    /**
     * 获取当前时间的字符串
     * @return
     * @throws Exception
     */
    public static String getCurrentDateStr()throws Exception{
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(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) throws IOException{
        Properties p=new Properties();
        InputStream in=PropertiesUtil.class.getResourceAsStream("/resources.properties");
        p.load(in);
        return p.getProperty(key);
    }
 }

图片映射代码:

写在tomcat的servlet.xml的host标签中

<Context path="/uploadImages" docBase="E:/temp/2021/mvc/upload/"/>        
<Context path="/" docBase="/mvc"/> 

BookAction中的图片上传方法

public String upload(HttpServletRequest request, HttpServletResponse response) {
    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(Integer.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(response, 1);
            }
        }

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

 注:tomcat尽量不要放在中文目录下,不然会出现映射地址无法使用的问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无感_K

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值