JAVA跳转页面jsp_java

JAVA跳转页面jsp_List_02

先上效果图如上

 四个javabean,第一个Emp.java

package bean;

import java.util.Date;

public class Emp {
	private int empno;
	private String ename;
	private String job;
	private int mgr;
	private Date hireDate;
	private float sal;
	private float comm;
	private int deptno;
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public int getMgr() {
		return mgr;
	}
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}
	public Date getHireDate() {
		return hireDate;
	}
	public void setHireDate(Date hireDate) {
		this.hireDate = hireDate;
	}
	public float getSal() {
		return sal;
	}
	public void setSal(float sal) {
		this.sal = sal;
	}
	public float getComm() {
		return comm;
	}
	public void setComm(float comm) {
		this.comm = comm;
	}
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	@Override
	public String toString() {
		return "Emp [ename=" + ename + ", job=" + job + ", sal=" + sal + "]";
	}
	
}

第二个  EmpTableModel.java

package bean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import dao.EmpDao;

public class EmpTableModel extends AbstractTableModel{
//	private String[][] data = {
//			{"张三","22","男"},
//			{"张三","22","男"},
//			{"张三","22","男"}
//	};
	private int number = 5;
//	//表头
	private String[] titles = {"员工姓名","职务","入职时间","薪资"};
	private List<Emp> list = new EmpDao().getEmps(0,number);
	
//	临时的集合,存储用户更改的信息
	private List<Emp> tempList = new ArrayList<>();
	
	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String[] getTitles() {
		return titles;
	}

	public void setTitles(String[] titles) {
		this.titles = titles;
	}

	public List<Emp> getList() {
		return list;
	}

	public void setList(List<Emp> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "EmpTableModel [number=" + number + ", titles="
				+ Arrays.toString(titles) + ", list=" + list + "]";
	}

	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return list.size();
	}
	
	

	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return titles.length;
	}
	
//	重写生成列标题的方法
	@Override
	public String getColumnName(int column) {
		return titles[column];
	}
	
//	重写单元格是否可以编辑的方法
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		// TODO Auto-generated method stub
		return true;
	}
	
//	当单元格被编辑时,用户输入的数据会传递到此方法
	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		//用户在页面上做的更改,默认不会保留,只有将用户的更改作用到list上
		//界面才会变化
		//根据传入行索引,找到list中对应的Emp对象
		Emp emp = list.get(rowIndex);
		
//		通过判断列,来绝对更改对象哪个属性
		switch (columnIndex) {
		case 0:
			emp.setEname((String) aValue);
			break;
		case 1:
			emp.setJob((String)aValue);
			break;
		case 2:
//			此处传递过来的日期是字符串类型,无法强制转换为日期
//			字符串 --》 日期   '1999-02-03' -> Date对象
			
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date date = simpleDateFormat.parse((String) aValue);
				emp.setHireDate(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			break;
		case 3:
			float sal = Float.parseFloat((String) aValue);
			emp.setSal(sal);	
			break;
		}
		//this.fireTableCellUpdated(rowIndex, columnIndex);  
		/*
		 * 	两个问题
		 * 		用户如果更改了新增的数据,会调用此方法
		 * 		用户如果更改了已有的数据,会调用此方法
		 * 	1、更新数据库的时候,需要判断是插入还是更新
		 *  2、 当用户更改了一个单元格的内容,此方法就会调用,
		 *     此方法调用的过于频繁,不应该在此处直接访问数据库
		 * 
		 */
//		用户如果更新了某条记录的值,我们就把对应的emp对象装入到临时的list中
		if(!tempList.contains(emp)){
			tempList.add(emp);
		}
		
	}

	//此方法会调用多次,每次传入一个行索引和列索引,索引从0开始
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Emp emp = list.get(rowIndex);
		switch (columnIndex) {
		case 0:
			return emp.getEname();
		case 1:
			return emp.getJob();
		case 2:
			return emp.getHireDate();
		case 3:
			return emp.getSal();			
		}
		return null;
	}
	
//	添加一行
	public void addRow() {
		Emp emp = new Emp();
//		为了区分哪些员工是新添加的,将员工的员工号临时改为-1
		emp.setEmpno(-1);
		list.add(emp);
	}

	public void save() {
		for (Emp emp : tempList) {
//			需要判断是要做添加还是做更新
			if(emp.getEmpno() == -1){
				//添加
				new EmpDao().add(emp);
			}else{
				//更新
				new EmpDao().update(emp);
			}
		}
//		清空临时表,保证数据不会被重复添加
		tempList.clear();
	}
	
	//删除
	public void delete(int index) {
		//获取到对应的员工对象
		Emp emp = list.get(index);
		list.remove(index);
		//调用dao的方法删除数据
		new EmpDao().delete(emp.getEmpno());
	}
	
	
	//查询
	public List<Emp> find(String findname){
		List<Emp> yesfind=new EmpDao().search(findname);
		return yesfind;
	}

	//查找部门
	public List<Emp> bumenfind(){
		List<Emp> bumenfind=new EmpDao().bumenfind();
		return bumenfind;
	}
	
	//查找所选部门的各项参数
	public List<Emp>bumenvalue(String bumenvalue){
		List<Emp>bumenvalues=new EmpDao().bumenvalue(bumenvalue);
		return bumenvalues;
	}

}

第三个FindTable.java

package bean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import dao.EmpDao;
import view.MainView;

public class FindTable extends AbstractTableModel {
	//表头
	private String[] titles = {"员工姓名","职务","入职时间","薪资"};
	private List<Emp> list ;
	
	
	public String[] getTitles() {
		return titles;
	}

	public void setTitles(String[] titles) {
		this.titles = titles;
	}

	public List<Emp> getList() {
		return list;
	}

	public void setList(List<Emp> list) {
		this.list = list;
	}

	
	
	
//	重写生成列标题的方法
	@Override
	public String getColumnName(int column) {
		
		return titles[column];
	}
	
	
	
	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return titles.length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		// TODO Auto-generated method stub
		Emp emp = list.get(rowIndex);
		switch (columnIndex) {
		case 0:
			System.out.println("get到了个屁"+emp.getEname());
			return emp.getEname();
		case 1:
			return emp.getJob();
		case 2:
			return emp.getHireDate();
		case 3:
			return emp.getSal();			
		}
		return null;
	}
	
	
//	当单元格被编辑时,用户输入的数据会传递到此方法
	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		//用户在页面上做的更改,默认不会保留,只有将用户的更改作用到list上
		//界面才会变化
		//根据传入行索引,找到list中对应的Emp对象
		Emp emp = list.get(rowIndex);
		
//		通过判断列,来绝对更改对象哪个属性
		switch (columnIndex) {
		case 0:
			emp.setEname((String) aValue);
			System.out.println("设置了"+aValue);
			break;
		case 1:
			emp.setJob((String)aValue);
			break;
		case 2:
//			此处传递过来的日期是字符串类型,无法强制转换为日期
//			字符串 --》 日期   '1999-02-03' -> Date对象
			
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date date = simpleDateFormat.parse((String) aValue);
				emp.setHireDate(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			break;
		case 3:
			float sal = Float.parseFloat((String) aValue);
			emp.setSal(sal);	
			break;
		}
		
		/*
		 * 	两个问题
		 * 		用户如果更改了新增的数据,会调用此方法
		 * 		用户如果更改了已有的数据,会调用此方法
		 * 	1、更新数据库的时候,需要判断是插入还是更新
		 *  2、 当用户更改了一个单元格的内容,此方法就会调用,
		 *     此方法调用的过于频繁,不应该在此处直接访问数据库
		 * 
		 */
//		用户如果更新了某条记录的值,我们就把对应的emp对象装入到临时的list中
		
		
	}
	
	
	public void loadList(List<Emp>emps){
		this.list=MainView.getYesfind();
	}

}

最后一个bean文件 User.java

package bean;

public class User {
	private int id;
	private String username;
	private String password;
	private String phone;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}

}

两个dao包中的数据库操作类,第一个EmpDao.java

package dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import bean.Emp;
import utils.JDBCUtils;
public class EmpDao {
	/*
	 *   查询客户
	 *   删除客户
	 *   更新客户
	 *   插入客户
	 */
	public List<Emp> getEmps() {
		
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
		String sql = "select * from emp";
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			List<Emp> list = (List<Emp>)queryRunner.query(connection, sql,new BeanListHandler(Emp.class));
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
	}
	public List<Emp> getEmps(int start,int number) {
		
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
//		                                     start number
		String sql = "select * from emp limit ?,?";
		Object[] pramas = {start,number};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			List<Emp> list = (List<Emp>)queryRunner.query(connection, sql,new BeanListHandler(Emp.class),pramas);
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
	}
	
//	查询数据的总条数
	public int getCount() {
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
//		                                     start number
		String sql = "select count(empno) from emp";
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 * ScalarHandler: 处理单个值,比如记录的个数
		 */
		try { 
			long count = (long)queryRunner.query(connection, sql,new ScalarHandler());
			return (int) count;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return 0;
	}
	public void add(Emp emp) {
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
//		                                     start number
		String sql = "insert into emp (ename,job,hiredate,sal) values(?,?,?,?)";
		Object[] params = {emp.getEname(),emp.getJob(),emp.getHireDate(),emp.getSal()};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 * ScalarHandler: 处理单个值,比如记录的个数
		 */
		try { 
			queryRunner.update(connection, sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		
	}
	public void update(Emp emp) {
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
//		                                     start number
		String sql = "update emp set ename = ?,job = ?,hiredate = ?,sal = ? where empno = ?";
		Object[] params = {emp.getEname(),emp.getJob(),emp.getHireDate(),emp.getSal(),emp.getEmpno()};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 * ScalarHandler: 处理单个值,比如记录的个数
		 */
		try { 
			queryRunner.update(connection, sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		
	}
	public void delete(int empno) {
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
//		                                     start number
		String sql = "delete from emp where empno = ?";
		Object[] params = {empno};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 * ScalarHandler: 处理单个值,比如记录的个数
		 */
		try { 
			queryRunner.update(connection, sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
	}
	
	
	public List<Emp> search(String findname){
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
		String sql = "select * from emp where ename = ?";
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		Object[] pramas = {findname};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			List<Emp> list = (List<Emp>)queryRunner.query(connection, sql,new BeanListHandler(Emp.class),pramas);
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
		
	}
	
	
	public List<Emp> bumenfind(){
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
		String sql = "select distinct(job) from emp ";
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		//Object[] pramas = {findname};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			List<Emp> list = (List<Emp>)queryRunner.query(connection, sql,new BeanListHandler(Emp.class));
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
		
	}
	
	
	public List<Emp> bumenvalue(String bumenvalue){
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
		String sql = "select * from emp where job=?";
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		Object[] pramas = {bumenvalue};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			List<Emp> list = (List<Emp>)queryRunner.query(connection, sql,new BeanListHandler(Emp.class),pramas);
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
		
	}
}

第二个UserDao.java首页操作登陆的

package dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import bean.User;
import utils.JDBCUtils;

/*
 * 	此类负责用户相关的操作
 * 		查询用户
 * 		插入用户
 *      更新用户
 *      删除用户
 */
public class UserDao {
	
	//	根据用户名和密码查询用户信息
	public User findUser(String username,String password) {
		QueryRunner queryRunner = new QueryRunner();
		Connection connection = JDBCUtils.getConnection();
		String sql = "select * from user where username = ? and password = ?";
		Object[] params = {username,password};
		/*
		 * BeanListHandler:将结果集封装为list集合
		 * BeanHandler:将结果集中的第一条记录封装为对象
		 */
		try {
			User user = (User)queryRunner.query(connection, sql,new BeanHandler(User.class),params);
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.release(null, null, connection);
		}
		return null;
	}
}

utils包下的JDBCUtils.java连接数据库

package utils;

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

import com.mysql.jdbc.Statement;

public class JDBCUtils {
	private static Properties properties;
	//注册驱动
	static{
		//静态代码块当类被加载的时候会执行,只要JDBCUtils类被第一次用到,JDBCUtils类就会被加载到内存,
		//静态代码块就会执行,驱动会被注册
		try {
			//通过类加载器读取src目录中的 properties文件
			ClassLoader cl = JDBCUtils.class.getClassLoader();
			InputStream is = cl.getResourceAsStream("db.properties");
			
			//Properties有一个对应的类,可以用于读取文件信息
			properties = new Properties();
			//通过输入流加载properties文件
			properties.load(is);
			
			//通过key获取到properties文件中对应的值
			String driver = properties.getProperty("driver");
			//注册驱动
			Class.forName(driver);
			
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取连接
	public static Connection getConnection(){
		
		//读取配置文件中的账号,密码等信息,用于连接数据库
		String url = properties.getProperty("url");
		String user = properties.getProperty("username");
		String password = properties.getProperty("password");
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}
	
	//释放资源
	public static void release(ResultSet resultSet,Statement statement,Connection connection){
		//资源在finnaly中释放
		if(resultSet != null){
			try {
				resultSet.close(); 
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	
	}
}

两个页面类,第一个JFrameDemo.java

package view;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.faces.event.AbortProcessingException;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import bean.User;
import dao.UserDao;

public class JFrameDemo extends JFrame {

	private JPanel contentPane;
	private JTextField userField;
	private JPasswordField passwordField;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					JFrameDemo frame = new JFrameDemo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public JFrameDemo() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel label = new JLabel("\u7528\u6237\u540D");
		label.setBounds(105, 62, 54, 15);
		contentPane.add(label);
		
		final JLabel userTip = new JLabel("");
		userTip.setBounds(303, 62, 121, 15);
		contentPane.add(userTip);
		
		userField = new JTextField();
		userField.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				//当用户名输入框失去焦点时会调用此方法
//				System.out.println("用户名输入框失去焦点");
				String username = userField.getText();
				if (username== null || username.trim().length() == 0) {
//					System.out.println("用户名必须大于6位");
					userTip.setText("用户名不能为空");
				}else{
					userTip.setText("");
				}
			}
		});
		userField.setBounds(161, 59, 140, 21);
		contentPane.add(userField);
		userField.setColumns(10);
		
		JLabel label_1 = new JLabel("\u5BC6\u7801");
		label_1.setBounds(105, 141, 54, 15);
		contentPane.add(label_1);
		
		final JLabel loginTip = new JLabel("");
		loginTip.setForeground(Color.red);
		loginTip.setBounds(131, 34, 167, 15);
		contentPane.add(loginTip);
		
		//记录一下,登录frame对象
		final JFrameDemo self = this;
		//登录
		JButton btnNewButton = new JButton("\u767B\u5F55");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				//创建dao对象,用于操作数据库
				UserDao dao1 = new UserDao();
				//dao.findUser();
				//1.获取到用户输入的密码和用户名验证数据库
				//2.获取输入框中的内容
				String username = userField.getText();
				//getPassword()返回的是C的字符串 char[],通过new String()将C的字符串转为String
				String password = new String(passwordField.getPassword());
				 //3.查询用户是否存在
				User user = dao1.findUser(username, password);
				if (user == null) {
//					System.out.println("登录失败");
					loginTip.setText("用户或密码错误");
				}else{
//					System.out.println("登录成功");
					//销毁登录页
					self.dispose();
					//跳转到MainView
					MainView frame = new MainView();
					//显示
					frame.setVisible(true);
				}
			}
		});
		btnNewButton.setBounds(107, 210, 80, 23);
		contentPane.add(btnNewButton);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(161, 138, 140, 21);
		contentPane.add(passwordField);
		
		JButton button = new JButton("重置");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				userField.setText("");
				passwordField.setText("");
			}
		});
		button.setBounds(268, 210, 80, 23);
		contentPane.add(button);
		
		
		
		
	}
}

第二个mainView.java

package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import bean.Emp;
import bean.EmpTableModel;
import bean.FindTable;
import dao.EmpDao;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.FlowLayout;

import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JTextArea;

public class MainView extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private JTable tablefind;
	
//	页面的起始值   查询、添加、删除、修改
	private int start;
	private int number = 5;
	static List<Emp> yesfind;
	static List<Emp>bumenfind;
	static List<Emp>bumenvalue;
	
	private EmpTableModel tableModel;
	private JPanel panel_left;
	private JButton btnAdd;
	private JButton btnBaoCun;
	private JButton btnDelete;
	private JLabel label;
	private JPanel panel_search;
	private JTextField textField_1;
	private JLabel label_1;
	private JPanel panel_acdu;
	private JPanel panel;
	private JButton btnFirst;
	private JButton btnPrevious;
	private JButton btnNext;
	private JButton btnLast;
	private JButton btnSearch;
	private JPanel panel_1;
	private JButton btnNewButton;
	private JPanel panel_2;
	private JLabel label_2;
	private JComboBox comboBox;
	private JTextArea textArea;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainView frame = new MainView();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public JPanel getPanel() {
		return panel;
	}

	public void setPanel(JPanel panel) {
		this.panel = panel;
	}

	public static List<Emp> getYesfind() {
		return yesfind;
	}

	public void setYesfind(List<Emp> yesfind) {
		this.yesfind = yesfind;
	}

	/**
	 * Create the frame.
	 */
	public MainView() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 649, 445);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		//以二维数组的方式提供数据
		/*
		String[][] data = {
				{"张三","22","男"},
				{"张三","22","男"},
				{"张三","22","男"}
		};
		//表头
		String[] titles = {"姓名","年龄","性别"};
		table = new JTable(data,titles);
		*/
//		编辑单元格后,点击页面的其他位置,结束编辑状态
//		table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
		
		tableModel = new EmpTableModel();
		
		
		
		//标题
		label = DefaultComponentFactory.getInstance().createTitle("员工管理系统");
		label.setIcon(new ImageIcon("image/人副本.png"));
		label.setFont(new Font("黑体", Font.PLAIN, 20));
		label.setHorizontalAlignment(SwingConstants.CENTER);
		contentPane.add(label, BorderLayout.NORTH);
		
	
		
		panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setAlignment(FlowLayout.TRAILING);
		contentPane.add(panel, BorderLayout.SOUTH);
		
		btnFirst = new JButton("first");
		btnFirst.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				start = 0;
				updateTable();
//				判断按钮是否可以让用户点击
				updateButtons();
			}
		});
		panel.add(btnFirst);
		
		
		
	//   每页5条         start,number   start - number
		btnPrevious = new JButton("previous");
		btnPrevious.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				start -= number;
				updateTable();
				updateButtons();
			}
		});
		panel.add(btnPrevious);
		// start + number
		btnNext = new JButton("next");
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				start += number;
				updateTable();
				updateButtons();
			}
		});
		panel.add(btnNext);
		
	
		
		
		btnLast = new JButton("last");
		btnLast.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				start = last();
				updateTable();
				updateButtons();
			}
		});
		panel.add(btnLast);
		
		//显示数据的表格
		
		table = new JTable(tableModel);
		table.setFont(new Font("宋体", Font.PLAIN, 14));
		
		/*
		 * 上面的方式只是测试,我们的数据应该来自于数据库
		 * 尽量不要在数据展示的代码中掺杂数据库操作的代码
		 * 数据库操作的代码应该放入到dao层
		 *
		 *
			如果把table直接放在面板上,默认没有表头,我们需要把table先
			放到一个滚动面板上,再将滚动面板放到contentPane
		*/
		
		JScrollPane scrollPane = new JScrollPane(table);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		
		panel_left = new JPanel();
		contentPane.add(panel_left, BorderLayout.WEST);
		panel_left.setLayout(new GridLayout(0, 1, 0, 0));
		
		panel_search = new JPanel();
		panel_left.add(panel_search);
		panel_search.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		
		//查询功能
		label_1 = new JLabel("员工姓名:");
		label_1.setHorizontalAlignment(SwingConstants.LEFT);
		panel_search.add(label_1);
		
		textField_1 = new JTextField();
		panel_search.add(textField_1);
		textField_1.setColumns(10);
		
		
		
		btnSearch = new JButton("");
		btnSearch.setIcon(new ImageIcon("image/查找1.png"));
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//根据姓名查找,先要拿到姓名
				//yesfind是返回的找到的人
				 yesfind=tableModel.find(textField_1.getText());
				//接下来应该是把此设置到table中
				tableModel.setList(yesfind);
				table.updateUI();
				
			}
		});
		panel_search.add(btnSearch);
		
		panel_2 = new JPanel();
		panel_left.add(panel_2);
		panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		label_2 = new JLabel("部门:");
		label_2.setHorizontalAlignment(SwingConstants.LEFT);
		label_2.setVerticalAlignment(SwingConstants.BOTTOM);
		panel_2.add(label_2);
		
		
		//下拉列表,根据部门得到平均薪水
		comboBox = new JComboBox();
		//1.先把所有部门加到下拉列表框
		bumenfind=tableModel.bumenfind();
		for(int i=0;i<bumenfind.size();i++){
			comboBox.addItem(bumenfind.get(i).getJob().toString()); 
		}
		panel_2.add(comboBox);
		
		textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.setColumns(14);
		panel_2.add(textArea);
		
		
		
		//为下拉列表框增加点击事件
		comboBox.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						// TODO Auto-generated method stub
						//找到所点击的部门的记录
						bumenvalue=tableModel.bumenvalue(comboBox.getSelectedItem().toString());
						//取出集合中的部门人数
						int count=bumenvalue.size();
						//取出集合中的薪水放入一个新的数组集合
						List bumensal=new ArrayList<>();
						for(int j=0;j<bumenvalue.size();j++){
							bumensal.add(bumenvalue.get(j).getSal());
						}
						//得到此部门的最大最小值,平均值
						float val=0;
						float minsal=Collections.min(bumensal);
						float maxsal=Collections.max(bumensal);
						for(int k=0;k<bumensal.size();k++){ 
					            val=val+(Float)bumensal.get(k); 
					       } 
						val=val/bumensal.size();
						//System.out.println("val="+val);
						//System.out.println(""+bumenvalue);
						textArea.setText("此部门人数:"+count+"   "+"最高薪水:"+maxsal+"   "+"最低薪水:"+minsal+"   "+"平均薪水:"+val);
					}
				});
				
		
		
		//增删改功能
		panel_acdu = new JPanel();
		panel_left.add(panel_acdu);
		panel_acdu.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		btnDelete = new JButton("delete");
		panel_acdu.add(btnDelete);
		btnDelete.setHorizontalAlignment(SwingConstants.LEADING);
		
		btnAdd = new JButton("add");
		panel_acdu.add(btnAdd);
		
		panel_1 = new JPanel();
		panel_left.add(panel_1);
		panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
		
		btnBaoCun = new JButton("save");
		btnBaoCun.setVerticalAlignment(SwingConstants.TOP);
		btnBaoCun.setHorizontalAlignment(SwingConstants.LEFT);
		panel_1.add(btnBaoCun);
		
		btnNewButton = new JButton("all");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//点击显示所有
				List<Emp> list = new EmpDao().getEmps(start, number);
				tableModel.setList(list);
				//		通知table更新一下界面,此方法会使table重写去找model要数据
				table.updateUI();
			}
		});
		btnNewButton.setHorizontalAlignment(SwingConstants.LEFT);
		panel_1.add(btnNewButton);
		btnBaoCun.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				将用户的更改都同步到数据库
				
				tableModel.save();
				table.updateUI();
			}
		});
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				给table增加一行
				tableModel.addRow();
				table.updateUI();
			}
		});
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				获取用户选中的行
				int index = table.getSelectedRow();
				tableModel.delete(index);
				table.updateUI();
			}
		});
		
//		页面加载以后,先判断一次按钮的状态,防止用户直接点击上一页
		updateButtons();
		
		
	}
	
	protected void updateButtons() {
//		判断四个按钮是否可以点击
//		当前页是首页,first,previous禁用
//		当前页不是首页,first,previous恢复
//		当前是尾页,last,next禁用
//		当前不是尾页,last,next恢复
		
		if(start == 0){
//			禁用首页按钮
			btnFirst.setEnabled(false);
			btnPrevious.setEnabled(false);
		}else{
			btnFirst.setEnabled(true);
			btnPrevious.setEnabled(true);
		}
		
		if(start == last()){
			btnNext.setEnabled(false);
			btnLast.setEnabled(false);
		}else{
			btnNext.setEnabled(true);
			btnLast.setEnabled(true);
		}
		
		
	}
	
	

	//判断最后一页的起始值
	private int last() {
	//		判断最后一页的起始值
	//		total - number   
	//	整除的情况	    20条数据    5条   最后页面 索引从15开始 
	//	无法整除的情况	17条数据    5条  最后页面  索引从15开始 
		int last = 0;
		int total = new EmpDao().getCount();
		if(total % number == 0){
			last = total - number;
		}else{
			last = total - total % number;
		}
		return last;
	}

	private void updateTable() {
		
		List<Emp> list = new EmpDao().getEmps(start, number);
		
		tableModel.setList(list);
		
//		通知table更新一下界面,此方法会使table重写去找model要数据
		table.updateUI();
	}
	
	

}

其中用到的db.properties信息

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/user
username=root
password=root

 最后就是数据库了建表之类的,这样我也列一下我的吧

/*
Navicat MySQL Data Transfer

Source Server         : bc
Source Server Version : 50527
Source Host           : localhost:3306
Source Database       : user

Target Server Type    : MYSQL
Target Server Version : 50527
File Encoding         : 65001

Date: 2018-06-29 18:29:18
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
  `empno` int(11) NOT NULL AUTO_INCREMENT,
  `ename` varchar(255) DEFAULT NULL,
  `job` varchar(255) DEFAULT NULL,
  `mgr` int(11) DEFAULT NULL,
  `hireDate` date DEFAULT NULL,
  `sal` float DEFAULT NULL,
  `comm` float DEFAULT NULL,
  `deptno` int(11) DEFAULT NULL,
  PRIMARY KEY (`empno`)
) ENGINE=InnoDB AUTO_INCREMENT=1017 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES ('1001', '曾智琴', '龙王', '1', '2000-06-07', '100', '10', '3');
INSERT INTO `emp` VALUES ('1002', '扶摇', '皇后', '1', '2016-07-01', '99', '1', '2');
INSERT INTO `emp` VALUES ('1003', '魏征', '丞相', '2', '2018-06-06', '98', '12', '1');
INSERT INTO `emp` VALUES ('1004', '奥巴马', '丞相', '3', '2018-06-13', '97', '13', '4');
INSERT INTO `emp` VALUES ('1005', '无极', '侍卫', '2', '2018-06-04', '96', '1', '5');
INSERT INTO `emp` VALUES ('1006', '纳兰性德', '侍卫', '4', '2018-06-11', '96', '4', '6');
INSERT INTO `emp` VALUES ('1007', '夜华', '侍卫', '5', '2018-06-05', '96', '7', '7');
INSERT INTO `emp` VALUES ('1008', '郑爽', '宫女', null, '2018-01-01', '90', null, null);
INSERT INTO `emp` VALUES ('1009', '陈思', '爱妃', null, '2018-06-01', '3', null, null);
INSERT INTO `emp` VALUES ('1010', '郑安然', '美人', null, '2018-06-01', '3', null, null);
INSERT INTO `emp` VALUES ('1011', '特朗普', '马夫', null, '2018-06-19', '1', null, null);
INSERT INTO `emp` VALUES ('1012', '黄星宇', '尚书', null, '2018-06-29', '88', null, null);
INSERT INTO `emp` VALUES ('1013', '王旨', '尚书', null, '2018-06-20', '88', null, null);
INSERT INTO `emp` VALUES ('1014', 'c罗', '大将军', null, '2018-06-23', '101', null, null);

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(10) NOT NULL,
  `password` varchar(10) DEFAULT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '杨幂', '1234', '1234567');
INSERT INTO `user` VALUES ('2', '胡歌', '123', '7654321');

需要导入有四个

JAVA跳转页面jsp_增删改_03

JAVA跳转页面jsp_JAVA跳转页面jsp_04