分享

ProdAddServlet

 金银宝100 2017-12-12
package com.tedu.jt.web.backend;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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

import com.tedu.jt.utils.JDBCUtils;

/**
 * 处理商品添加请求
 */
public class ProdAddServlet
extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException {
// 0.处理乱码(在过滤器已处理!)
// >>请求参数乱码(POST)
//request.setCharacterEncoding("utf-8");
// >>响应正文乱码
//response.setContentType("text/html;charset=utf-8");

// 1.获取商品信息
String name = request
.getParameter("name");
String category = request
.getParameter("category");
double price = Double.parseDouble(
request.getParameter("price"));
int pnum = Integer.parseInt(request
.getParameter("pnum"));
String description = request
.getParameter("description");

// 2.将商品信息保存到数据库中
addProd(name, category, price, pnum,
description);

// 3.提示用户商品添加成功
response.getWriter()
.write("<h1 style='color:red;"
+ "text-align:center;'>");
response.getWriter()
.write("商品添加成功, 3秒之后将"
+ "会跳转到商品列表页面...");
response.getWriter().write("</h1>");

// 4.定时刷新到ProdListServlet查询所有的商品
response.setHeader("Refresh",
"3;url="+request.getContextPath()
+ "/ProdListServlet");
}

/**
 * 将商品信息保存到数据库中
 * 
 * @param name
 * @param category
 * @param price
 * @param pnum
 * @param description
 */
private void addProd(String name,
String category, double price,
int pnum, String description) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.获取连接(从连接池中获取一个连接对象)
conn = JDBCUtils.getConn();
//2.创建sql语句
String sql = "insert into "
+ "product values(null,"
+ "?,?,?,?,?)";
//3.获取传输器
ps = conn.prepareStatement(sql);
//4.设置sql参数
ps.setString(1, name);
ps.setString(2, category);
ps.setDouble(3, price);
ps.setInt(4, pnum);
ps.setString(5, description);
//5.执行sql
ps.executeUpdate();
} catch (Exception e) {
System.out.println("商品添加失败!!");
e.printStackTrace();
throw new RuntimeException(
"商品添加失败!!");
} finally{
/* 6.释放资源(如果使用了连接池技术,调用
* conn.close方法是将连接对象还回连接池中)
*/
JDBCUtils.close(conn, ps, rs);
}
}

protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException {
doGet(request, response);
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多