NETCTOSS项目(一)

项目分布结构:



一、dao包里面文件

package dao;

import entity.Admin;

public interface AdminDao {
	Admin findByCode(String code);
}
package dao;

import java.util.List;

import entity.Cost;

public interface CostDao {
	List<Cost> findAll();  //资费查询功能
	
	void save(Cost c);    //增加资费功能
	
	Cost findById(int id);
	
	void update(Cost c);  //修改资费
	
	void startCost(int id); //启用资费
	
    void deleteCost(int id);	//删除资费
    
    List<Cost> findByPage(int page,int size);//分页查询
    
    int findRows();    //查询数据的总行数
}
实现类

package dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import entity.Admin;
import util.DBUtil2;

public class AdminDoaImpl implements AdminDao,Serializable {

	public Admin findByCode(String code) {//根据帐号查找
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "SELECT * FROM admin_info WHERE admin_code=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, code);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){//若账号存在,否则返回null
				Admin a = createAdmin(rs);
				return a;
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("查找管理员失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
		return null;
	}

	//自动生成,供其他调用
	private Admin createAdmin(ResultSet rs) throws SQLException {
		Admin a = new Admin();
		a.setAdminId(rs.getInt("admin_id"));
		a.setAdminCode(rs.getString("admin_code"));
		a.setPassword(rs.getString("password"));
		a.setName(rs.getString("name"));
		a.setTelephone(rs.getString("telephone"));
		a.setEmail(rs.getString("email"));
		a.setEnrolldate(rs.getTimestamp("enrolldate"));
		return a;
	}

	public static void main(String[] args) {
		AdminDoaImpl dao = new AdminDoaImpl();
		Admin a = dao.findByCode("caocao");
		if(a != null){
			System.out.println(a.getAdminId());
			System.out.println(a.getTelephone());
		}else{
			System.out.println(a);//null
		}
		
	}
}
package dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.Cost;
import util.DBUtil2;

public class CostDaoImpl implements CostDao, Serializable {

	public List<Cost> findAll() {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "SELECT * FROM cost ORDER BY cost_id";
			Statement state = conn.createStatement();
			ResultSet rs = state.executeQuery(sql);
			List<Cost> list = new ArrayList<Cost>();
			while(rs.next()){
				Cost c = createCost(rs);//重构方法(封装)
				list.add(c);
			}
			return list;
		}catch(Exception e){
			//实际情况要记录日志--Log4j工具
			e.printStackTrace();
			//抛出异常-由调用者处理
			throw new RuntimeException("查询资费失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	/**
	 * Alt + Shift +M  提取方法的快捷键(先选中某代码片段)
	 */
	private Cost createCost(ResultSet rs) throws SQLException {
		Cost c = new Cost();
		c.setCostId(rs.getInt("cost_id"));
		c.setName(rs.getString("name"));
		c.setBaseDuration(rs.getInt("base_duration"));
		c.setBaseCost(rs.getDouble("base_cost"));
		c.setUnitCost(rs.getDouble("unit_cost"));
		c.setStatus(rs.getString("status"));
		c.setDescr(rs.getString("descr"));
		c.setCreatime(rs.getTimestamp("creatime"));
		c.setStartime(rs.getTimestamp("startime"));
		c.setCostType(rs.getString("cost_type"));
		return c;
	}
	
	//增加资费功能
	public void save(Cost c) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "INSERT INTO cost VALUES "
					+ "(cost_seq.nextval,?,?,?,?,1,?,sysdate,null,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, c.getName());
			/***
			 * ps.setInt()  ps.setDouble()只能传入基本类型,但在实际业务中确实有null,
			 * 而且数据库支持null,要用Object替换,当作对象来处理
			 */
			ps.setObject(2, c.getBaseDuration());
			ps.setObject(3, c.getBaseCost());
			ps.setObject(4, c.getUnitCost());
			ps.setString(5, c.getDescr());
			ps.setString(6, c.getCostType());
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("增加员工失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	
	//测试dao
	public static void main(String[] args) {
		CostDao dao = new CostDaoImpl();
		dao.deleteCost(203);
	}

	public Cost findById(int id) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "SELECT * FROM cost WHERE cost_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			Cost c = new Cost();
			if(rs.next()){
				return createCost(rs);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("查询数据库失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
		return null;//没有找到返回null
	}
	
	//修改资费
	public void update(Cost c) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "UPDATE cost SET "
					+ "name=?,base_duration=?,base_cost=?,unit_cost=?,cost_type=?,descr=? "
					+ "WHERE cost_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			//从Cost中获取的该属性可能为null,所以ps中使用Object
			ps.setString(1, c.getName());
			ps.setObject(2, c.getBaseDuration());
			ps.setObject(3, c.getBaseCost());
			ps.setObject(4, c.getUnitCost());
			ps.setString(5, c.getCostType());
			ps.setString(6, c.getDescr());
			ps.setObject(7, c.getCostId());
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("修改数据库失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	public void startCost(int id) {
		try{
			Connection conn = new DBUtil2().getConnection();
			String sql = "UPDATE cost SET status='0' WHERE cost_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("启用资费失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	public void deleteCost(int id) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "DELETE FROM cost WHERE cost_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("删除资费失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	//分页查询
	public List<Cost> findByPage(int page, int size) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = 
			"SELECT * FROM("+
			"SELECT ROWNUM rw,c.* FROM("+
			"SELECT * FROM cost ORDER BY cost_id) c"+
			") WHERE rw BETWEEN ? AND ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, (page-1)*size+1);
			ps.setInt(2, page*size);
			ResultSet rs = ps.executeQuery();
			List<Cost> list = new ArrayList<Cost>();
			while(rs.next()){
				Cost c = createCost(rs);
				list.add(c);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("分页查询失败",e);
		}finally{
			DBUtil2.closeConnection();
		}
	}
	//查询总行数
	public int findRows() {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "SELECT COUNT(*) c FROM cost";
			Statement state = conn.createStatement();
			ResultSet rs = state.executeQuery(sql);
			if(rs.next()){
				return rs.getInt(1);//return rs.getInt("c");
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("查询总行数失败", e);
		}finally{
			DBUtil2.closeConnection();
		}
		return 0;
	}
}


entity包
package entity;

import java.io.Serializable;
import java.sql.Timestamp;

public class Admin implements Serializable {

	private Integer adminId;
	private String adminCode;
	private String password;
	private String name;
	private String telephone;
	private String email;
	private Timestamp enrolldate;
	
	public Admin(){}

	public Integer getAdminId() {
		return adminId;
	}

	public void setAdminId(Integer adminId) {
		this.adminId = adminId;
	}

	public String getAdminCode() {
		return adminCode;
	}

	public void setAdminCode(String adminCode) {
		this.adminCode = adminCode;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Timestamp getEnrolldate() {
		return enrolldate;
	}

	public void setEnrolldate(Timestamp enrolldate) {
		this.enrolldate = enrolldate;
	}
	
	
}
package entity;

import java.io.Serializable;
import java.sql.Timestamp;
/**
 * 一共10个字段
 * java.sql.包下的日期类型:
 * java.sql.Date          年月日
 * java.sql.Time          时分秒
 * java.sql.Timestamp     年月日时分秒且带有小数    
 */
public class Cost implements Serializable {
	//主键
	private Integer costId;
	//资费名称
	private String name;
	//基本时长
	private Integer baseDuration;
	//基本费用
	private Double baseCost;
	//单位费用
	private Double unitCost;
	//状态(数据库是char)  0-开通    1-暂停
	private String status;
	//描述
	private String descr;
	//创建时间
	private Timestamp creatime;
	//开通时间
	private Timestamp startime;
	//资费类型(数据库是char)  1-包月  2-套餐  3-计时
	private String costType;
	
	public Cost(){}

	public Integer getCostId() {
		return costId;
	}

	public void setCostId(Integer costId) {
		this.costId = costId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getBaseDuration() {
		return baseDuration;
	}

	public void setBaseDuration(Integer baseDuration) {
		this.baseDuration = baseDuration;
	}

	public Double getBaseCost() {
		return baseCost;
	}

	public void setBaseCost(Double baseCost) {
		this.baseCost = baseCost;
	}

	public Double getUnitCost() {
		return unitCost;
	}

	public void setUnitCost(Double unitCost) {
		this.unitCost = unitCost;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getDescr() {
		return descr;
	}

	public void setDescr(String descr) {
		this.descr = descr;
	}

	public Timestamp getCreatime() {
		return creatime;
	}

	public void setCreatime(Timestamp creatime) {
		this.creatime = creatime;
	}

	public Timestamp getStartime() {
		return startime;
	}

	public void setStartime(Timestamp startime) {
		this.startime = startime;
	}

	public String getCostType() {
		return costType;
	}

	public void setCostType(String costType) {
		this.costType = costType;
	}
	
}


util包
package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * 使用连接池技术管理连接
 */
public class DBUtil2 {
	// 数据库连接池
	private static BasicDataSource ds;
	// 为不同线程管理连接
	private static ThreadLocal<Connection> tl;
	static {
		Properties p = new Properties();
		InputStream is = DBUtil2.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			p.load(is);
			is.close();
			String driver = p.getProperty("driver").trim();
			String url = p.getProperty("url").trim();
			String user = p.getProperty("user").trim();
			String password = p.getProperty("password").trim();
			int initsize = Integer.parseInt((p.getProperty("initsize")));
			int maxactive = Integer.parseInt(p.getProperty("maxactive"));
			long maxwait = Integer.parseInt(p.getProperty("maxwait"));
			// 初始化连接池
			ds = new BasicDataSource();
			// 设置驱动
			ds.setDriverClassName(driver);
			// 设置url
			ds.setUrl(url);
			// 设置数据库用户名
			ds.setUsername(user);
			// 设置数据库密码
			ds.setPassword(password);
			// 设置初始化连接数量
			ds.setInitialSize(initsize);
			// 设置连接池允许的最大连接数量
			ds.setMaxActive(maxactive);
			// 设置最大等待时间
			ds.setMaxWait(maxwait);
			//初始化线程本地
			tl = new ThreadLocal<Connection>();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("加载配置文件失败", e);
		}
	}
	
	/**
	 * 通过连接池获取一个空闲连接
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException{
		Connection conn = ds.getConnection();
		tl.set(conn);
		return conn;
	}
	/**
	 * 关闭数据库连接
	 */
	public static void closeConnection(){
		try {
			Connection conn = tl.get();
			if(conn != null){
				//恢复连接为自动提交事务
				conn.setAutoCommit(true);
				/**
				 * 通过连接池获取的此处的Connection的
				 * close()方法实际上并没有将连接关闭,
				 * 而是将该连接归还给连接池
				 */
				conn.close();
				tl.remove();//将该连接从线程本地删除
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//测试数据库连接正常
	public static void main(String[] args) {
		try {
			Connection conn = DBUtil2.getConnection();
			System.out.println(conn);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil2.closeConnection();
		}
	}
}
package util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public final class ImageUtil {
	
	// 验证码字符集
	private static final char[] chars = { 
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
		'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
	// 字符数量
	private static final int SIZE = 4;
	// 干扰线数量
	private static final int LINES = 5;
	// 宽度
	private static final int WIDTH = 80;
	// 高度
	private static final int HEIGHT = 40;
	// 字体大小
	private static final int FONT_SIZE = 30;

	/**
	 * 生成随机验证码及图片
	 */
	public static Object[] createImage() {
		StringBuffer sb = new StringBuffer();
		// 1.创建空白图片
		BufferedImage image = new BufferedImage(
			WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		// 2.获取图片画笔
		Graphics graphic = image.getGraphics();
		// 3.设置画笔颜色
		graphic.setColor(Color.LIGHT_GRAY);
		// 4.绘制矩形背景
		graphic.fillRect(0, 0, WIDTH, HEIGHT);
		// 5.画随机字符
		Random ran = new Random();
		for (int i = 0; i <SIZE; i++) {
			// 取随机字符索引
			int n = ran.nextInt(chars.length);
			// 设置随机颜色
			graphic.setColor(getRandomColor());
			// 设置字体大小
			graphic.setFont(new Font(
				null, Font.BOLD + Font.ITALIC, FONT_SIZE));
			// 画字符
			graphic.drawString(
				chars[n] + "", i * WIDTH / SIZE, HEIGHT / 2);
			// 记录字符
			sb.append(chars[n]);
		}
		// 6.画干扰线
		for (int i = 0; i < LINES; i++) {
			// 设置随机颜色
			graphic.setColor(getRandomColor());
			// 随机画线
			graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
					ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
		}
		// 7.返回验证码和图片
		return new Object[]{sb.toString(), image};
	}

	/**
	 * 随机取色
	 */
	public static Color getRandomColor() {
		Random ran = new Random();
		Color color = new Color(ran.nextInt(256), 
				ran.nextInt(256), ran.nextInt(256));
		return color;
	}
	
	public static void main(String[] args) throws IOException {
		Object[] objs = createImage();
		BufferedImage image = 
			(BufferedImage) objs[1];
		// /home/soft01/1.png
		OutputStream os = 
			new FileOutputStream("d:/1.png");
		ImageIO.write(image, "png", os);
		os.close();
	}

}
数据库配置文件:config.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=jsd161102
initsize=1
maxactive=1
maxwait=5000


web包

过滤器:

package web;

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;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		//从session中尝试获取帐号
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse)res;
		//有三个请求不需要过滤,排除他们
		String[] path = new String[]{"/toLogin.do","/login.do","/createImg.do"};
		//当前路径
		String sp = request.getServletPath();
		//若当前路径是这三个路径之一,则不必过滤,请求继续执行
		for(String s : path){
			if(s.equals(sp)){
				chain.doFilter(request, response);
				return;
			}
		}
		
		HttpSession session = request.getSession();
		String adminCode = (String) session.getAttribute("adminCode");
		//根据帐号判断是否已经登录
		if(adminCode == null){
			response.sendRedirect("/netctoss/toLogin.do");
		}else{
			chain.doFilter(request, response);//传入req,res都可以
		}

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}


Servlet主程序:

package web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.AdminDoaImpl;
import dao.CostDao;
import dao.CostDaoImpl;
import entity.Admin;
import entity.Cost;
import util.ImageUtil;

public class MainServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//获取请求路径
		String path = req.getServletPath();
		//根据路径处理规范
		if("/findCost.do".equals(path)){//查询资费
			findCost(req,res);
		}else if("/toAddCost.do".equals(path)){//打开增加资费页面
			toAddCost(req,res);
		}else if("/addCost.do".equals(path)){//增加资费
			addCost(req,res);
		}else if("/toUpdateCost.do".equals(path)){//打开修改资费页面
			toUpdateCost(req,res);
		}else if("/updateCost.do".equals(path)){  //修改资费
			updateCost(req,res);
		}else if("/toLogin.do".equals(path)){     //打开登录页面
			toLogin(req,res);
		}else if("/login.do".equals(path)){			//登录
			login(req,res);
		}else if("/toIndex.do".equals(path)){       //主页              
			toIndex(req,res);
		}else if("/startCost.do".equals(path)){    //启用资费
			startCost(req,res);
		}else if("/deleteCost.do".equals(path)){    //删除资费
			deleteCost(req,res);
		}else if("/createImg.do".equals(path)){     //创建验证码图片
			createImg(req,res);
		}else if("/logout.do".equals(path)){          //退出登录
			logout(req,res);
		}else{
			throw new RuntimeException("查无此页");
		}
	}
	
	//退出登录     /logout.do
	protected void logout(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//销毁session 重定向到登录页面
		HttpSession session = req.getSession();
		session.invalidate();
		res.sendRedirect("toLogin.do");
	}
	
	//生成验证码    /createImg.do
	protected void createImg(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//生成验证码及图片
		Object[] obj = ImageUtil.createImage();
		//将验证码存入sesssion
		HttpSession session = req.getSession();
		session.setAttribute("imgcode", obj[0]);//验证码
		//将图片输出给浏览器
		res.setContentType("image/png");
		//获取输出流,该流由服务器自动创建,输出目标指向当前访问的浏览器
		OutputStream os = res.getOutputStream();
		BufferedImage image = (BufferedImage) obj[1];
		ImageIO.write(image, "png", os);
		os.close();
	}
	
	//删除资费    /deleteCost.do
	protected void deleteCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//获取参数--没有中文
		int id = Integer.parseInt(req.getParameter("id"));
		//处理业务
		new CostDaoImpl().deleteCost(id);
		//从定向到查询页面
		res.sendRedirect("findCost.do");
	}
	
	//启用资费     /startCost.do
	protected void startCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//接受参数(由于没有中文,不用设置字符集)
		int id = Integer.parseInt(req.getParameter("costId"));
		//处理业务--修改状态
		new CostDaoImpl().startCost(id);
		//从定向到查询页面
		res.sendRedirect("findCost.do");
	}
	
	//登录验证       /login.do   判断帐号密码
	protected void login(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//接受参数(由于没有中文,不用设置字符集)
		String adminCode = req.getParameter("adminCode");
		String password = req.getParameter("password");
		String code = req.getParameter("code");//接收验证码
		HttpSession session = req.getSession();
		String imgcode = (String)session.getAttribute("imgcode");
		if(code == null || !code.equalsIgnoreCase(imgcode)){
			req.setAttribute("error", "验证码错误");
			req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
			return;//后面不用再执行dao,新能更好
		}	
		//帐号密码验证
		Admin a = new AdminDoaImpl().findByCode(adminCode);
		if(a == null){
			//帐号错误,转发到登录页面
			req.setAttribute("error", "账号错误");
			req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
		}else if(!a.getPassword().equals(password)){
			//密码错误
			req.setAttribute("error", "密码错误");
			req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
		}else{
			//检查成功,将帐号存入cookie,供其他页面调用,然后从定向主页,
			Cookie c = new Cookie("adminCode",adminCode);
			res.addCookie(c);//发送给浏览器
			//考虑是否有中文,是否需要存硬盘,是否需要改变有效路径
			c.setPath(req.getContextPath());
			//利用session存入账号
			session.setAttribute("adminCode", adminCode);
			//String url = res.encodeRedirectURL("toIndex.do");//禁用cookie后的重定向
			res.sendRedirect("toIndex.do");
		}
	}

	//打开登录页面     /toLogin.do
	protected void toLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res);
	}

	//打开主页面     /toIndex.do
	protected void toIndex(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.getRequestDispatcher("WEB-INF/main/index.jsp").forward(req, res);
	}

	//修改资费       /updateCost.do
	protected void updateCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//接收数据
		req.setCharacterEncoding("utf-8");
		String costId = req.getParameter("costId");
		String name = req.getParameter("name");
		String costType = req.getParameter("costType");
		//baseDuration  baseCost  unitCost 根据业务要求时可能为""空字符串
		String baseDuration = req.getParameter("baseDuration");
		String baseCost = req.getParameter("baseCost");
		String unitCost = req.getParameter("unitCost");
		String descr = req.getParameter("descr");
		//System.out.println("获取baseDuration:"+baseDuration);  该三个值可能为""
		//System.out.println("获取baseCost:"+baseCost);
		//System.out.println("获取unitCost:"+unitCost);
		//给属性赋值的时候,若为空字符串就不赋值,让其等于默认值null
		Cost c = new Cost();
		c.setCostId(Integer.parseInt(costId));
		c.setName(name);
		c.setCostType(costType);
		if(baseDuration != null && !baseDuration.equals("")){
			c.setBaseDuration(new Integer(baseDuration));
		}
		if(baseCost != null && !baseCost.equals("")){
			c.setBaseCost(new Double(baseCost));
		}
		if(unitCost != null && !unitCost.equals("")){
			c.setUnitCost(new Double(unitCost));
		}
		c.setDescr(descr);
		//System.out.println("实体baseDuration:"+c.getBaseDuration()); 该三个值可能为null
		//System.out.println("实体baseCost:"+c.getBaseCost());   
		//System.out.println("实体unitCost:"+c.getUnitCost());
		
		//处理业务
		new CostDaoImpl().update(c);
		//从定向
		res.sendRedirect("findCost.do");
	}

	//打开修改资费页面      /toUpdateCost.do
	protected void toUpdateCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//接收参数(路径传参)  location.href='toUpdateCost.do?id=${c.costId}';
		int id = Integer.parseInt(req.getParameter("id"));
		Cost cost = new CostDaoImpl().findById(id);
		//转发
		req.setAttribute("cost", cost);
		req.getRequestDispatcher("WEB-INF/cost/update.jsp").forward(req, res);
	}
	
	//查询资费    /findCost.do
	protected void findCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//获取请求参数
		String page = req.getParameter("page");
		if(page == null || page.equals("")){
			page = "1";
		}
		//获取常量
		String size = getServletContext().getInitParameter("size");
		//查询资费(这一页的资费情况)
		CostDao dao = new CostDaoImpl();
		List<Cost> list = 
				dao.findByPage(Integer.parseInt(page), Integer.parseInt(size));
		//将查询的数据计算总行数
		int rows = dao.findRows();
		int total = rows/Integer.parseInt(size);//到总页数
		if(rows%Integer.parseInt(size) != 0){//多了一页
			total++;
		}
		//转发到jsp
		req.setAttribute("costs", list);
		req.setAttribute("total", total);
		req.setAttribute("page", page);
		//当前:/netctoss/findCost.do    目标:/netctoss/WEB-INF/cost/find.jsp
		req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res);
	}
	
	//打开增加资费页面    /toAddCost.do
	protected void toAddCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.getRequestDispatcher("WEB-INF/cost/add.jsp").forward(req, res);
	}

	//增加资费         /addCost.do
	protected void addCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		//获取请求参数
		String name = req.getParameter("name");
		String costType = req.getParameter("costType");
		//baseDuration  baseCost  unitCost如没有输入则为空字符串,不用给该属性赋值,让其为null
		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);
		//由于业务类型的不同可能该字段readonly,不能输入,获取道德String为""空字符串
		if(baseDuration != null && !baseDuration.equals("")){
			c.setBaseDuration(new Integer(baseDuration));
		}
		if(baseCost != null && !baseCost.equals("")){
			c.setBaseCost(new Double(baseCost));
		}
		if(unitCost != null && !unitCost.equals("")){
			c.setUnitCost(new Double(unitCost));
		}
		c.setDescr(descr);
		CostDao dao = new CostDaoImpl();
		dao.save(c);
		//从定向到查询资费页面
		res.sendRedirect("findCost.do");
	}
}


  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值