文章目录
项目结构
jar包
数据库dusk
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(50) DEFAULT NULL,
`dir_id` bigint(11) DEFAULT NULL,
`salePrice` double(10,2) DEFAULT NULL,
`supplier` varchar(50) DEFAULT NULL,
`brand` varchar(50) DEFAULT NULL,
`cutoff` double(2,2) DEFAULT NULL,
`costPrice` double(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
DAO实现类ProductDAOImpl
public class ProductDAOImpl implements IProductDAO<Product> {
private String getStatement(String id) {
return "com.dusk.mapper.ProductMapper." + id;
}
@Override
public void save(Product t) {
// TODO Auto-generated method stub
//获取sessionduixiang
SqlSession session = MyBatisUtil.getSession();
//执行操作
session.insert(getStatement("save"),t);
//提交事务
session.commit();
//关闭事务
session.close();
}
@Override
public void update(Product t) {
// TODO Auto-generated method stub
SqlSession session = MyBatisUtil.getSession();
session.update(getStatement("update"), t);
session.commit();
session.close();
}
@Override
public void delete(Long id) {
// TODO Auto-generated method stub
SqlSession session = MyBatisUtil.getSession();
session.delete(getStatement("delete"),id);
session.commit();
session.close();
}
@Override
public Product get(Long id) {
// TODO Auto-generated method stub
SqlSession session = MyBatisUtil.getSession();
Product product = session.selectOne(getStatement("get"), id);
session.commit();
session.close();
return product;
}
@Override
public List<Product> list() {
// TODO Auto-generated method stub
SqlSession session = MyBatisUtil.getSession();
List<Product> list = session.selectList(getStatement("list"));
session.commit();
session.close();
return list;
}
}
DAO接口IProductDAO.java
public interface IProductDAO <T>{
void save(T t);
void update(T t);
void delete(Long id);
T get(Long id);
List<T> list();
}
实体类Product.java
@Setter@Getter@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private Long id;
private String productName;
private Long dir_id;
private Double salePrice;
private String supplier;
private String brand;
private Double cutoff;
private Double costPrice;
}
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="com.dusk.mapper.ProductMapper">
<insert id="save" parameterType="com.dusk.domain.Product" useGeneratedKeys="true" keyProperty="true">
insert product
(productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)
values(#{productName},#{dir_id},#{salePrice},
#{supplier},#{brand},#{cutoff},#{costPrice})
</insert>
<update id="update" parameterType="Product">
update product set
productName=#{productName},dir_id=#{dir_id},salePrice=#{salePrice},
supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice}
where id=#{id}
</update>
<delete id="delete" parameterType="long">
delete from product where id = #{id}
</delete>
<select id="get" parameterType="long" resultType="com.dusk.domain.Product">
select * from product where id = #{id}
</select>
<select id="list" resultType="com.dusk.domain.Product">
select * from product
</select>
</mapper>
测试类App
public class App {
IProductDAO<Product> dao = new ProductDAOImpl();
@Test
public void testSave() throws Exception {
Product product = new Product(null,"欧西里斯.天空龙",2L,5000D,"YXW","YXW",0.8,2500D);
dao.save(product);
}
@Test
public void testUpdate() throws Exception {
Product product = new Product(22L,"欧贝利斯科.巨神兵",2L,5000D,"YXW","YXW",0.8,2500D);
dao.update(product);
}
@Test
public void testDelete() throws Exception {
dao.delete(23L);
}
@Test
public void testGet() throws Exception {
Product product = dao.get(22L);
System.out.println(product);
}
@Test
public void testList() throws Exception {
List<Product> list = dao.list();
for (Product product : list) {
System.out.println(product);
}
}
}
MyBatis工具类
public class MyBatisUtil {
private MyBatisUtil() {}
//SessionFactory工厂对象
private static SqlSessionFactory factory;
static {
try {
//根据Resource的getResourceASStream获取方法
InputStream in = Resources.getResourceAsStream("mybatis.xml");
//创建SqlSessinFactoryBuilder()的build();获得SqlSessionFactory对象
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession() {
//根据工厂的openSession方法获取SqlSession对象
//org.apache.ibatis.session.defaults.DefaultSqlSession@60c6f5b
SqlSession session = factory.openSession();
return session;
}
}
String工具类StringUtil
public class StringUtil {
private StringUtil() {}
public static boolean hasLength(String value) {
return value != null && ! "".equals(value.trim());
}
}
Servlet类ProdutctServlet.java
@WebServlet("/product")
public class ProdutctServlet extends HttpServlet {
IProductDAO<Product> dao = new ProductDAOImpl();
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/heml;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("ninii");
String cmd = req.getParameter("cmd");
if ("delete".equals(cmd)) {
delete(req, resp);
} else if ("update".equals(cmd)) {
update(req, resp);
} else if ("saveOrUpdate".equals(cmd)) {
saveOrUpdate(req, resp);
} else {
list(req, resp);
}
}
private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
if (StringUtil.hasLength(id)) {
dao.delete(Long.valueOf(id));
}
resp.sendRedirect("/product");
}
private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
if (StringUtil.hasLength(id)) {
//编辑
Product product = dao.get(Long.valueOf(id));
req.setAttribute("product", product);
}
req.getRequestDispatcher("/WEB-INF/views/product/update.jsp").forward(req, resp);;
}
private void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
String productName = req.getParameter("productName");
String dir_id = req.getParameter("dir_id");
String salePrice = req.getParameter("salePrice");
String supplier = req.getParameter("supplier");
String brand = req.getParameter("brand");
String cutoff = req.getParameter("cutoff");
String costPrice = req.getParameter("costPrice");
if (
StringUtil.hasLength(productName) &&
StringUtil.hasLength(dir_id) &&
StringUtil.hasLength(salePrice) &&
StringUtil.hasLength(supplier) &&
StringUtil.hasLength(brand) &&
StringUtil.hasLength(cutoff) &&
StringUtil.hasLength(costPrice)
) {
Long dir_idL = Long.valueOf(dir_id);
Double salePriceD = Double.valueOf(salePrice);
Double cutoffD = Double.valueOf(cutoff);
Double costPriceD = Double.valueOf(costPrice);
Product product = new Product(null,productName,dir_idL,salePriceD,supplier,brand,cutoffD,costPriceD);
if (StringUtil.hasLength(id)) {
product.setId(Long.valueOf(id));
dao.update(product);
}else {
dao.save(product);
}
resp.sendRedirect("/product");
}
}
private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
List<Product> list = dao.list();
req.setAttribute("products", list);
req.getRequestDispatcher("/WEB-INF/views/product/list.jsp").forward(req, resp);
}
}
连接数据库资源文件druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///dusk
username=root
password=admin
MyBatis配置文件log4j.properties
log4j.rootLogger=ERROR,stdout
log4j.logger.dusk.mapper=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mapper管理文件mybatis.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="druid.properties" />
<typeAliases>
<package name="com.dusk.domain" />
</typeAliases>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC" />
<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="com/dusk/domain/ProductMapper.xml" />
</mappers>
</configuration>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" width="60%">
<tr>
<td colspan="9"><a href="/product?cmd=update">添加</a></td>
</tr>
<tr>
<th>编号</th>
<th>名称</th>
<th>产品类型</th>
<th>销售价</th>
<th>生产商</th>
<th>品牌</th>
<th>折扣</th>
<th>成本价</th>
<th>操作</th>
</tr>
<c:forEach items="${products}" var='p'>
<tr>
<td>${p.id }</td>
<td>${p.productName }</td>
<td>${p.dir_id}</td>
<td>${p.salePrice }</td>
<td>${p.supplier }</td>
<td>${p.brand }</td>
<td>${p.cutoff }</td>
<td>${p.costPrice }</td>
<td><a href="/product?cmd=delete&id=${p.id }">删除</a>|
<a href="/product?cmd=update&id=${p.id }">编辑</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p><a>${empty product ? "添加" : "编辑"}信息</a></p>
<form action="/product?cmd=saveOrUpdate" method="post">
<p>编号<input type="hidden" name="id" value="${product.id}"></p>
<p>名称<input type="text" name="productName" value="${product.productName}"></p>
<p>分类<input type="text" name="dir_id" value="${product.dir_id}"></p>
<p>销售价格<input type="text" name="salePrice" value="${product.salePrice}"></p>
<p>品牌<input type="text" name="supplier" value="${product.supplier}"></p>
<p>生产商<input type="text" name="brand" value="${product.brand}"></p>
<p>折扣<input type="text" name="cutoff" value="${product.cutoff}"></p>
<p>成本价<input type="text" name="costPrice" value="${product.costPrice}"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="false">
<!-- 统一处理项目异常 -->
<error-page>
<!-- 错误状态码:针对一类异常统一处理 -->
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
</web-app>