//实体类
import java.io.Serializable;
import java.sql.Timestamp;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = -728103096813097978L;
private int id;
private String name;
private Timestamp birthday;
private String sex;
private String schoolRecord;
private String phone;
private String email;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSchoolRecord() {
return schoolRecord;
}
public void setSchoolRecord(String schoolRecord) {
this.schoolRecord = schoolRecord;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
//封装的DB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class EmployeeSqLServerDB {
private Connection conn=null;
private static String jdbcDriverString="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static String urlString="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=employee";
private static String user="sa";
private static String password="yy116";
private EmployeeSqLServerDB() {
}
private static EmployeeSqLServerDB db;
static
{
if(db== null)db=new EmployeeSqLServerDB();
}
public static EmployeeSqLServerDB newInstance()
{
return db;
}
public static EmployeeSqLServerDB newInstance(String jdbcDriverString, String urlString)
{
setJdbcDriverString(jdbcDriverString);
setUrlString(urlString);
return db;
}
public Connection getConn() throws Exception
{
try {
Class.forName(jdbcDriverString);
conn = DriverManager.getConnection( urlString, user, password );
}
//Load the Driver
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("数据库连接失败!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new Exception("数据库驱动包加载失败!");
}
return conn;
}
public Statement getStatement(Connection conn) throws Exception
{
Statement stmt=null;
try {
stmt=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("[数据库操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
return stmt;
}
public ResultSet executeQuery(Statement stmt,String sql) throws Exception
{
ResultSet res=null;
try {
res=stmt.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("[数据库操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
return res;
}
public int executeUpate(Statement stmt,String sql) throws Exception
{
try {
return stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("[数据库更新操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
}
public PreparedStatement getPreparedStatement(Connection conn,String sql) throws Exception
{
PreparedStatement pstmt=null;
try {
pstmt=conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("[数据库操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
return pstmt;
}
public PreparedStatement getPreparedStatement(Connection conn,String sql,int autoGeneratedKeys) throws SQLException
{
PreparedStatement pstmt=null;
pstmt=conn.prepareStatement(sql,autoGeneratedKeys);
return pstmt;
}
public void close(Connection conn) throws Exception
{
try
{
if(conn!=null)
{
conn.close();
conn=null;
}
}catch (SQLException e) {
e.printStackTrace();
throw new Exception("[数据库关闭操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
}
public void close(ResultSet rs) throws Exception
{
try
{
if(rs!=null)
{
rs.close();
rs=null;
}
}catch (SQLException e) {
e.printStackTrace();
throw new Exception("[数据库关闭操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
}
public void close(Statement stmt) throws Exception
{
try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}catch (SQLException e) {
e.printStackTrace();
throw new Exception("[数据库关闭操作错误!]"+e.getErrorCode()+":"+e.getMessage());
}
}
public static EmployeeSqLServerDB getDb() {
return db;
}
public static void setDb(EmployeeSqLServerDB db) {
EmployeeSqLServerDB.db = db;
}
public static String getJdbcDriverString() {
return jdbcDriverString;
}
public static void setJdbcDriverString(String jdbcDriverString) {
EmployeeSqLServerDB.jdbcDriverString = jdbcDriverString;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
EmployeeSqLServerDB.password = password;
}
public static String getUrlString() {
return urlString;
}
public static void setUrlString(String urlString) {
EmployeeSqLServerDB.urlString = urlString;
}
public static String getUser() {
return user;
}
public static void setUser(String user) {
EmployeeSqLServerDB.user = user;
}
}
//封装的DAO
package com.zcsoft.test.employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class EmploySqlServerDAO {
private static EmploySqlServerDAO dao;
private EmployeeSqLServerDB db;
static {
if (dao == null)
dao = new EmploySqlServerDAO();
}
private EmploySqlServerDAO() {
// TODO 自动生成构造函数存根
}
public static EmploySqlServerDAO newInstance(EmployeeSqLServerDB db) {
dao.setDb(db);
return dao;
}
public void addEmployee(Employee e) throws Exception {
Connection conn = db.getConn();
String sql = "insert into employee2(name,birthday,sex,schoolrecord,phone,email,addr) values(?,?,?,?,?,?,?)";
PreparedStatement pstmt = db.getPreparedStatement(conn, sql);
pstmt.setString(1, e.getName());
pstmt.setTimestamp(2, e.getBirthday());
pstmt.setString(3, e.getSex());
pstmt.setString(4, e.getSchoolRecord());
pstmt.setString(5, e.getPhone());
pstmt.setString(6, e.getEmail());
pstmt.setString(7, e.getAddress());
pstmt.executeUpdate();
db.close(pstmt);
db.close(conn);
}
public Employee getEmployeeByID(int employeeID) throws Exception {
Connection conn = db.getConn();
String sql = "select * from employee2 where id=" + employeeID;
Employee e = new Employee();
Statement stmt = db.getStatement(conn);
ResultSet rs = db.executeQuery(stmt, sql);
while (rs.next()) {
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setBirthday(rs.getTimestamp(3));
e.setSex(rs.getString(4));
e.setSchoolRecord(rs.getString(5));
e.setPhone(rs.getString(6));
e.setEmail(rs.getString(7));
e.setAddress(rs.getString(8));
}
db.close(rs);
db.close(stmt);
db.close(conn);
return e;
}
public List<Employee> getEmployees() throws Exception {
Connection conn = db.getConn();
String sql = "select * from employee2 order by id desc";
List<Employee> employees = new ArrayList<Employee>();
Statement stmt = db.getStatement(conn);
ResultSet rs = db.executeQuery(stmt, sql);
while (rs.next()) {
Employee e = new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setBirthday(rs.getTimestamp(3));
e.setSex(rs.getString(4));
e.setSchoolRecord(rs.getString(5));
e.setPhone(rs.getString(6));
e.setEmail(rs.getString(7));
e.setAddress(rs.getString(8));
employees.add(e);
}
db.close(rs);
db.close(stmt);
db.close(conn);
return employees;
}
public void removeEmployee(Employee e) throws Exception {
Connection conn = db.getConn();
String sql = "delete from employee2 ";
sql += "where id =" + e.getId();
Statement stmt = db.getStatement(conn);
db.executeUpate(stmt, sql);
db.close(stmt);
db.close(conn);
}
public void updateEmployee(Employee e) throws Exception {
Connection conn = db.getConn();
String sql = "update employee2 set ";
sql += "name='" + e.getName() + "'";
sql += ",birthday='"
+ new SimpleDateFormat("yyyy-MM-dd").format(e.getBirthday())
+ "'";
sql += ",sex='" + e.getSex() + "'";
sql += ",schoolrecord='" + e.getSchoolRecord() + "'";
sql += ",phone='" + e.getPhone() + "'";
sql += ",email='" + e.getEmail() + "'";
sql += ",addr='" + e.getAddress() + "'";
sql += "where id =" + e.getId();
Statement stmt = db.getStatement(conn);
db.executeUpate(stmt, sql);
db.close(stmt);
db.close(conn);
}
public EmployeeSqLServerDB getDb() {
return db;
}
public void setDb(EmployeeSqLServerDB db) {
this.db = db;
}
}
//封装的序列化传输类
package com.zcsoft.test.employee;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
public class Transport implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int role = 0;
private boolean success = false;
private Object transportObject = null;
private String errorMessage = null;
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Object getTransportObject() {
return transportObject;
}
public void setTransportObject(Object transportObject) {
this.transportObject = transportObject;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public static HttpURLConnection getUrlConnection(String url)
throws IOException {
URL servletURL = new URL(url);
HttpURLConnection servletConnection = (HttpURLConnection) servletURL
.openConnection();
servletConnection.setRequestMethod("POST");
servletConnection.setDoOutput(true);
servletConnection.setDoInput(true);
servletConnection.setUseCaches(false);
servletConnection.setRequestProperty("Content-type",
"application/octet-stream");
return servletConnection;
}
public static Transport loadFromInputStream(InputStream is)
throws IOException, ClassNotFoundException {
Transport t = new Transport();
ObjectInputStream ois = new ObjectInputStream(is);
t = (Transport) ois.readObject();
ois.close();
return t;
}
public static void sendToOutputstream(OutputStream os, Transport t)
throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(t);
oos.flush();
oos.close();
}
}
// applet
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import com.zcsoft.test.table.SortTableModel;
public class EmployeeJApplet extends JApplet {
/**
*
*/
public static int pageSize = 12;
private static final long serialVersionUID = -863616962167228283L;
private JTextField nameField;
private JTextField birthdayField;
private JComboBox sexBox;
private JComboBox schoolRecordBox;
private JTextField phoneField;
private JTextField emailField;
private JTextField addrField;
private JTable mainTable;
private JButton addButton;
private JButton deleteButton;
private JButton updateButton;
private JButton refresh;
private javax.swing.JLabel allCount;
SortTableModel stableModel=null;
private List<Employee> employees = new ArrayList<Employee>();
public void launch() {
JLabel addrLabel;
JLabel allCountLabel;
JLabel birthdayLabel;
JLabel emailLabel;
JLabel phoneLabel;
JLabel sexLabel;
JLabel schoolRecordLabel;
JLabel nameLabel;
JLabel inforLabel=new JLabel("~友情提示~:双击表头可以自动排序 ");;
JPanel topPanel = new JPanel();
JScrollPane tablePane = new JScrollPane(mainTable);
JPanel bottomPanel = new JPanel();
nameLabel = new JLabel();
schoolRecordLabel = new JLabel();
addrLabel = new JLabel();
birthdayLabel = new JLabel();
phoneLabel = new JLabel();
sexLabel = new JLabel();
emailLabel = new JLabel();
allCountLabel = new JLabel();
refresh=new JButton("刷新");
nameField = new JTextField();
birthdayField = new JTextField();
phoneField = new JTextField();
emailField = new JTextField();
addrField = new JTextField();
sexBox = new JComboBox();
schoolRecordBox = new JComboBox(new String[] { "大专", "本科",
"硕士", "博士" });
mainTable = new JTable();
allCount = new JLabel();
addButton = new JButton();
updateButton = new JButton();
deleteButton = new JButton();
nameLabel.setText("姓名:"); // NOI18N
schoolRecordLabel.setText("学历:"); // NOI18N
schoolRecordLabel.setName("schoolRecordLabel"); // NOI18N
addrLabel.setText("联系地址:"); // NOI18N
addrLabel.setName("addrLabel"); // NOI18N
birthdayLabel.setText("生日:"); // NOI18N
phoneLabel.setText("电话:"); // NOI18N
sexLabel.setText("性别:"); // NOI18N
emailLabel.setText("邮件:"); // NOI18N
sexBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"男", "女" }));
addButton.setText("添加"); // NOI18N
addButton.addActionListener(new OperateMonitor());
updateButton.setText("修改"); // NOI18N
updateButton.addActionListener(new OperateMonitor());
deleteButton.setText("删除"); // NOI18N
deleteButton.addActionListener(new OperateMonitor());
mainTable.addMouseListener(new OperateMonitor());
allCountLabel.setText("条记录");
allCount.setForeground(new java.awt.Color(255, 0, 51));
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
topPanel.setLayout(gridBag);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
gridBag.setConstraints(nameLabel, c);
gridBag.setConstraints(birthdayLabel, c);
gridBag.setConstraints(sexLabel, c);
c.weightx = 8.0;
gridBag.setConstraints(nameField, c);
gridBag.setConstraints(birthdayField, c);
c.gridwidth = GridBagConstraints.REMAINDER;
gridBag.setConstraints(sexBox, c);
c.gridwidth = 1;
c.weightx = 1.0;
gridBag.setConstraints(schoolRecordLabel, c);
gridBag.setConstraints(phoneLabel, c);
gridBag.setConstraints(emailLabel, c);
c.weightx = 8.0;
gridBag.setConstraints(schoolRecordBox, c);
gridBag.setConstraints(phoneField, c);
c.gridwidth = GridBagConstraints.REMAINDER;
gridBag.setConstraints(emailField, c);
c.gridwidth = 1;
c.weightx = 1.0;
gridBag.setConstraints(addrLabel, c);
c.gridwidth = GridBagConstraints.REMAINDER;
gridBag.setConstraints(addrField, c);
topPanel.add(nameLabel);
topPanel.add(nameField);
topPanel.add(birthdayLabel);
topPanel.add(birthdayField);
topPanel.add(sexLabel);
topPanel.add(sexBox);
topPanel.add(schoolRecordLabel);
topPanel.add(schoolRecordBox);
topPanel.add(phoneLabel);
topPanel.add(phoneField);
topPanel.add(emailLabel);
topPanel.add(emailField);
topPanel.add(addrLabel);
topPanel.add(addrField);
tablePane.setViewportView(mainTable);
FlowLayout flowLayout = new FlowLayout();
bottomPanel.setLayout(flowLayout);
bottomPanel.add(inforLabel);
bottomPanel.add(allCount);
bottomPanel.add(allCountLabel);
flowLayout.setAlignment(FlowLayout.RIGHT);
refresh.addActionListener(new OperateMonitor());
bottomPanel.add(addButton);
bottomPanel.add(updateButton);
bottomPanel.add(deleteButton);
bottomPanel.add(refresh);
mainTable.getTableHeader().addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()<2)
return;
int column=mainTable.getTableHeader().columnAtPoint(e.getPoint());
stableModel.sort(column);
}
});
this.setLayout(new BorderLayout());
this.add(topPanel, BorderLayout.NORTH);
this.add(tablePane, BorderLayout.CENTER);
this.add(bottomPanel, BorderLayout.SOUTH);
this.setSize(new Dimension(600, 400));
}
@Override
public void init() {
// TODO 自动生成方法存根
super.init();
launch();
load();
}
private void load() {
loadEmployees();
loadTable();
}
public void setAllCount(int count) {
allCount.setText(count + "");
}
public int getAllCount() {
return Integer.parseInt(allCount.getText());
}
public void deleteOperation(ActionEvent arg0) {
int row = mainTable.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(null, "请先选择要删除的一行");
} else {
if (JOptionPane.showConfirmDialog(null, "真的要删除吗?", "请您确认",
JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) {
try {
this.deleteEmployeeToRemotion(employees.get(row));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"对不起出错啦!该错误可能是由不正常连接引起的!:" + e.getMessage(),
"出错啦!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane
.showMessageDialog(null, "对不起出错啦: "
+ e.getMessage(), "出错啦!",
JOptionPane.ERROR_MESSAGE);
}
employees.remove(row);
this.setAllCount(this.getAllCount() - 1);
this.loadTable();
}
}
}
public void updateOperation(ActionEvent arg0) {
int row = mainTable.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(null, "请先选择要修改的一行");
} else {
if (JOptionPane.showConfirmDialog(null, "真的要修改吗?", "请您确认",
JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) {
try {
Employee e = employees.get(row);
loadEmployeeFromField(e);
this.updateEmployeeToRemotion(e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null,
"对不起出错啦!该错误可能是由不正常连接引起的!:" + e1.getMessage(),
"出错啦!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "对不起出错啦: "
+ e1.getMessage(), "出错啦!",
JOptionPane.ERROR_MESSAGE);
this.loadEmployees();
}
this.loadTable();
}
}
}
public void addOperation(ActionEvent arg0) {
Employee e = new Employee();
if (loadEmployeeFromField(e)) {
try {
this.addEmployeeToRemotion(e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "对不起出错啦!该错误可能是由不正常连接引起的!:"
+ e1.getMessage(), "出错啦!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "对不起出错啦: "
+ e1.getMessage(), "出错啦!", JOptionPane.ERROR_MESSAGE);
}
this.load();
}
}
public void mouseClickedTableOperation(MouseEvent arg0) {
int currentRow = mainTable.getSelectedRow();
System.out.println(currentRow);
if (currentRow < employees.size()) {
Employee e = employees.get(currentRow);
setEmployeeToField(e);
}
}
private void loadTable() {
Vector<Vector<String>> vs = new Vector<Vector<String>>();
for (Employee e : employees) {
Vector<String> v = new Vector<String>();
v.add(e.getName());
v.add(new SimpleDateFormat("yyyy-MM-dd").format(e.getBirthday()));
v.add(e.getSex());
v.add(e.getSchoolRecord());
v.add(e.getPhone());
v.add(e.getEmail());
v.add(e.getAddress());
vs.add(v);
}
Vector<String> header = new Vector<String>();
header.add("姓名");
header.add("出生日期");
header.add("性别");
header.add("文化程度");
header.add("联系电话");
header.add("电子邮件");
header.add("联系地址");
DefaultTableModel tableModel = new DefaultTableModel(vs, header);
stableModel=new SortTableModel(tableModel);
mainTable.setModel(stableModel);
}
private void loadEmployees() {
employees = new ArrayList<Employee>();
try {
employees = this.loadEmployeesFromRemotion();
this.setAllCount(employees.size());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "对不起出错啦!该错误可能是由不正常连接引起的!:"
+ e1.getMessage(), "出错啦!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "对不起出错啦: " + e1.getMessage(),
"出错啦!", JOptionPane.ERROR_MESSAGE);
}
}
private boolean setEmployeeToField(Employee e) {
this.nameField.setText(e.getName());
try {
this.birthdayField.setText(new SimpleDateFormat("yyyy-MM-dd")
.format(e.getBirthday()));
} catch (NumberFormatException ne) {
JOptionPane.showMessageDialog(null, "对不起,[" + e.getName()
+ "] 信息加载失败!");
return false;
}
this.sexBox.setSelectedItem(e.getSex());
this.schoolRecordBox.setSelectedItem(e.getSchoolRecord());
this.phoneField.setText(e.getPhone());
this.emailField.setText(e.getEmail());
this.addrField.setText(e.getAddress());
return true;
}
private boolean loadEmployeeFromField(Employee e) {
if (this.nameField.getText().trim().equals("")
|| this.nameField.getText().trim().equals("")
|| this.birthdayField.getText().trim().equals("")
|| this.phoneField.getText().trim().equals("")
|| this.emailField.getText().trim().equals("")
|| this.addrField.getText().equals("")) {
JOptionPane.showMessageDialog(null, "对不起,请把信息填写完整!");
return false;
}
e.setName(this.nameField.getText());
try {
e.setBirthday(Timestamp.valueOf(birthdayField.getText()
+ " 00:00:00"));
} catch (Exception ee) {
JOptionPane.showMessageDialog(null, "生日请用请用 yyyy-MM-dd格式!");
return false;
}
e.setSex((String) sexBox.getSelectedItem());
e.setSchoolRecord((String) schoolRecordBox.getSelectedItem());
e.setPhone(this.phoneField.getText());
e.setEmail(emailField.getText());
e.setAddress(addrField.getText());
return true;
}
private List<Employee> loadEmployeesFromRemotion() throws IOException,
ClassNotFoundException, Exception {
HttpURLConnection uc = Transport
.getUrlConnection("http://localhost:8080/test3/employee");
Transport t = new Transport();
t.setRole(1);
Transport.sendToOutputstream(uc.getOutputStream(), t);
t = Transport.loadFromInputStream(uc.getInputStream());
if (!t.isSuccess()) {
throw new Exception(t.getErrorMessage());
}
else {
List<Employee> employees = (List<Employee>) t.getTransportObject();
return employees;
}
}
private void addEmployeeToRemotion(Employee e) throws IOException,
ClassNotFoundException, Exception {
HttpURLConnection uc;
uc = Transport.getUrlConnection("http://localhost:8080/test3/employee");
Transport t = new Transport();
t.setRole(2);
t.setTransportObject(e);
Transport.sendToOutputstream(uc.getOutputStream(), t);
t = Transport.loadFromInputStream(uc.getInputStream());
if (!t.isSuccess()) {
throw new Exception(t.getErrorMessage());
}
}
private void updateEmployeeToRemotion(Employee e) throws IOException,
ClassNotFoundException, Exception {
HttpURLConnection uc;
uc = Transport.getUrlConnection("http://localhost:8080/test3/employee");
Transport t = new Transport();
t.setRole(3);
t.setTransportObject(e);
Transport.sendToOutputstream(uc.getOutputStream(), t);
t = Transport.loadFromInputStream(uc.getInputStream());
if (!t.isSuccess()) {
throw new Exception(t.getErrorMessage());
}
}
private void deleteEmployeeToRemotion(Employee e) throws IOException,
ClassNotFoundException, Exception {
HttpURLConnection uc;
uc = Transport.getUrlConnection("http://localhost:8080/test3/employee");
Transport t = new Transport();
t.setRole(4);
t.setTransportObject(e);
Transport.sendToOutputstream(uc.getOutputStream(), t);
t = Transport.loadFromInputStream(uc.getInputStream());
if (!t.isSuccess()) {
throw new Exception(t.getErrorMessage());
}
}
class OperateMonitor extends MouseAdapter implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton)
addOperation(e);
if (e.getSource() == updateButton)
updateOperation(e);
if (e.getSource() == deleteButton)
deleteOperation(e);
if (e.getSource() == refresh)
{
load();
}
}
public void mouseClicked(MouseEvent arg0) {
mouseClickedTableOperation(arg0);
}
}
}
//servlet
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EmployeeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 3649463966187564412L;
/**
*
*/
EmploySqlServerDAO mgr = EmploySqlServerDAO.newInstance(EmployeeSqLServerDB
.newInstance());
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/octet-stream");
Transport t = null;
try {
t = (Transport) Transport.loadFromInputStream(request
.getInputStream());
switch (t.getRole()) {
case 1: {
List<Employee> employees = mgr.getEmployees();
t.setTransportObject(employees);
t.setSuccess(true);
break;
}
case 2: {
Employee e = (Employee) t.getTransportObject();
mgr.addEmployee(e);
t.setTransportObject(null);
t.setSuccess(true);
break;
}
case 3:
{
Employee e = (Employee) t.getTransportObject();
mgr.updateEmployee(e);
t.setTransportObject(null);
t.setSuccess(true);
}
break;
case 4: {
Employee e = (Employee) t.getTransportObject();
mgr.removeEmployee(e);
t.setTransportObject(null);
t.setSuccess(true);
}
break;
default:
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
t.setSuccess(false);
t.setErrorMessage(e.getMessage());
}
Transport.sendToOutputstream(response.getOutputStream(), t);
}
}
//自己定义的表格排序模板
import java.util.Arrays;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class SortTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
private TableModel model;
public int sortColumn;
private Row row[];
public SortTableModel(TableModel model) {
super();
this.model = model;
row = new Row[model.getRowCount()];
for (int i = 0; i < row.length; i++) {
row[i] = new Row(i);
}
}
public int getColumnCount() {
// TODO 自动生成方法存根
return model.getColumnCount();
}
public int getRowCount() {
return model.getRowCount();
}
public Object getValueAt(int r, int c) {
return model.getValueAt(row[r].getIndex(), c);
}
@Override
public boolean isCellEditable(int r, int c) {
// TODO 自动生成方法存根
return model.isCellEditable(r, c);
}
@Override
public String getColumnName(int arg0) {
// TODO 自动生成方法存根
return model.getColumnName(arg0);
}
@Override
public Class<?> getColumnClass(int c) {
// TODO 自动生成方法存根
return getValueAt(0, c).getClass();
}
public void sort(int sortColumn) {
this.sortColumn = sortColumn;
Arrays.sort(row);
this.fireTableDataChanged();
}
private class Row implements Comparable<Row> {
private int index;
public Row(int index) {
super();
this.index = index;
}
public int compareTo(Row other) {
Object a = model.getValueAt(index, sortColumn);
Object b = model.getValueAt(other.getIndex(), sortColumn);
if (a instanceof Comparable) {
return ((Comparable) a).compareTo(b);
} else
return a.toString().compareTo(b.toString());
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
}