第19讲.综合案例

2020-02-18  本文已影响0人  祥祺

项目准备

前台CRUD
前台高级查询和分页
创建系统默认账户:Listener
用户登录:session
用户注销:session
登录检查:Filter
验证码:session
记住我:Cookie
添加商品图片:文件上传

完整代码如下:

dao

IEmployeeDAO:

package cn.wolfcode.crud.dao;

import cn.wolfcode.crud.domain.Employee;

public interface IEmployeeDAO {
    /**
     * 增加操作
     * 
     * @param employee
     *            对象
     */
    void insert(Employee employee);

    /**
     * 查询单条信息
     * 
     * @param name
     *            行数
     * @return 对象
     */
    Employee selectByName(String name);

    /**
     * 验证用户名和密码
     * 
     * @param employee1
     * @return
     */
    Employee selectByNameAndPwd(Employee employee1);

}

IProductDAO:

package cn.wolfcode.crud.dao;

import java.util.List;

import cn.wolfcode.crud.domain.Product;
import cn.wolfcode.crud.query.QueryObject;

public interface IProductDAO {
    /**
     * 增加操作
     * 
     * @param product
     *            对象
     */
    void insert(Product product);

    /**
     * 删除操作
     * 
     * @param id
     *            行数
     */
    void delete(Long id);

    /**
     * 更新操作
     * 
     * @param product
     *            对象
     */
    void update(Product product);

    /**
     * 查询单条信息
     * 
     * @param id
     *            行数
     * @return 对象
     */
    Product get(Long id);

    /**
     * 查询全部信息
     * 
     * @return list集合中
     */
    List<Product> getList();

    /**
     * 根据条件获取总条数
     * 
     * @param qo
     * @return
     */
    int queryForTotalCount(QueryObject qo);

    /**
     * 根据条件获取数据
     * 
     * @param qo
     * @return
     */
    List<Product> queryForListData(QueryObject qo);
}


dao.impl

EmployeeDAOImpl:

package cn.wolfcode.crud.dao.impl;

import org.apache.ibatis.session.SqlSession;

import cn.wolfcode.crud.dao.IEmployeeDAO;
import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.util.MybatisUtil;

public class EmployeeDAOImpl implements IEmployeeDAO {

    @Override
    public void insert(Employee employee) {
        SqlSession session = MybatisUtil.getSession();
        session.insert("cn.wolfcode.crud.mapper.EmployeeMapper.insert", employee);
        session.close();
    }

    @Override
    public Employee selectByName(String name) {
        SqlSession session = MybatisUtil.getSession();
        Employee employee = session.selectOne("cn.wolfcode.crud.mapper.EmployeeMapper.selectByName", name);
        session.close();
        return employee;
    }

    @Override
    public Employee selectByNameAndPwd(Employee employee1) {
        SqlSession session = MybatisUtil.getSession();
        Employee employee = session.selectOne("cn.wolfcode.crud.mapper.EmployeeMapper.selectByNameAndPwd", employee1);
        session.close();
        return employee;
    }

}


ProductDAOImpl:

package cn.wolfcode.crud.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import cn.wolfcode.crud.dao.IProductDAO;
import cn.wolfcode.crud.domain.Product;
import cn.wolfcode.crud.query.QueryObject;
import cn.wolfcode.crud.util.MybatisUtil;

public class ProductDAOImpl implements IProductDAO {
    @Override
    public void insert(Product product) {
        SqlSession session = MybatisUtil.getSession();
        session.insert("cn.wolfcode.crud.mapper.ProductMapper.insert", product);
        session.close();
    }

    @Override
    public void delete(Long id) {
        SqlSession session = MybatisUtil.getSession();
        session.delete("cn.wolfcode.crud.mapper.ProductMapper.delete", id);
        session.close();
    }

    @Override
    public void update(Product product) {
        SqlSession session = MybatisUtil.getSession();
        session.update("cn.wolfcode.crud.mapper.ProductMapper.update", product);
        session.close();
    }

    @Override
    public Product get(Long id) {
        SqlSession session = MybatisUtil.getSession();
        Product p = session.selectOne("cn.wolfcode.crud.mapper.ProductMapper.get", id);
        session.close();
        return p;
    }

    @Override
    public List<Product> getList() {
        SqlSession session = MybatisUtil.getSession();
        List<Product> list = session.selectList("cn.wolfcode.crud.mapper.ProductMapper.getList");
        session.close();
        return list;
    }

    @Override
    public int queryForTotalCount(QueryObject qo) {
        SqlSession session = MybatisUtil.getSession();
        int count = session.selectOne("cn.wolfcode.crud.mapper.ProductMapper.queryForTotalCount", qo);
        session.close();
        return count;
    }

    @Override
    public List<Product> queryForListData(QueryObject qo) {
        SqlSession session = MybatisUtil.getSession();
        List<Product> list = session.selectList("cn.wolfcode.crud.mapper.ProductMapper.queryForListData", qo);
        session.close();
        return list;
    }

}


domain

Product:

package cn.wolfcode.crud.domain;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter@Setter@ToString
public class Product {
    private Long id;
    private String productName;
    private Long dirId;
    private Double salePrice;
    private String supplier;
    private String brand;
    private Double cutoff;
    private Double costPrice;
    private String imagePath;// 商品图片的路径
    //增加属性 商品分类的名称
    public String getDirName() {
        if (dirId == 1) {
            return "鼠标";
        } else if (dirId == 2) {
            return "无线鼠标";
        } else if (dirId == 3) {
            return "有线鼠标";
        } else {
            return "游戏鼠标";
        }
    }
}


Employee:

package cn.wolfcode.crud.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@NoArgsConstructor
@ToString
public class Employee {
    private Long id;
    private String name;
    private String password;
    private String email;
    private boolean admin;
}


mapper

ProductMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wolfcode.crud.mapper.ProductMapper">
    <insert id="insert">
        insert into
        product(productName,dir_id,salePrice,supplier,
        brand,cutoff,costPrice,imagePath)
        values(#{productName},#{dirId},#{salePrice},#{supplier},#{brand},
        #{cutoff},#{costPrice},#{imagePath})
    </insert>
    <delete id="delete">
        delete from product where id=#{id}
    </delete>
    <update id="update">
        update product set
        productName=#{productName},dir_id=#{dirId},
        salePrice=#{salePrice},imagePath=#{imagePath} 
        ,supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},
        costPrice=#{costPrice}
        where id=#{id}
    </update>
    <resultMap type="product" id="map">
        <id column="id" property="id" />
        <result column="productName" property="productName" />
        <result column="dir_id" property="dirId" />
        <result column="salePrice" property="salePrice" />
        <result column="supplier" property="supplier" />
        <result column="brand" property="brand" />
        <result column="cutoff" property="cutoff" />
        <result column="costPrice" property="costPrice" />
        <result column="imagePath" property="imagePath" />
    </resultMap>
    <select id="get" resultMap="map">
        select * from product where id=#{id}
    </select>
    <select id="getList" resultMap="map">
        select * from product
    </select>

    <select id="queryForTotalCount" resultType="int">
        select count(*) from product
       <include refid="condition"/>
    </select>

    <sql id="condition">
        <where>
            <if test="keyword != null and keyword != '' ">
                and (productName like concat('%',#{keyword},'%') or 
                brand like concat('%',#{keyword},'%'))
            </if>
            <if test="minPrice != null">
                and salePrice &gt;= #{minPrice}
            </if>
            <if test="maxPrice != null">
                and salePrice &lt;=#{maxPrice}
            </if>
        </where>
    </sql>

    <select id="queryForListData" resultMap="map">
        select * from product
         <include refid="condition"/>
         limit #{startIndex},#{pageSize}
    </select>
</mapper>
  

EmployeeMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wolfcode.crud.mapper.EmployeeMapper">
    <insert id="insert">
        insert into
        employee(name,password,email,admin)
        values(#{name},#{password},#{email},#{admin})
    </insert>
     
     <select id="selectByName" resultType="employee">
        select * from employee where name = #{name}
     </select>
     
     <select id="selectByNameAndPwd" resultType="employee">
      select * from employee where name = #{name} and password= #{password}
     </select> 
</mapper>
  

query

PageResult:

package cn.wolfcode.crud.query;

import java.util.Collections;
import java.util.List;

import lombok.Getter;

@Getter
public class PageResult {
    private int currentPage; // 当前页
    private int pageSize; // 每页数量
    private int prevPage; // 上一页
    private int nextPage; // 下一页
    private int endPage; // 末页
    private int totalCount; // 总条数
    private List<?> data; // 当前页的数据

    public PageResult(int pageSize) {
        this(1, pageSize, 0, Collections.EMPTY_LIST);
    }

    public PageResult(int currentPage, int pageSize, int totalCount, List<?> data) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.data = data;
        this.totalCount = totalCount;
        // 表示总共一页
        if (totalCount < pageSize) {
            endPage = 1;
            prevPage = 1;
            nextPage = 1;
            return;
        }
        endPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        prevPage = currentPage - 1 >= 1 ? currentPage - 1 : 1;
        nextPage = currentPage + 1 < endPage ? currentPage + 1 : endPage;
    }
}


ProductQueryObject:

package cn.wolfcode.crud.query;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ProductQueryObject extends QueryObject {
    private String keyword; // 关键字
    private Double minPrice;// 最低价
    private Double maxPrice;// 最高价
}


QueryObject:

package cn.wolfcode.crud.query;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class QueryObject {
    private int currentPage = 1; // 当前页
    private int pageSize = 5; // 每页显示的数量

    public int getStartIndex() {
        return (currentPage - 1) * pageSize;
    }

}


service

IProductService:

package cn.wolfcode.crud.service;

import java.util.List;

import cn.wolfcode.crud.domain.Product;

public interface IProductService {
    void insertService(Product product);

    void deleteService(Long id);

    void updateService(Product product);

    Product getService(Long id);

    List<Product> getListService();
}


IEmployeeService:

package cn.wolfcode.crud.service;

import cn.wolfcode.crud.domain.Employee;

public interface IEmployeeService {
    void insertEmployee(Employee employee);

    Employee selectEmployeeByName(String name);

    Employee selectEmpByNameAndPwd(Employee employee);

}


service.impl

ProductServiceImpl:

package cn.wolfcode.crud.service.impl;

import java.util.List;

import cn.wolfcode.crud.dao.IProductDAO;
import cn.wolfcode.crud.dao.impl.ProductDAOImpl;
import cn.wolfcode.crud.domain.Product;
import cn.wolfcode.crud.query.PageResult;
import cn.wolfcode.crud.query.QueryObject;
import cn.wolfcode.crud.service.IProductService;

public class ProductServiceImpl implements IProductService {

    IProductDAO dao = new ProductDAOImpl();

    @Override
    public void insertService(Product product) {
        dao.insert(product);
    }

    @Override
    public void deleteService(Long id) {
        dao.delete(id);
    }

    @Override
    public void updateService(Product product) {
        dao.update(product);
    }

    @Override
    public Product getService(Long id) {
        Product product = dao.get(id);
        return product;
    }

    @Override
    public List<Product> getListService() {
        List<Product> list = dao.getList();
        return list;
    }

    public PageResult query(QueryObject qo) {
        int totalCount = dao.queryForTotalCount(qo);
        if (totalCount == 0) {
            return new PageResult(qo.getPageSize());
        }
        List<Product> products = dao.queryForListData(qo);
        return new PageResult(qo.getCurrentPage(), qo.getPageSize(), totalCount, products);
    }

}


EmployeeServiceImpl:

package cn.wolfcode.crud.service.impl;

import cn.wolfcode.crud.dao.IEmployeeDAO;
import cn.wolfcode.crud.dao.impl.EmployeeDAOImpl;
import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.service.IEmployeeService;

public class EmployeeServiceImpl implements IEmployeeService {

    IEmployeeDAO dao = new EmployeeDAOImpl();

    @Override
    public void insertEmployee(Employee employee) {
        dao.insert(employee);
    }

    @Override
    public Employee selectEmployeeByName(String name) {
        Employee employee = dao.selectByName(name);
        return employee;
    }

    @Override
    public Employee selectEmpByNameAndPwd(Employee employee1) {
        Employee employee = dao.selectByNameAndPwd(employee1);
        return employee;
    }

}


test

ProductServiceTest:

package cn.wolfcode.crud.test;

import java.util.List;

import org.junit.Test;

import cn.wolfcode.crud.domain.Product;
import cn.wolfcode.crud.service.IProductService;
import cn.wolfcode.crud.service.impl.ProductServiceImpl;

public class ProductServiceTest {
    IProductService dao = new ProductServiceImpl();
    @Test
    public void testInsertService() {
        Product p = new Product();
        p.setProductName("苹果");
        p.setDirId(2L);
        p.setSalePrice(Double.valueOf(121));
        p.setSupplier("苹果");
        p.setBrand("苹果");
        p.setCutoff(Double.valueOf(0.9));
        p.setCostPrice(Double.valueOf(3434));
        dao.insertService(p);
    }

    @Test
    public void testDeleteService() {
        dao.deleteService(23L);
    }

    @Test
    public void testUpdateService() {
        Product p = new Product();
        p.setProductName("苹果aaaa");
        p.setDirId(2L);
        p.setSalePrice(Double.valueOf(121));
        p.setSupplier("苹果sdfg");
        p.setBrand("苹果sdf");
        p.setCutoff(Double.valueOf(0.9));
        p.setCostPrice(Double.valueOf(3434));
        p.setId(23L);
        dao.updateService(p);
    }

    @Test
    public void testGetService() {
        Product p = dao.getService(9L);
        System.out.println(p);
    }

    @Test
    public void testGetListService() {
        List<Product> list = dao.getListService();
        for (Product p : list) {
            System.out.println(p);
        }
    }

}

util

MybatisUtil:

package cn.wolfcode.crud.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
    private static SqlSessionFactory factory;

    private MybatisUtil() {
    }
    static {
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() {
        return factory.openSession(true);
    }
}

StringUtil:

package cn.wolfcode.crud.util;

public final class StringUtil {
    //判断字符串
    public static  boolean hasLength(String str) {
        return str != null && str.trim().length() != 0;
    }
}

UploadUtil:

package cn.wolfcode.crud.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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

public final class UploadUtil {

    // 用来处理上传功能
    public static Map<String, String> upload(HttpServletRequest req) {
        // 定义Map集合
        Map<String, String> map = new HashMap<>();

        // 用来判断request是否符合文件上传的请求
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        // isMultipart 如果为true 表示请求是文件上传
        if (isMultipart) {
            try {
                // 创建一个磁盘工厂对象
                FileItemFactory factory = new DiskFileItemFactory();
                // 创建文件上传处理器
                ServletFileUpload upload = new ServletFileUpload(factory);
                // 设置上传文件大小的限制了
                // 限制上传单个文件的大小
                upload.setFileSizeMax(1024 * 1024 * 4);
                // 解析请求
                @SuppressWarnings("unchecked")
                List<FileItem> items = upload.parseRequest(req);

                for (FileItem fileItem : items) {
                    // 通过调用isFormField 来判断是否是普通字段
                    if (fileItem.isFormField()) {
                        // 获取普通字段的名称
                        String name = fileItem.getFieldName();
                        // 获取普通字段的内容
                        // 解决中文乱码的问题 通过调用getString(String encoding)方法 来解决
                        String value = fileItem.getString("utf-8");
                        map.put(name, value);
                    } else {
                        // 获取上传文件的名称
                        String fileName = fileItem.getName();
                        System.out.println(fileName);
                        // 把上传的文件写入指定的路径
                        if (fileName != null && fileName.trim().length() != 0) {
                            // fileItem.write(new File("F:/", fileName));
                            // 获取upload文件夹的真实路径
                            String realPath = req.getServletContext().getRealPath("/upload");
                            // 修改上传文件的名称 chengxuyuan.png
                            // 使用UUID 产生随机字符串
                            String randomStr = UUID.randomUUID().toString();
                            // 获取文件的后缀
                            String extName = fileName.substring(fileName.lastIndexOf("."));
                            // 拼接 文件的名称
                            String newFileName = randomStr + extName;
                            // 上传文件的类型约束
                            String contentType = fileItem.getContentType();
                            if (contentType.startsWith("image/")) {
                                File file = new File(realPath, newFileName);
                                map.put("imagePath", "/upload/" + newFileName);
                                fileItem.write(file);
                            } else {
                                System.out.println("文件类型不符合");
                            }

                        }
                    }
                }

            } catch (FileSizeLimitExceededException e) {
                System.out.println("单个文件上传过大");
            } catch (SizeLimitExceededException e) {
                System.out.println("所有文件的大小总和上传过大");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return map;
    }

}


web

web.servlet

LoginServlet:

package cn.wolfcode.crud.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.service.IEmployeeService;
import cn.wolfcode.crud.service.impl.EmployeeServiceImpl;
import cn.wolfcode.crud.util.StringUtil;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private IEmployeeService service = new EmployeeServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设值编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取表单提交的登录信息
        String name = req.getParameter("name");
        String pwd = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");

        if (StringUtil.hasLength(rememberMe)) {
            // 如果勾选了记住账号按钮,则我们把账号存放到cookie中
            // 保存账号信息到Cookie中
            Cookie cookie = new Cookie("name", name);
            Cookie checkBoxStatus = new Cookie("rememberMe", "on");
            resp.addCookie(cookie);
            resp.addCookie(checkBoxStatus);
        } else {
            // 如果没有勾选记住账号按钮,则我们把之前存在cookie中的账号信息清除
            Cookie cookie = new Cookie("name", "");
            resp.addCookie(cookie);
            Cookie checkBoxStatus = new Cookie("rememberMe", null);
            resp.addCookie(checkBoxStatus);
        }

        // 验证验证码的正确性
        // 获取表单提交过来的验证码
        String randomCode = req.getParameter("randomCode");
        // 获取session中保存的验证码
        String sessionCode = (String) req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
        if (!StringUtil.hasLength(randomCode) || !StringUtil.hasLength(sessionCode)) {
            // 表示两个验证码其中有一个是缺失的
            req.setAttribute("errorMsg", "验证码不能为空");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }

        if (!randomCode.equals(sessionCode)) {
            req.setAttribute("errorMsg", "验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        // 封装信息
        Employee employee = new Employee();
        employee.setName(name);
        employee.setPassword(pwd);

        Employee employeeResult = service.selectEmpByNameAndPwd(employee);
        // 如果查询到了用户信息 把信息存入session中
        if (employeeResult != null) {
            req.getSession().setAttribute("EMP_IN_SESSION", employeeResult);
            resp.sendRedirect("/product");
            return;
        }

        if (employeeResult == null) {
            req.setAttribute("errorMsg", "账号或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }

    }

}

LogoutServlet:

package cn.wolfcode.crud.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求用户信息从session中
        // 方式一: remove 掉指定的session
        req.getSession().removeAttribute("EMP_IN_SESSION");
        // 方式二: 通过销毁session
        // req.getSession().invalidate();
        // 重定向到登录
        resp.sendRedirect("/login.jsp");
    }

}


ProductServlet:

package cn.wolfcode.crud.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import cn.wolfcode.crud.domain.Product;
import cn.wolfcode.crud.query.PageResult;
import cn.wolfcode.crud.query.ProductQueryObject;
import cn.wolfcode.crud.service.impl.ProductServiceImpl;
import cn.wolfcode.crud.util.StringUtil;
import cn.wolfcode.crud.util.UploadUtil;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设值编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取参数,根据参数判断出要执行那一个方法
        String cmd = req.getParameter("cmd");
        if (cmd == null) {
            cmd = "";
        }
        switch (cmd) {
        case "input":
            inputService(req, resp);

            break;
        case "delete":
            deleteService(req, resp);

            break;
        case "saveOrUpdate":
            saveService(req, resp);

            break;

        default:
            listService(req, resp);
            break;
        }
    }

    // 创建一个业务层的对象来调用操作数据库
    private ProductServiceImpl service = new ProductServiceImpl();

    private void listService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取高级查询的条件
        String keyword = req.getParameter("keyword");
        String minPrice = req.getParameter("minPrice");
        String maxPrice = req.getParameter("maxPrice");
        String currentPage = req.getParameter("currentPage");
        ProductQueryObject qo = new ProductQueryObject();
        if (StringUtil.hasLength(minPrice)) {
            qo.setMinPrice(Double.valueOf(minPrice));
        }
        if (StringUtil.hasLength(maxPrice)) {
            qo.setMaxPrice(Double.valueOf(maxPrice));
        }
        if (StringUtil.hasLength(currentPage)) {
            qo.setCurrentPage(Integer.valueOf(currentPage));
        }
        qo.setKeyword(keyword);
        // 在页面上回显查询条件
        req.setAttribute("qo", qo);
        PageResult result = service.query(qo);
        req.setAttribute("result", result);
        req.getRequestDispatcher("/WEB-INF/views/product/list.jsp").forward(req, resp);
    }

    @Deprecated
    private void listService_bak(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        List<Product> list = service.getListService();
        req.setAttribute("list", list);
        req.getRequestDispatcher("/WEB-INF/views/product/list.jsp").forward(req, resp);
    }

    private void saveService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> map = UploadUtil.upload(req);
        Product product = new Product();
        try {
            BeanUtils.copyProperties(product, map);
            // 根据ID判断是添加还是更新数据然后调用业务层方法
            if (product.getId() != 0) {
                service.updateService(product);
            } else {
                // 新增操作不用ID
                service.insertService(product);
            }
            resp.sendRedirect("/product");

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private void deleteService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (StringUtil.hasLength(id)) {
            service.deleteService(Long.valueOf(id));
        }
        resp.sendRedirect("/product");
    }

    private void inputService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取ID判断
        String id = req.getParameter("id");
        if (id != null) {
            // 有ID证明是更新操作.此时我们要获取数据并回响数据给到界面给用户修改
            Product p = service.getService(Long.valueOf(id));
            // 把数据信息共享到作用域
            req.setAttribute("p", p);
        }
        // 请求转发到input.jsp
        req.getRequestDispatcher("/WEB-INF/views/product/input.jsp").forward(req, resp);
    }

}


web.listener

SystemAdminListener:

package cn.wolfcode.crud.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.service.IEmployeeService;
import cn.wolfcode.crud.service.impl.EmployeeServiceImpl;

public class SystemAdminListener implements ServletContextListener {
    IEmployeeService service = new EmployeeServiceImpl();

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // 先查询数据库中是否已经存在了管理员账号
        String name = "admin";
        String password = "123456";
        Employee employee = service.selectEmployeeByName(name);
        // 存在
        // 不存在
        if (employee == null) {
            // 新增一个管理员信息到数据库
            Employee employee2 = new Employee();
            employee2.setName(name);
            employee2.setPassword(password);
            employee2.setAdmin(true);
            employee2.setEmail("admin@wolfcode.cn");
            service.insertEmployee(employee2);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

}

RandomCodeServlet:

package cn.wolfcode.crud.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/randomCode")
public class RandomCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 生成随机数
        String randomCode = UUID.randomUUID().toString().substring(0, 5);

        // 把随机数放进Session中
        req.getSession().setAttribute("RANDOMCODE_IN_SESSION", randomCode);

        // 创建图片对象
        int width = 80;
        int height = 30;
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(width, height, imageType);

        // 画板
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        // 绘制一个实心的矩形
        g.fillRect(1, 1, width - 2, height - 2);

        // 把随机数画进图片中
        g.setColor(Color.BLACK);// 设置随机数的颜色
        Font font = new Font("宋体", Font.BOLD + Font.ITALIC, 20);
        g.setFont(font);// 设置随机数的字体和大小
        g.drawString(randomCode, 10, 24);
        // 干扰线
        g.setColor(Color.GRAY);
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            g.fillRect(r.nextInt(width), r.nextInt(height), 2, 2);
        }

        // 关闭
        g.dispose();
        // 把图片对象以流的方式保存出去
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }
}

web.filter

CheckLoginFilter:

package cn.wolfcode.crud.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginFilter implements Filter {

    private FilterConfig config;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 强转参数
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取配置的init-param参数
        String parameter = config.getInitParameter("check");
        String[] checkArray = parameter.split(",");
        for (String check : checkArray) {
            String uri = req.getRequestURI();
            if (uri.contains(check)) {
                // 能进入到if判断体中,表示不能放行
                // 验证用户是否登录
                // 1.从session中获取用户信息
                Object emp = req.getSession().getAttribute("EMP_IN_SESSION");
                // 2.如果没有获取到用户信息
                if (emp == null) {
                    resp.sendRedirect("/login.jsp");
                    return;
                }
            }
        }
        // 放行
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

}


resources

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"></properties>
    <typeAliases>
        <package name="cn.wolfcode.crud.domain" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
<mappers>
<mapper resource="cn/wolfcode/crud/mapper/ProductMapper.xml"/>
<mapper resource="cn/wolfcode/crud/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>

webapp

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>叩丁狼客户管理系统->用户登录</title>
    <link rel="stylesheet" href="/css/core.css" type="text/css"/>
    <link rel="stylesheet" href="/js/plugins/bootstrap/css/bootstrap.css" type="text/css"/>
    <script src="/js/plugins/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="/js/plugins/bootstrap/js/bootstrap.js" type="text/javascript"></script>
    <style type="text/css">
        body {
            background-color: #FFFFFF;
        }

        .cm-container {
            margin-top: 160px;
        }

        .login {
            width: 360px;
            height: 300px;
            margin: 0px auto;
        }
    </style>

    <script>
        function changeCode() {
            document.getElementById("randomCode").src = "/randomCode;" + new Date().getTime();
        }
    </script>
</head>
<body>
<div class="container cm-container">
    <h3 class="text-center"><font style="color: #337ab7;">叩丁狼客户管理系统(系统管理平台)</font></h3>
    <hr/>

    <div class="login">
        <span style="color: red" class="col-sm-3"></span>
        <span style="color: red" class="col-sm-9">${errorMsg}</span>
        <form class="form-horizontal" action="/login" method="post">
            <div class="form-group">
                <label for="inputEmail3" class="col-sm-3 control-label">用户名</label>
                <div class="col-sm-9">
                    <input type="text" name="name" class="form-control" id="inputEmail3"
                           value="${cookie.name.value}">
                </div>
            </div>
            <div class="form-group">
                <label for="inputPassword3" 
                class="col-sm-3 control-label">密&nbsp;&nbsp;&nbsp;码</label>
                <div class="col-sm-9">
                    <input type="password" name="password" 
                    class="form-control" id="inputPassword3">
                </div>
            </div>
             <div class="form-group">
                <label for="inputPassword3" class="col-sm-3 control-label">验证码</label>
                <div class="col-sm-5">
                    <input name="randomCode" class="form-control">

                </div>
                <div class="col-sm-4">

                    <img src="/randomCode" alt="验证码" id="randomCode" onclick="changeCode();"/>
                </div>
            </div> 
          <div class="form-group">
                <label for="inputPassword3" class="col-sm-3 control-label"></label>
                <div class="col-sm-9">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" name="rememberMe"
                                ${empty cookie.rememberMe.value?"":"checked='checked'"}> 记住账号
                        </label>
                    </div>
                </div>
            </div>    
            <div class="form-group">
                <label for="inputPassword3" class="col-sm-3 control-label"></label>
                <div class="col-sm-9">
                    <button type="submit" class="btn btn-default">登录</button>
                </div>
            </div>
        </form>
    </div>
</div>

<%--清楚session中的错误信息--%>
<%session.removeAttribute("errorMsg");%>
</body>
</html>

webapp/WEB-INF/views/product

input.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>叩丁狼教育-JavaWEB综合案例</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <%@include file="../common/header.jsp"%>
</head>
<body>

<div class="container " style="margin-top: 20px">
    <%@include file="../common/top.jsp"%>
    <br/>
    <br/>
    <div class="row">
        <div class="col-sm-3">
            <%@include file="../common/menu.jsp"%>
        </div>
        <div class="col-sm-9">
            <div class="row col-sm-10">
                <form class="form-horizontal" action="/product?cmd=saveOrUpdate" method="post" enctype="multipart/form-data" id="editForm">
                    <input type="hidden" value="${p.id}" name="id">
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品名称:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="productName" value="${p.productName}" placeholder="请输入商品的名称">
                        </div>
                    </div>
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品分类:</label>
                        <div class="col-sm-6">
                         <select name="dirId" class="form-control">
                            <option value="1"  ${p.dirId== 1 ? "selected='selected'" : "" } >鼠标</option>
                            <option value="2"  ${p.dirId== 2 ? "selected='selected'" : "" } >无线鼠标</option>
                            <option value="3"  ${p.dirId== 3 ? "selected='selected'" : "" } >有线鼠标</option>
                            <option value="4"  ${p.dirId== 4 ? "selected='selected'" : "" } >游戏鼠标</option>
                         </select>
                        </div>
                    </div>
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品售价:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="salePrice" value="${p.salePrice}" placeholder="请输入商品的售价">
                        </div>
                    </div>
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品供应商:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="supplier" value="${p.supplier}" placeholder="请输入商品的供应商">
                        </div>
                    </div>
                    
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品品牌:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="brand" value="${p.brand}" placeholder="请输入商品的品牌">
                        </div>
                    </div>
                    
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品折扣:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="cutoff" value="${p.cutoff}" placeholder="请输入商品的折扣">
                        </div>
                    </div>
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品成本:</label>
                        <div class="col-sm-6">
                        <input type="text" class="form-control" id="name" name="costPrice" value="${p.costPrice}" placeholder="请输入商品的成本">
                        </div>
                    </div> 
                    
                    <div class="form-group" >
                        <label for="name" class="col-sm-2 control-label">商品图片:</label>
                        <div class="col-sm-6">
                        <input type="file"    name="imagePath" >
                        </div>
                    </div> 
                    
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-6">
                            <button id="btn_submit" type="submit" class="btn btn-default">保存</button>
                            <button type="reset" class="btn btn-default">重置</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

list.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>叩丁狼教育-JavaWEB综合案例</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<%@include file="../common/header.jsp"%>

<script type="text/javascript">
        function goPage(currentPage) {
            //为表单中的currentPage输入框设值
            document.getElementById("currentPage").value = currentPage;
            //提交表单
            document.forms[0].submit();
        }
    </script>
</head>
<body>
    <form class="form-inline" id="searchForm" action="/product"
        method="post">
        <div class="container " style="margin-top: 20px">
            <%@include file="../common/top.jsp"%>
            <br /> <br />
            <div class="row">
                <div class="col-sm-3">
                    <%@include file="../common/menu.jsp"%>
                </div>
                <div class="col-sm-9">
                    <div class="row"></div>
                    <!--高级查询--->
                    <input type="hidden" name="currentPage" id="currentPage" />
                     关键字:<input
                        type="text" name="keyword" value="${qo.keyword }"> 
                    售价: <input
                        type="text" name="minPrice" value="${qo.minPrice }" /> 
                     - <input
                        type="text" name="maxPrice" value="${qo.maxPrice }"> <input
                        type="button" onclick="goPage(1);" value="查询">
                        <a href="/product?cmd=input" class="btn btn-success">添加</a>
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>商品名称</th>
                                <th>商品分类</th>
                                <th>商品售价</th>
                                <th>商品供应商</th>
                                <th>商品品牌</th>
                                <th>商品折扣</th>
                                <th>商品成本价</th>
                                <th>商品缩略图</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <c:forEach items="${result.data}" var="entity" varStatus="vs">
                            <tr>
                                <td>${vs.count}</td>
                                <td>${entity.productName}</td>
                                <td>${entity.dirName}</td>
                                <td>${entity.salePrice}</td>
                                <td>${entity.supplier}</td>
                                <td>${entity.brand}</td>
                                <td>${entity.cutoff}</td>
                                <td>${entity.costPrice}</td>
                                <td><img alt="图片失败" width="80px"  src="${entity.imagePath}"></td>
                                <td><a class="btn btn-info btn-xs"
                                    href="/product?cmd=input&id=${entity.id}"> <span
                                        class="glyphicon glyphicon-pencil"></span>编辑
                                </a> <a href="/product?cmd=delete&id=${entity.id}"
                                    class="btn btn-danger btn-xs"> <span
                                        class="glyphicon glyphicon-trash"></span>删除
                                </a></td>
                            </tr>
                        </c:forEach>
                    </table>
                    <div style="text-align: center;">
                        <a href="javascript:;" onclick="goPage(1)">首页</a> <a
                            href="javascript:;" onclick="goPage(${result.prevPage})">上一页</a>
                        <a href="javascript:;" onclick="goPage(${result.nextPage})">下一页</a>
                        <a href="javascript:;" onclick="goPage(${result.endPage})">尾页</a>
                        当前页: ${result.currentPage} / ${result.endPage} 共
                        ${result.totalCount} 条数据
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读