添加商品
1.功能截图
2.代码实现
web层
package com.itheima.web; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.itheima.domain.Product; import com.itheima.service.AdminProductListService; public class AdminAddProductServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); //1.获取数据 Map<String, String[]> properties = request.getParameterMap(); //2.封装数据 Product product = new Product(); try { BeanUtils.populate(product, properties); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //3.将product中未封装的属性封装,使其与数据库中的属性一一对应 product.setPid(UUID.randomUUID().toString()); product.setPimage("products/1/c_0001.jpg"); Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String pdate = format.format(date); product.setPdate(pdate); product.setPflag(0); AdminProductListService service = new AdminProductListService(); try { service.addProduct(product); } catch (SQLException e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath()+"/AdminProductListServlet"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }