一.增加资费图解分析

分析:完成此功能需要发送三个请求
1.点击浏览器界面的增加按钮,访问路径为/toAddCost.do,通过转发找到add.jsp,用jsp向浏览器做出响应跳转到增加界面
2.在增加界面单击保存后,访问路径为/addCost.do,然后调CostDao的save方法,传输Cost对象
3.重定向,显示查询界面
二.增加功能
1.打开增加资费界面
1.1在MainServlet类中增加toAddCost方法,转发到add.jsp
//打开增加资费
protected void toAddCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.getRequestDispatcher("WEB-INF/cost/add.jsp").forward(req, res);
}
1.2在重写的service方法里做路径判断
else if("/toAddCost.do".equals(path)) {
toAddCost(req,res);
}
1.3在src->main->webapp->WEB-INF->cost文件,创建add.jsp文件,并且把之前写好的静态页(fee_add)代码粘贴到add.jsp文件中
注:修改css文件的导入路径,图片img的导入路径,以及把find.jsp中的增加按钮的点击事件中的路径替换成toAddCost.do

2.保存增加的资费
2.1在CostDao中封装保存对象的save()方法,并在main方法中添加点假数据测试一波
public void save(Cost cost) {
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql =
"insert into cost_bao values("
+ "cost_seq.nextval,"
+ "?,?,?,?,'1',?,sysdate,null,?)";
PreparedStatement ps =
conn.prepareStatement(sql);
ps.setString(1, cost.getName());
//setInt,setDouble不允许传入null,
//但实际业务中该字段却是可能为null,
//并且数据库也支持为null,可以将
//这样的字段当做Object处理
ps.setObject(2, cost.getBaseDuration());
ps.setObject(3, cost.getBaseCost());
ps.setObject(4, cost.getUnitCost());
ps.setString(5, cost.getDescr());
ps.setString(6, cost.getCostType());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"增加资费失败", e);
} finally {
DBUtil.close(conn);
}
}
注:参数有10个,
第一个主键给序列,
第六个开通状态默认暂停,
第八个创建时间给系统时间,
第九个开通时间给null
public static void main(String[] args) {
CostDao dao = new CostDao();
Cost cost = new Cost();
cost.setName("包月");
//cost.setBaseDuration(660);
cost.setBaseCost(1200.0);
//cost.setUnitCost(0.6);
cost.setDescr("包月最爽");
cost.setCostType("1");
dao.save(cost);
}
2.2在重写的service方法里做路径判断,访问MainServlet
else if ("/addCost.do".equals(path)) {
addCost(req, res);
}
2.3增加资费数据在MainServlet类中增加addCost方法,保存数据后重定向到查询
// 增加资费数据
protected void addCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// 接收传入的参数
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String costType = req.getParameter("costType");
String baseDuration = req.getParameter("baseDuration");
String baseCost = req.getParameter("baseCost");
String unitCost = req.getParameter("unitCost");
String descr = req.getParameter("descr");
// 保存该数据
Cost c = new Cost();
c.setName(name);
c.setCostType(costType);
if (baseDuration != null && baseDuration.length() > 0) {
c.setBaseDuration(Integer.valueOf(baseDuration));
}
if (baseCost != null && baseCost.length() > 0) {
c.setBaseCost(Double.valueOf(baseCost));
}
if (unitCost != null && unitCost.length() > 0) {
c.setUnitCost(Double.valueOf(unitCost));
}
c.setDescr(descr);
CostDao dao = new CostDao();
dao.save(c);
// 重定向到查询
// 当前: /netctoss/addCost.do
// 目标: /netctoss/findCost.do
res.sendRedirect("findCost.do");
}
注:这里为了防止乱码产生,在接受传入参数之前设置编码
req.setCharacterEncoding("utf-8");
3.处理表单中的相应参数

网友评论