版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、基于B/S架构的applet和servlet通信Applet的优缺点这里也不想细说,百度上面多的是,只不过实例多为一个版本,这几天也研究了一下,写了个小例子,希望可以对大家有用.1.首先页面如下,主要完成的是增删改查的操作,数据传递主要依靠的是对象的序列化,封装了两个对象TempObject(客户到服务端)和ServerObject(服务到客户端),页面中的刷新是全表格的刷新,增删改操作后有局部动态刷新,整体布局为GridBagLayout和BorderLayout相结合,包的划分如下:2.代码部分Client端主要是ManageInfo,java:代码如下:package com.zcsof
2、t.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.ObjectOutputStream;import java.i
3、o.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.JComb
4、oBox;import 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.
5、border.LineBorder;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 ernal.UDPClient;import com.sun.corba.se.i
6、mpl.ior.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;/文本框priv
7、ate JTextField 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;priv
8、ate Object result=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, ro
9、w, column);tabModel.removeRow();*/tab.getSelectionModel().addListSelectionListener(new ListSelectionListener()/Override/public void valueChanged(ListSelectionEvent e) /);/* * 组件初始化 */private void componentInit()/用于BorderLayout布局的上中下面板JPanel pnlTop,pnlFoot;JScrollPane spnlTab;/实例化文本框txtName=new JText
10、Field(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 JButton(删除);btnM
11、od=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编号,姓名,出生年月,性别,文化程度,联系电话,电子邮件,通讯地址;Object data=null;tabMode
12、l=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.gridy=0;gbc.anchor=GridBagConstraints
13、.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);pnlTop.add(new JLabel(联系电话),gbc);pnlTop.add(txtP
14、hone,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,BorderLayout.NORTH);this.add(spnlTab,BorderLayout.CENTER);thi
15、s.add(pnlFoot,BorderLayout.SOUTH);/* * 绑定监听器 */private void bindListener()btnUpd.addActionListener(new btnClick();btnAdd.addActionListener(new btnClick();btnDel.addActionListener(new btnClick();btnMod.addActionListener(new btnClick();tab.getSelectionModel().addListSelectionListener(new tabSelectedCh
16、ange();/* * 表格变更行监听实现类 * author training * */private class tabSelectedChange implements ListSelectionListenerOverridepublic void valueChanged(ListSelectionEvent e) /获取选中的行的对象if(tab.getSelectedRow()=-1)return;if(!e.getValueIsAdjusting()/清空组件InitFrame();int sel=tab.getSelectedRow();if(tab.getValueAt(s
17、el, 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)!=null)txtEmail.setText(tab.getValueAt(sel, 6)
18、.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.setSelectedIndex(1);else if(tab.getValueAt(s
19、el, 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(男)cboSex.setSelectedIndex(0);elsecboSex.setSelectedI
20、ndex(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)update();/添加else if(btn=btnAdd)add();/删除else if
21、(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();education=cboEducation.getSelectedItem().toSt
22、ring();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(email);emp.setEducation(education);if(cboSex
23、.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(returnObject.getFlag()tabModel.addRow(new Objectid,name
24、,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,请选择要操作的行);return;/实例化TempObjectTempObject tempObject=new
25、 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.setAddress(txtAddress.getText();/选择男if(cboSex.getS
26、electedIndex()=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(cboEducation.getSelectedIndex()=3)emp.setEducation(专科);else
27、 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.getEducation(),emp.getPhone(),emp.getEmail(),emp.getAddress(
28、);/获取响应result=readObjectFromServer();if(result!=null)ServerObject serverObject=(ServerObject)result;if(serverObject.getFlag()for(int i=1;i8;i+)tabModel.setValueAt(dataModi-1,tab.getSelectedRow(), i);JOptionPane.showMessageDialog(null,修改成功);elseJOptionPane.showMessageDialog(null,serverObject.getMsg()
29、;return;/* * 删除方法 */private void del()if(tab.getSelectedRow()=-1)JOptionPane.showMessageDialog(null,请选择要操作的行);return;int sel=JOptionPane.showConfirmDialog(null, 确认删除);if(sel=JOptionPane.OK_OPTION)TempObject tempObject=new TempObject();/3 表示删除tempObject.setType(3);int id=Integer.parseInt(tab.getValue
30、At(tab.getSelectedRow(), 0).toString();Employee emp=new Employee();emp.setId(id);tempObject.setEmployee(emp);/写到服务端writeObjectToServer(tempObject);/从服务端获得结果result=readObjectFromServer();ServerObject serverObject=(ServerObject)result;if(serverObject.getFlag()tabModel.removeRow(tab.getSelectedRow();JO
31、ptionPane.showMessageDialog(null,删除成功);InitFrame();elseJOptionPane.showMessageDialog(null, serverObject.getMsg();else/* * 根据指定数据更新表数据 * param list */private void InitData()urlcon=getCon();/获取所有数据TempObject tempObject=new TempObject();tempObject.setType(0);writeObjectToServer(tempObject);/获取服务返回数据Obj
32、ect obj=readObjectFromServer();ServerObject returnObj=(ServerObject)obj;/方法正确执行if(returnObj.getFlag()List list=returnObj.getEmpList();String columns=new String编号,姓名,出生年月,性别,文化程度,联系电话,电子邮件,通讯地址;Object data=new Objectlist.size()8;for(int i=0;ilist.size();i+)datai0=list.get(i).getId();datai1=list.get(i
33、).getName();datai2=list.get(i).getBirth();if(list.get(i).getSex()=1)datai3=男;elsedatai3=女;datai4=list.get(i).getEducation();datai5=list.get(i).getPhone();datai6=list.get(i).getEmail();datai7=list.get(i).getAddress();tabModel.setDataVector(data, columns);/隐藏第一列TableColumnModel colModel=tab.getColumnM
34、odel();TableColumn column=colModel.getColumn(0);column.setMaxWidth(0);column.setMinWidth(0);column.setPreferredWidth(0);elseJOptionPane.showMessageDialog(null,returnObj.getMsg();/* * 获取链接 * param url * return */private URLConnection getCon()URLConnection con=null;try url=new URL(http:/localhost:8080
35、/Web2/EmployeeSer);con=url.openConnection();con.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false);con.connect(); catch (MalformedURLException e) / TODO Auto-generated catch blockJOptionPane.showMessageDialog(null, e.getMessage(); catch (IOException e) / TODO Auto-generated catch blockJO
36、ptionPane.showMessageDialog(null, e.getMessage();return con;/* * 清空组件框 */private void InitFrame()txtAddress.setText();txtBirth.setText();txtEmail.setText();txtPhone.setText();txtName.setText();cboEducation.setSelectedIndex(0);cboSex.setSelectedIndex(0);/* * 将对象写入服务端 * param obj */private void writeO
37、bjectToServer(Object obj)try oos=new ObjectOutputStream(urlcon.getOutputStream();oos.writeObject(obj);oos.flush();oos.close(); catch (IOException e) / TODO Auto-generated catch blockJOptionPane.showMessageDialog(null, e.getMessage();/* * 从服务端读取对象 * return */private Object readObjectFromServer()Objec
38、t objRerurn=null;try ins=urlcon.getInputStream();ois=new ObjectInputStream(ins);objRerurn=ois.readObject();ois.close(); catch (IOException e) / TODO Auto-generated catch blockJOptionPane.showMessageDialog(null, e.getMessage(); catch (ClassNotFoundException e) / TODO Auto-generated catch blockJOption
39、Pane.showMessageDialog(null, e.getMessage();return objRerurn;/* * 校验服务端是否发生异常 */private boolean checkServer()urlcon=getCon();writeObjectToServer(new TempObject();ServerObject returnObject=(ServerObject) readObjectFromServer();if(returnObject!=null)if(returnObject.getFlag()=false)JOptionPane.showMess
40、ageDialog(null, returnObject.getMsg();elsereturn returnObject.getFlag();elsereturn false;/* * 获取一个编号 * return */private int getNum()String s=Calendar.getInstance().hashCode()+;String b=s.substring(5);return Integer.parseInt(b);public static void main(String args) /try /UIManager.setLookAndFeel(UIMan
41、ager.getSystemLookAndFeelClassName();/ catch (ClassNotFoundException e) / TODO Auto-generated catch block/e.printStackTrace();/ catch (InstantiationException e) / TODO Auto-generated catch block/e.printStackTrace();/ catch (IllegalAccessException e) / TODO Auto-generated catch block/e.printStackTrac
42、e();/ catch (UnsupportedLookAndFeelException e) / TODO Auto-generated catch block/e.printStackTrace();/JFrame frame=new JFrame();frame.setLayout(new BorderLayout();ManageInfo manageInfo=new ManageInfo();frame.add(manageInfo,BorderLayout.CENTER);frame.setBounds(200, 200,800,500);frame.setVisible(true
43、);Server端的EmployeeSer代码如下:package com.zcsoft.servlet;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import javax.print.a
44、ttribute.standard.Severity;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.sun.corba.se.impl.ior.WireObjectKeyTemplate;import com.zcsoft.dao.EmployeeDao;import com.zcsoft
45、.test.Employee;import com.zcsoft.test.ServerObject;import com.zcsoft.test.TempObject;public class EmployeeSer extends HttpServlet private EmployeeDao employeeDao=null;private InputStream ins=null;private OutputStream ops=null;private ObjectInputStream ois=null;private ObjectOutputStream oos=null;pri
46、vate Object result=null;private TempObject temp=null;private ServerObject serverObject=null;public EmployeeSer() / TODO Auto-generated constructor stubserverObject=new ServerObject();try employeeDao=new EmployeeDao(); catch (ClassNotFoundException e) / TODO Auto-generated catch blockserverObject.set
47、Msg(e.getMessage();serverObject.setFlag(false); catch (SQLException e) / TODO Auto-generated catch blockserverObject.setMsg(e.getMessage();serverObject.setFlag(false);Overrideprotected void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException /若服务端初始化错误if(serverObject.getFlag()=false)writeObjectToClient(res, serverObject);return;/读取对象try result=readObjectFromClient(req); catch
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 报废食品销售合同
- 舞蹈表演培训课程
- 山西省2024八年级物理上册第二章声现象第2节声音的特性课件新版新人教版
- 河北省唐山市部分学校2024-2025学年高一上学期11月期中联考化学试卷(含答案)
- 《麻纺织品中木质素含量的测定 硫酸溶解法》
- 钢业生产安全防范
- 福建省漳州第一中学2024-2025学年七年级上学期11月期中历史试题
- 企业植树节活动方案
- 城市燃气相关行业投资方案范本
- 老年体位性低血压的护理
- 诊断与检修电动天窗
- 生产异常及停线管理规范(1)
- 结核性胸膜炎(课堂PPT)
- 渝价〔2013〕430号
- CA6132普通车床使用说明书
- 软基监测方案
- 建设工程档案文件目录
- 国家开放大学《数据结构(本)》形考作业1-4参考答案
- 如何学好英语口语ppt课件
- 消防器材登记卡
- 花木绿化养护考核评分表
评论
0/150
提交评论