1、基于 B/S 架构的 applet 和 servlet 通信Applet 的优缺点这里也不想细说,百度上面多的是,只不过实例多为一个版本,这几天也研究了一下,写了个小例子,希望可以对大家有用.1.首先页面如下,主要完成的是增删改查的操作,数据传递主要依靠的是对象的序列化,封装了两个对象 TempObject(客户到服务端) 和 ServerObject(服务到客户端),页面中的刷新是全表格的刷新,增删改操作后有局部动态刷新,整体布局为 GridBagLayout 和BorderLayout 相结合 ,包的划分如下:2.代码部分Client 端主要是 ManageInfo,java:代码如下:p
2、ackage com.zcsoft.frame;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStre
3、am;import java.io.OutputStream;import .MalformedURLException;import .URL;import .URLConnection;import java.util.Calendar;import java.util.List;import java.util.Vector;import javax.print.attribute.standard.Severity;import javax.swing.JApplet;import javax.swing.JButton;import javax.swing.JComboBox;imp
4、ort javax.swing.JFrame;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.UIManager;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.border.L
5、ineBorder;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import javax.swing.table.DefaultTableModel;import javax.swing.table.TableColumn;import javax.swing.table.TableColumnModel;import sun.security.krb5.internal.UDPClient;import com.sun.corba.se.impl.ior.
6、WireObjectKeyTemplate;import com.zcsoft.dao.EmployeeDao;import com.zcsoft.test.Employee;import com.zcsoft.test.ServerObject;import com.zcsoft.test.TempObject;/* 页面窗体* author training*/public class ManageInfo extends JApplet private JTable tab;private DefaultTableModel tabModel;/文本框private JTextField
7、 txtName,txtBirth,txtPhone,txtEmail,txtAddress;/下拉列表private JComboBox cboSex,cboEducation;/按钮private JButton btnUpd,btnAdd,btnMod,btnDel;private URL url;private URLConnection urlcon;private InputStream ins=null;private ObjectInputStream ois=null;private ObjectOutputStream oos=null;private Object res
8、ult=null;private Calendar calendar;public ManageInfo() setBounds(200, 200, 900, 700);setLayout(new BorderLayout();/组件初始化componentInit();/校验服务端if(checkServer()/数据初始化InitData();/绑定监听器bindListener();/ cboEducation.addActionListener()/*tabModel.addRow(rowData);tabModel.setValueAt(aValue, row, column);ta
9、bModel.removeRow();*/ tab.getSelectionModel().addListSelectionListener(new ListSelectionListener()/ Override/ public void valueChanged(ListSelectionEvent e) / / );/* 组件初始化*/private void componentInit()/用于 BorderLayout 布局的上中下面板JPanel pnlTop,pnlFoot;JScrollPane spnlTab;/实例化文本框txtName=new JTextField(10
10、);txtBirth=new JTextField(10);txtPhone=new JTextField(10);txtEmail=new JTextField(10);txtAddress=new JTextField(40);/实例化下拉列表cboEducation=new JComboBox(new String“博士“,“硕士“,“ 本科“,“专科“,“高中“);cboSex=new JComboBox(new String“男“,“ 女“);/实例化按钮btnUpd=new JButton(“刷新“);btnAdd=new JButton(“添加“);btnDel=new JBut
11、ton(“删除“);btnMod=new JButton(“修改“);/主体部分pnlTop=new JPanel(new GridBagLayout();pnlTop.setBorder(new LineBorder(Color.red,1);/底部pnlFoot=new JPanel();pnlFoot.add(btnUpd);pnlFoot.add(btnAdd);pnlFoot.add(btnMod);pnlFoot.add(btnDel);/实例化表格String columns=new String“编号“,“姓名“,“ 出生年月“,“性别“,“文化程度“,“ 联系电话“,“电子邮
12、件“,“通讯地址“;Object data=null;tabModel=new DefaultTableModel(data,columns);tab=new JTable(tabModel);/禁止拖动tab.getTableHeader().setReorderingAllowed(false);/实例化滚动面板,将表格加入其中spnlTab=new JScrollPane(tab);/将组件添加至 pnlTop 中GridBagConstraints gbc=new GridBagConstraints();gbc.insets=new Insets(10,10,10,20);gbc.g
13、ridy=0;gbc.anchor=GridBagConstraints.NORTHWEST;pnlTop.add(new JLabel(“姓名“),gbc);pnlTop.add(txtName,gbc);pnlTop.add(new JLabel(“出生日期“),gbc);pnlTop.add(txtBirth,gbc);pnlTop.add(new JLabel(“性别“),gbc);pnlTop.add(cboSex,gbc);gbc.gridy=1;pnlTop.add(new JLabel(“文化程度“),gbc);pnlTop.add(cboEducation,gbc);pnlT
14、op.add(new JLabel(“联系电话“),gbc);pnlTop.add(txtPhone,gbc);pnlTop.add(new JLabel(“电子邮件“),gbc);pnlTop.add(txtEmail,gbc);gbc.gridy=2;pnlTop.add(new JLabel(“通讯地址“),gbc);gbc.gridwidth=5;pnlTop.add(txtAddress,gbc);gbc.gridy=3;gbc.gridwidth=6;gbc.fill=GridBagConstraints.HORIZONTAL;this.add(pnlTop,BorderLayou
15、t.NORTH);this.add(spnlTab,BorderLayout.CENTER);this.add(pnlFoot,BorderLayout.SOUTH);/* 绑定监听器*/private void bindListener()btnUpd.addActionListener(new btnClick();btnAdd.addActionListener(new btnClick();btnDel.addActionListener(new btnClick();btnMod.addActionListener(new btnClick();tab.getSelectionMod
16、el().addListSelectionListener(new tabSelectedChange();/* 表格变更行监听实现类* author training*/private class tabSelectedChange implements ListSelectionListenerOverridepublic void valueChanged(ListSelectionEvent e) /获取选中的行的对象if(tab.getSelectedRow()=-1)return;if(!e.getValueIsAdjusting()/清空组件InitFrame();int sel
17、=tab.getSelectedRow();if(tab.getValueAt(sel, 1)!=null)txtName.setText(tab.getValueAt(sel, 1).toString();if(tab.getValueAt(sel, 2)!=null)txtBirth.setText(tab.getValueAt(sel, 2).toString();if(tab.getValueAt(sel, 5)!=null)txtPhone.setText(tab.getValueAt(sel, 5).toString();if(tab.getValueAt(sel, 6)!=nul
18、l)txtEmail.setText(tab.getValueAt(sel, 6).toString();if(tab.getValueAt(sel, 7)!=null)txtAddress.setText(tab.getValueAt(sel, 7).toString();if(tab.getValueAt(sel, 4).toString().trim().equals(“博士“)cboEducation.setSelectedIndex(0);else if(tab.getValueAt(sel, 4).toString().trim().equals(“硕士“)cboEducation
19、.setSelectedIndex(1);else if(tab.getValueAt(sel, 4).toString().trim().equals(“本科“)cboEducation.setSelectedIndex(2);else if(tab.getValueAt(sel, 4).toString().trim().equals(“专科“)cboEducation.setSelectedIndex(3);elsecboEducation.setSelectedIndex(4);if(tab.getValueAt(sel, 3).toString().trim().equals(“男“
20、)cboSex.setSelectedIndex(0);elsecboSex.setSelectedIndex(1);/* 按钮监听器实现类* author training*/private class btnClick implements ActionListenerOverridepublic void actionPerformed(ActionEvent e) JButton btn=(JButton)e.getSource();/检测服务端是否异常if(checkServer()=false)return;/建立链接urlcon=getCon();if(btn=btnUpd)up
21、date();/添加else if(btn=btnAdd)add();/删除else if(btn=btnDel)del();/修改elsemod();/更新表格/ InitData();/* 刷新表格*/private void update()InitData();InitFrame();/* 新增方法*/private void add()/封装对象String name,birth,sex,education,phone,email,address;int id=getNum();name=txtName.getText();birth=txtBirth.getText();educa
22、tion=cboEducation.getSelectedItem().toString();phone=txtPhone.getText();email=txtEmail.getText();address=txtAddress.getText();TempObject temp=new TempObject();Employee emp=new Employee();emp.setId(id);emp.setName(name);emp.setAddress(address);emp.setBirth(birth);emp.setPhone(phone);emp.setEmail(emai
23、l);emp.setEducation(education);if(cboSex.getSelectedIndex()=0)sex=“男“;emp.setSex(1);elsesex=“女“;emp.setSex(0);temp.setEmployee(emp);temp.setType(1);/将对象写到服务端writeObjectToServer(temp);/获取服务端返回结果result=readObjectFromServer();if(result!=null)ServerObject returnObject=(ServerObject)result;if(returnObjec
24、t.getFlag()tabModel.addRow(new Objectid,name,birth,sex,education,phone,email,address);JOptionPane.showMessageDialog(null,“新增成功“);elseJOptionPane.showMessageDialog(null, returnObject.getMsg();return;/* 修改方法*/private void mod()if(tab.getSelectedRow()=-1)JOptionPane.showMessageDialog(null,“请选择要操作的行“);r
25、eturn;/实例化 TempObjectTempObject tempObject=new TempObject();Employee emp=new Employee();emp.setId(Integer.parseInt(tab.getValueAt(tab.getSelectedRow(), 0).toString();emp.setName(txtName.getText();emp.setBirth(txtBirth.getText();emp.setPhone(txtPhone.getText();emp.setEmail(txtEmail.getText();emp.setA
26、ddress(txtAddress.getText();/选择男if(cboSex.getSelectedIndex()=0)emp.setSex(1);elseemp.setSex(0);if(cboEducation.getSelectedIndex()=0)emp.setEducation(“博士“);else if(cboEducation.getSelectedIndex()=1)emp.setEducation(“硕士“);else if(cboEducation.getSelectedIndex()=2)emp.setEducation(“本科“);else if(cboEduc
27、ation.getSelectedIndex()=3)emp.setEducation(“专科“);else if(cboEducation.getSelectedIndex()=4)emp.setEducation(“高中“);tempObject.setType(2);tempObject.setEmployee(emp);/发送请求writeObjectToServer(tempObject);Object dataMod=new Objectemp.getName(),emp.getBirth(),cboSex.getSelectedItem().toString(),emp.getE
28、ducation(),emp.getPhone(),emp.getEmail(),emp.getAddress();/获取响应result=readObjectFromServer();if(result!=null)ServerObject serverObject=(ServerObject)result;if(serverObject.getFlag()for(int i=1;i list=returnObj.getEmpList();String columns=new String“编号“,“姓名“,“ 出生年月“,“性别“,“文化程度“,“联系电话“,“电子邮件“,“通讯地址“;O
29、bject data=new Objectlist.size()8;for(int i=0;i empList = null;try empList = employeeDao.getAllEmployee(); catch (SQLException e) / TODO Auto-generated catch blockserverObject.setMsg(e.getMessage();serverObject.setFlag(false);serverObject.setEmpList(empList);return serverObject;/ List empList=new Ar
30、rayList();/ empList=employeeDao.getAllEmployee();/ return empList;/* 查找员工* return* throws SQLException / */ private ServerObject doFind()/ / ServerObject serverObject=new ServerObject();/ Employee emp=temp.getEmployee();/ Employee e=employeeDao.getEmployeeById(emp.getId();/ return e;/ /* 修改员工* param
31、 res* return*/private ServerObject doMod(HttpServletResponse res)Employee emp=temp.getEmployee();boolean flag=false;ServerObject serverObject=new ServerObject();try flag= employeeDao.modifyEmployee(emp); catch (SQLException e) / TODO Auto-generated catch blockserverObject.setMsg(e.getMessage();serve
32、rObject.setFlag(flag);return serverObject;/* 删除员工* param res* return*/private ServerObject doDel(HttpServletResponse res)Employee emp=temp.getEmployee();ServerObject serverObject=new ServerObject();boolean flag=true;try flag= employeeDao.delEmployee(emp.getId(); catch (SQLException e) / TODO Auto-ge
33、nerated catch blockserverObject.setMsg(e.getMessage();serverObject.setFlag(flag);return serverObject;/* 新增员工方法* param req* param res*/private ServerObject doAdd(HttpServletResponse res)Employee obj=temp.getEmployee();ServerObject serverObject=new ServerObject();boolean flag = false;try flag = employ
34、eeDao.addEmployee(obj); catch (SQLException e) / TODO Auto-generated catch blockserverObject.setMsg(e.getMessage();serverObject.setFlag(flag);return serverObject;/* 从客户端取读对象* throws IOException * throws ClassNotFoundException */private Object readObjectFromClient(HttpServletRequest req) throws IOExc
35、eption, ClassNotFoundExceptionObject obj=null;ins=req.getInputStream();ois=new ObjectInputStream(ins);obj=ois.readObject();ois.close();return obj;/* 对象写到客户端* throws IOException */private void writeObjectToClient(HttpServletResponse res,Object obj) throws IOExceptionops=res.getOutputStream();oos=new
36、ObjectOutputStream(ops);oos.writeObject(obj);oos.flush();oos.close();public static void main(String args) EmployeeSer test=new EmployeeSer();Web.xml 配置:EmployeeSercom.zcsoft.servlet.EmployeeSerEmployeeSer/EmployeeSerBaseDao.java 代码:package com.zcsoft.dao;import java.sql.Connection;import java.sql.Dr
37、iverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class BaseDao / private static Connection con;private Connection con;public BaseDao() throws ClassNotFoundException, SQLException Class.forName(“oracle.jdbc.driver.OracleDriver“);con=DriverMan
38、ager.getConnection(“jdbc:oracle:thin:192.168.0.73:1521:orcl“, “system“, “niit“);public void closeAll(ResultSet rs,PreparedStatement pstmt)try if(rs!=null)rs.close();if(pstmt!=null)pstmt.close(); catch (SQLException e) / TODO Auto-generated catch blocke.printStackTrace();public Connection getCon() re
39、turn con;public void setCon(Connection con) this.con = con;Employee.dao 代码 :package com.zcsoft.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.zcsoft.test.Employee;/* E
40、mployee 的数据操作类* author training*/public class EmployeeDao extends BaseDaoprivate Connection con;private PreparedStatement pstmt;private ResultSet rs;public EmployeeDao() throws ClassNotFoundException, SQLException super();/ TODO Auto-generated constructor stub/* 获取所有的员工* return* throws SQLException
41、*/public List getAllEmployee() throws SQLExceptioncon=getCon();ArrayList list=new ArrayList();Employee e;if(con!=null)pstmt=con.prepareStatement(“select * from employee“);rs=pstmt.executeQuery();while(rs.next()e=new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),r
42、s.getString(6),rs.getString(7),rs.getString(8);list.add(e);closeAll(rs, pstmt);return list;/* 根据员工编号删除该员工* param id* return* throws SQLException */public boolean delEmployee(int id) throws SQLExceptionboolean flag=false;con=getCon();int n=0;if(con!=null)pstmt=con.prepareStatement(“delete from employ
43、ee where id=?“);pstmt.setInt(1, id);n=pstmt.executeUpdate();if(n!=0)flag=true;elseflag=false;closeAll(rs, pstmt);return flag;/* 新增员工* param e* throws SQLException */public boolean addEmployee(Employee e) throws SQLExceptionint n=0;boolean flag=false;con=getCon();if(con!=null)pstmt=con.prepareStateme
44、nt(“insert into employee values(?,?,?,?,?,?,?,?)“);pstmt.setInt(1, e.getId();pstmt.setString(2, e.getName();pstmt.setString(3, e.getBirth();pstmt.setInt(4, e.getSex();pstmt.setString(5, e.getEducation();pstmt.setString(6, e.getPhone();pstmt.setString(7, e.getEmail();pstmt.setString(8, e.getAddress()
45、;n=pstmt.executeUpdate();if(n0)flag=true;elseflag=false;closeAll(rs, pstmt);return flag;/* 修改员工信息* param e* return* throws SQLException * throws SQLException */public boolean modifyEmployee(Employee e) throws SQLExceptionboolean flag=false;int n=0;con=getCon();if(con!=null)pstmt=con.prepareStatement
46、(“update employee set name=?,birth=?,sex=?,education=?,phone=?,email=?,address=? where id=?“);pstmt.setString(1, e.getName();pstmt.setString(2, e.getBirth();pstmt.setInt(3, e.getSex();pstmt.setString(4, e.getEducation();pstmt.setString(5, e.getPhone();pstmt.setString(6, e.getEmail();pstmt.setString(
47、7, e.getAddress();pstmt.setInt(8, e.getId();n=pstmt.executeUpdate();if(n0)flag=true;closeAll(rs, pstmt);return flag;/* 根据编号查找该员工对象* param id* return* throws SQLException */public Employee getEmployeeById(int id) throws SQLExceptionEmployee e=null;con=getCon();if(con!=null)pstmt=con.prepareStatement(
48、“select * from employee where id=?“);pstmt.setInt(1, id);rs=pstmt.executeQuery();while(rs.next()e=new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8);closeAll(rs, pstmt);return e;TempObject.java 代码:package com.zcsoft.test;import java.io.Serializable;/* 用于传递的对象类* author training*/public class TempObject implements Serializable/调用方法的类型 0获取所有, 1新增 2修改,3 删