【高级Java】高级Java实验
一、反射与动态代理
1、(4分)请通过反射技术,为附件中的Person.class生成相应的.java代码,java代码中的方法的方法体为空,即方法内部代码不用生成。请注意生成的java代码的格式。
2、(3分)请为第1题中Person类创建代理类 PersonProxy,PersonProxy的在代理Person类的所有setter方法时,把方法的调用时间、方法名称写入到文本文件中,每一行日志的格式为:
* 时间:2012-09-01 23:34:24;方法名称:setName;参数:张小平
3、(3分)请用动态代理技术完成第2题
1.1 experiment1
public class Person implements Speakable {private String name;//学生姓名private String Gender;//性别private String id;//身份证号private String tel;//电话public Person() {}public Person(String name, String Gender, String id, String tel) {this.name = name;this.Gender = Gender;this.id = id;this.tel = tel;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return Gender;}public void setGender(String Gender) {this.Gender = Gender;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}@Overridepublic String toString() {return "PersonRefection{" +"name='" + name + '\'' +", sex='" + Gender + '\'' +", id='" + id + '\'' +", tel='" + tel + '\'' +'}';}@Overridepublic void speak(String message) {System.out.println(message);}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.*;public class PersonRefection {static String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";static FileOutputStream fos;static {try {fos = new FileOutputStream(pathName);} catch (FileNotFoundException e) {e.printStackTrace();}}static Class clazz;static {try {clazz = Class.forName("Person");fos = new FileOutputStream(pathName);} catch (ClassNotFoundException | FileNotFoundException e) {e.printStackTrace();}}public static void getPackage(String pathName) {String packageName = clazz.getPackage().getName();String writePackage = "package " + packageName + ";\n\n";try {fos.write(writePackage.getBytes());} catch (IOException e) {e.printStackTrace();}}public static void main(final String[] args) throws NoSuchMethodException, IOException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";FileOutputStream fos = new FileOutputStream(pathName);Class clazz = Class.forName("Person");//获取类所在的包名String packageName = clazz.getPackage().getName();String writePackage = "package " + packageName + ";\n\n";fos.write(writePackage.getBytes());//获取类中的权限修饰符及类名并输出String modifier = Modifier.toString(clazz.getModifiers());String className = clazz.getSimpleName();String writeClass = modifier + " class " + className + " {\n";fos.write(writeClass.getBytes());//获取类中所有的字段Field[] fieldArray = clazz.getDeclaredFields();for (Field f : fieldArray) {String mod = Modifier.toString(f.getModifiers());String type = f.getType().getSimpleName();String name = f.getName();String writeField = "\t" + mod + " " + type + " " + name + ";\n";fos.write(writeField.getBytes());}fos.write("\n".getBytes());//获取类中所有的构造方法Constructor[] constructorArray = clazz.getConstructors();for (Constructor c : constructorArray) {String mod = Modifier.toString(c.getModifiers());String writeConstructor = "\t" + mod + " " + className + "(";//获取构造方法里面所有的参数Class[] prams = c.getParameterTypes();int count = 0;for (Class cl : prams) {String pramName = cl.getSimpleName();writeConstructor += pramName + " args" + count;if (count < prams.length - 1) {writeConstructor += ", ";}count++;}writeConstructor += ") {}\n";fos.write(writeConstructor.getBytes());}fos.write("\n".getBytes());//获取类中所有的方法Method[] methodArray = clazz.getDeclaredMethods();for (Method m : methodArray) {String mod = Modifier.toString(m.getModifiers());String type = m.getReturnType().getSimpleName();String name = m.getName();String writeMethod = "\t" + mod + " " + type + " " + name + "(";//与构造方法一样,获取方法里面所有的参数Class[] prams = m.getParameterTypes();int count = 0;for (Class cl : prams) {String pramName = cl.getSimpleName();writeMethod += pramName + " args" + count;if (count < prams.length - 1) {writeMethod += ", ";}count++;}writeMethod += ") {\n";if (type.equals("int") || type.equals("double")) {writeMethod += "\t\treturn 0;\n";} else if (type.equals("boolean")) {writeMethod += "\t\treturn false;\n";} else if (type.equals("void")) {writeMethod += "";} else {writeMethod += "\t\treturn null;\n";}writeMethod += "\t}\n\n";fos.write(writeMethod.getBytes());}fos.write("}".getBytes());}
}
import java.io.IOException;public interface Speakable {public void speak(String message);public void setName(String args0) throws IOException;public void setTel(String args0) throws IOException;public void setGender(String args0) throws IOException;public void setId(String args0) throws IOException;
}
1.2 experiment2
import homework2.experiment1.Person;import java.io.IOException;public class Bootstrap {public static void main(final String[] args) throws IOException {Person person = new Person();PersonProxy personProxy = new PersonProxy(person);personProxy.setId("123");personProxy.setName("魏乐天");}
}
public class Person {private String name;private String Gender;private String id;private String tel;public Person() {}public Person(String args0, String args1, String args2, String args3) {}public String toString() {return null;}public String getName() {return null;}public void setName(String args0) {}public String getId() {return null;}public void setGender(String args0) {}public String getTel() {return null;}public void speak(String args0) {}public void setTel(String args0) {}public String getGender() {return null;}public void setId(String args0) {}}
import homework2.experiment1.Person;
import homework2.experiment1.Speakable;import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;//2、(3分)请为第1题中Person类创建代理类 PersonProxy,PersonProxy的在代理Person类的所有setter方法时,把方法的调用时间、方法名称写入到文本文件中,每一行日志的格式为:
// 时间:2012-09-01 23:34:24;方法名称:setName;参数:张小平
public class PersonProxy implements Speakable {Person person;File file = new File("E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Log");public PersonProxy(Person person) {this.person = person;}@Overridepublic void speak(String message) {}public void setName(String name) throws IOException {WriteToText(file, "setName", name);this.person.setName(name);}public void setGender(String Gender) throws IOException {WriteToText(file, "setGender", Gender);this.person.setGender(Gender);}public void setId(String id) throws IOException {WriteToText(file, "setId", id);this.person.setId(id);}public void setTel(String tel) throws IOException {WriteToText(file, "setTel", tel);this.person.setTel(tel);}public void WriteToText(File file, String MethodName, String parameter) throws IOException {//如果文件不存在,就动态创建文件if (!file.exists()) {file.createNewFile();}FileWriter fw = null;final String writeDate = "时间:" + this.get_nowDate() + ";" + "方法名称:" + MethodName + ";参数:" + parameter;try {//设置为:True,表示写入的时候追加数据fw = new FileWriter(file, true);//回车并换行fw.write(writeDate + "\r\n");} catch (final IOException e) {e.printStackTrace();} finally {if (fw != null) {fw.close();}}}private String get_nowDate() {Calendar D = Calendar.getInstance();int year = 0;int moth = 0;int day = 0;int hour = 0;int minute = 0;int second = 0;year = D.get(Calendar.YEAR);moth = D.get(Calendar.MONTH) + 1;day = D.get(Calendar.DAY_OF_MONTH);hour = D.get(Calendar.HOUR_OF_DAY);minute = D.get(Calendar.MINUTE);second = D.get(Calendar.SECOND);String now_date = String.valueOf(year) + "-" + String.valueOf(moth)+ "-" + String.valueOf(day) + " " + String.valueOf(hour) + ":"+ String.valueOf(minute) + ":" + String.valueOf(second);return now_date;}}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;public class PersonRefection {static String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";static FileOutputStream fos;static {try {fos = new FileOutputStream(pathName);} catch (FileNotFoundException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException, ClassNotFoundException {getPackage();getClazz();getField();getConstructor();getMethod();}/*** 获取包名*/public static void getPackage() throws ClassNotFoundException, FileNotFoundException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";Class<?> clazz = Class.forName("homework2.experiment2.Person");String packageName = clazz.getPackage().getName();String writePackage = "package " + packageName + ";\n\n";try {fos.write(writePackage.getBytes());} catch (IOException e) {e.printStackTrace();}}/*** 获取类中的权限修饰符及类名并输出*/public static void getClazz() throws IOException, ClassNotFoundException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";Class<?> clazz = Class.forName("homework2.experiment2.Person");String modifier = Modifier.toString(clazz.getModifiers());String className = clazz.getSimpleName();String writeClass = modifier + " class " + className + " {\n";fos.write(writeClass.getBytes());}/*** 获取类中所有的字段*/public static void getField() throws IOException, ClassNotFoundException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";Class<?> clazz = Class.forName("homework2.experiment2.Person");Field[] fieldArray = clazz.getDeclaredFields();for (Field f : fieldArray) {String mod = Modifier.toString(f.getModifiers());String type = f.getType().getSimpleName();String name = f.getName();String writeField = "\t" + mod + " " + type + " " + name + ";\n";fos.write(writeField.getBytes());}fos.write("\n".getBytes());}/*** 获取类中所有的构造方法*/public static void getConstructor() throws IOException, ClassNotFoundException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";Class<?> clazz = Class.forName("homework2.experiment2.Person");String className = clazz.getSimpleName();Constructor[] constructorArray = clazz.getConstructors();for (Constructor c : constructorArray) {String mod = Modifier.toString(c.getModifiers());String writeConstructor = "\t" + mod + " " + className + "(";//获取构造方法里面所有的参数Class[] prams = c.getParameterTypes();int count = 0;for (Class cl : prams) {String pramName = cl.getSimpleName();writeConstructor += pramName + " args" + count;if (count < prams.length - 1) {writeConstructor += ", ";}count++;}writeConstructor += ") {}\n";fos.write(writeConstructor.getBytes());}fos.write("\n".getBytes());}/*** 获取类中所有的方法*/public static void getMethod() throws IOException, ClassNotFoundException {String pathName = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment2\\Person.java";Class<?> clazz = Class.forName("homework2.experiment2.Person");Method[] methodArray = clazz.getDeclaredMethods();for (Method m : methodArray) {String mod = Modifier.toString(m.getModifiers());String type = m.getReturnType().getSimpleName();String name = m.getName();String writeMethod = "\t" + mod + " " + type + " " + name + "(";//与构造方法一样,获取方法里面所有的参数Class[] prams = m.getParameterTypes();int count = 0;for (Class cl : prams) {String pramName = cl.getSimpleName();writeMethod += pramName + " args" + count;if (count < prams.length - 1) {writeMethod += ", ";}count++;}writeMethod += ") {\n";switch (type) {case "int":case "double":writeMethod += "\t\treturn 0;\n";break;case "boolean":writeMethod += "\t\treturn false;\n";break;case "void":writeMethod += "";break;default:writeMethod += "\t\treturn null;\n";break;}writeMethod += "\t}\n\n";fos.write(writeMethod.getBytes());}fos.write("}".getBytes());}}
1.3 experiment3
import homework2.experiment1.Speakable;import java.io.IOException;
import java.lang.reflect.Proxy;public class BootStrap {public static void main(final String[] args) throws IOException {//创建一个真实对象Person person = new Person();//创建一个动态代理对象MyProxy myProxy = new MyProxy(person);//获取被代理类的CLassLoader对象ClassLoader loader = person.getClass().getClassLoader();//动态构造一个代理对象Speakable speakable = (Speakable) Proxy.newProxyInstance(loader,new Class[]{Speakable.class},//接口对象数组,表示我们要给代理对象提供一个怎样的接口,如果提供了这样一组接口数组,就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。myProxy);speakable.setGender("man");}
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Calendar;public class MyProxy implements InvocationHandler {File file = new File("E:\\学习\\代码\\AdvancedJAVA\\src\\homework2\\experiment3\\Log");private Object proxied;public MyProxy(Object proxied) {this.proxied = proxied;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//proxy:代理类代理的真实代理对象//method:我们要调用某个对象真实的方法的Method对象//args:代理对象方法传递的参数WriteToText(file, method.getName(), (String) args[0]);method.invoke(this.proxied, args);return null;}public void WriteToText(File file, String MethodName, String parameter) throws IOException {//如果文件不存在,就动态创建文件if (!file.exists()) {file.createNewFile();}FileWriter fw = null;String writeDate = "时间:" + this.get_nowDate() + ";" + "方法名称:" + MethodName + ";参数:" + parameter;try {//设置为:True,表示写入的时候追加数据fw = new FileWriter(file, true);//回车并换行fw.write(writeDate + "\r\n");} catch (IOException e) {e.printStackTrace();} finally {if (fw != null) {fw.close();}}}private String get_nowDate() {Calendar D = Calendar.getInstance();int year = 0;int moth = 0;int day = 0;int hour = 0;int minute = 0;int second = 0;year = D.get(Calendar.YEAR);moth = D.get(Calendar.MONTH) + 1;day = D.get(Calendar.DAY_OF_MONTH);hour = D.get(Calendar.HOUR_OF_DAY);minute = D.get(Calendar.MINUTE);second = D.get(Calendar.SECOND);String now_date = String.valueOf(year) + "-" + String.valueOf(moth)+ "-" + String.valueOf(day) + " " + String.valueOf(hour) + ":"+ String.valueOf(minute) + ":" + String.valueOf(second);return now_date;}
}
public class Person implements Speakable {private String name;private String Gender;private String id;private String tel;public Person() {}public Person(String args0, String args1, String args2, String args3) {}public String toString() {return null;}public String getName() {return null;}public void setName(String args0) {}public String getId() {return null;}public void setGender(String args0) {}public String getTel() {return null;}public void speak(String args0) {}public void setTel(String args0) {}public String getGender() {return null;}public void setId(String args0) {}}
import java.io.IOException;public interface Speakable {public void speak(String message);public void setName(String args0) throws IOException;public void setTel(String args0) throws IOException;public void setGender(String args0) throws IOException;public void setId(String args0) throws IOException;
}
二、基于数据库的学生管理系统
1、请编程实现基于数据库的学生信息管理程序,程序的功能有:显示所有学生、新增学生、删除学生、修改学生、查找学生(根据学号、姓名、班级、性别、专业、学院等),程序采用命令行方式。
2、请编程实现把从数据库中查询出的学生信息记录集(ResultSet)中的记录转换为学生对象。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;//1、请编程实现基于数据库的学生信息管理程序,程序的功能有:显示所有学生、新增学生、删除学生、修改学生、查找学生(根据学号、姓名、班级、性别、专业、学院等),程序采用命令行方式。
// 2、请编程实现把从数据库中查询出的学生信息记录集(ResultSet)中的记录转换为学生对象。/*** 建立与数据库之间的连接会话,所有的操作都是基于这个会话基础上进行的*/
public class MySqlDAO {public static Connection getConnection() throws Exception {String driverName = "com.mysql.cj.jdbc.Driver"; //驱动名称String url = "jdbc:mysql://localhost:3306/student"; //连接字符串String username = "root"; //用户名String password = "lele20011019"; //密码Class.forName(driverName); //加载数据库的驱动,驱动程序自动调用DriverManger中方法将自身注册到管理器中return DriverManager.getConnection(url, username, password);}/*** 获取Statement对象,通过Statement执行SQL语句** @return* @throws Exception*/public static Statement getStatement() throws Exception {return getConnection().createStatement();}/*** 获取PreparedStatement对象,通过PreparedStatement执行SQL语句** @param sql* @return* @throws Exception*/public static PreparedStatement preparedStatement(String sql) throws Exception {return getConnection().prepareStatement(sql);}public static void connectionClose() throws Exception {getConnection().close();}
}
public class Student {private int Id; //学号private String Name; //姓名private String Gender; //性别private String college; //学院private String Major; //专业private int Clazz; //班级public Student() {}public Student(int id, String name, String gender, String college, String major, int Clazz) {this.Id = id;this.Name = name;this.Gender = gender;this.college = college;this.Major = major;this.Clazz = Clazz;}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 getGender() {return Gender;}public void setGender(String gender) {if (gender.equals("男") || gender.equals("女")) {this.Gender = gender;} else {try {throw new IllegalAccessException("性别只能为男或女");} catch (IllegalAccessException E) {E.printStackTrace();}}}public String getCollege() {return college;}public void setCollege(String college) {this.college = college;}public String getMajor() {return Major;}public void setMajor(String major) {this.Major = major;}public int getClazz() {return Clazz;}public void setClass(int Clazz) {this.Clazz = Clazz;}
}
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;import static homework3.MySqlDAO.connectionClose;public class StudentManagementSystem {static Scanner input = new Scanner(System.in);static ResultSet rs = null;public static void main(String[] args) throws Exception {
// Student student1 = new Student(1, "魏乐天", "男", "两江人工智能学院", "软件工程", 2);
// Student student2 = new Student(2, "茹祎龙", "男", "两江人工智能学院", "软件工程", 2);
// Student student3 = new Student(3, "宋梦洋", "男", "两江人工智能学院", "软件工程", 2);
// Student student4 = new Student(4, "边帝行", "男", "两江人工智能学院", "软件工程", 2);
// Student student5 = new Student(5, "张毅敏", "男", "电子与电气工程学院", "自动化", 1);startSystem();}public static void startSystem() throws Exception {while (true) {int choice;System.out.println("学生管理系统");System.out.println("请选择所需功能");System.out.println("1.创建学生信息");System.out.println("2.删除学生信息");System.out.println("3.修改学生信息");System.out.println("4.查询学生信息");System.out.println("5.退出");choice = input.nextInt();if (choice == 1) {createStudent();} else if (choice == 2) {while (true) {System.out.println("请输入要删除学生的学号(输入-1退出):");int no = input.nextInt();if (no == -1)break;deleteStudent(no);}} else if (choice == 3) {while (true) {System.out.println("输入要修改学生的学号,如果学号不存在则创建(输入-1退出)");int no = input.nextInt();if (no == -1)break;updateStudent(no);}} else if (choice == 4) {int choice1;while (true) {System.out.println("请输入查询的方式");System.out.println("1.通过学号查询");System.out.println("2.通过姓名查询");System.out.println("3.通过性别查询");System.out.println("4.通过学院查询");System.out.println("5.通过专业查询");System.out.println("6.通过班级查询");System.out.println("7.退出");choice1 = input.nextInt();if (choice1 == 1) {System.out.println("请输入学号:");int xuehao = input.nextInt();selectStudentById(xuehao);} else if (choice1 == 2) {System.out.println("请输姓名:");String name1 = input.next();selectStudentByName(name1);} else if (choice1 == 3) {System.out.println("请输入性别:");String gender1 = input.next();selectStudentByGender(gender1);} else if (choice1 == 4) {System.out.println("请输入学院:");String college1 = input.next();selectStudentByCollege(college1);} else if (choice1 == 5) {System.out.println("请输入专业:");String major1 = input.next();selectStudentByMajor(major1);} else if (choice1 == 6) {System.out.println("请输入班级:");int class1 = input.nextInt();selectStudentByClass(class1);} else {break;}}} else {break;}}}public static void createStudent() throws Exception {System.out.println("请输入你想创建的学生的信息(输入-1退出):");int no, clazz;String name, gender, college, major;while (true) {System.out.println("学号:");no = input.nextInt();if (no == -1)break;System.out.println("姓名:");name = input.next();if (name.equals("-1"))break;System.out.println("性别:");gender = input.next();if (gender.equals("-1"))break;System.out.println("学院:");college = input.next();if (college.equals("-1"))break;System.out.println("专业:");major = input.next();if (major.equals("-1"))break;System.out.println("班级:");clazz = input.nextInt();if (clazz == -1)break;Student newStudent = new Student(no, name, gender, college, major, clazz);insertStudent(newStudent);}}public static boolean tableNameExist(String tableName) throws Exception {String sql = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='student' and TABLE_NAME='" + tableName + "'";PreparedStatement ps = MySqlDAO.preparedStatement(sql);ps.execute();ResultSet rs = ps.executeQuery();rs.close();ps.close();connectionClose();return rs.next();}/*** 建表*/public static void createTable(String tableName) throws Exception {String sql = "create table " + tableName + "(No int primary key, name char(20),gender char(4),college char(100),major char(100),Class int)";if (!tableNameExist(tableName)) {PreparedStatement ps = MySqlDAO.preparedStatement(sql);ps.execute();ps.close();} else {try {throw new Exception("该表已经存在");} catch (Exception E) {E.printStackTrace();}}}/*** 插入学生信息*/public static void insertStudent(Student student) throws Exception {String sql = "insert into student values(?,?,?,?,?,?)";PreparedStatement ps = MySqlDAO.preparedStatement(sql);ps.setInt(1, student.getId());ps.setString(2, student.getName());ps.setString(3, student.getGender());ps.setString(4, student.getCollege());ps.setString(5, student.getMajor());ps.setInt(6, student.getClazz());ps.execute();ps.close();connectionClose();}/*** 删除学生信息*/public static void deleteStudent(int no) throws Exception {String sql = "delete from student where No=?";PreparedStatement ps = MySqlDAO.preparedStatement(sql);ps.setInt(1, no);ps.execute();ps.close();connectionClose();}/*** 更新学生信息*/public static void updateStudent(int no) throws Exception {int clazz;String name, gender, college, major;deleteStudent(no);System.out.println("姓名:");name = input.next();System.out.println("性别:");gender = input.next();System.out.println("学院:");college = input.next();System.out.println("专业:");major = input.next();System.out.println("班级:");clazz = input.nextInt();Student newStudent = new Student(no, name, gender, college, major, clazz);insertStudent(newStudent);}/*** 打印学生信息*/public static void printInformation(ResultSet rs) throws SQLException {while (rs.next()) {System.out.println("id: " + rs.getInt("no"));System.out.println("name: " + rs.getString("name"));System.out.println("gender: " + rs.getString("gender"));System.out.println("college: " + rs.getString("college"));System.out.println("major: " + rs.getString("major"));System.out.println("class: " + rs.getInt("class"));System.out.println();}}public static void executeToRs(PreparedStatement ps) throws Exception {rs = ps.executeQuery();ps.close();connectionClose();}/*** 通过id查询学生信息*/public static void selectStudentById(int id) throws Exception {String sql = "select * from student where no = " + id;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}/*** 通过name查询学生信息*/public static void selectStudentByName(String name) throws Exception {String sql = "select * from student where name = " + name;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}/*** 通过性别查询学生信息*/public static void selectStudentByGender(String gender) throws Exception {String sql = "select * from student where gender = " + gender;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}/*** 通过学院查询学生信息*/public static void selectStudentByCollege(String college) throws Exception {String sql = "select * from student where college = " + college;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}/*** 通过专业查询学生信息*/public static void selectStudentByMajor(String major) throws Exception {String sql = "select * from student where major = " + major;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}/*** 通过班级查询学生信息*/public static void selectStudentByClass(int clazz) throws Exception {String sql = "select * from student where class = " + clazz;PreparedStatement ps = MySqlDAO.preparedStatement(sql);executeToRs(ps);printInformation(rs);ps.close();connectionClose();}public static void rsToObject(ResultSet rs) throws SQLException {List<Student> students = new ArrayList<>();while (rs.next()) {int no = rs.getInt("no");String name = rs.getString("name");String gender = rs.getString("gender");String college = rs.getString("college");String major = rs.getString("major");int clazz = rs.getInt("class");students.add(new Student(no, name, gender, college, major, clazz));}}}
三、注解、
3.1 experiment1
1.创建Person类,Person的属性有:
* String name 姓名
* String sex 性别
* Integer age 年龄,
* String idNo 身份证号
* Boolean isMarried 是否已婚
* 请生成相应的getter、setter方法。请编写注解@Label,表示所注解对象的中文名称,√
* 请把@Label注解标注在Person类和Person的每个属性上面。√
* 请编写PersonInput类,负责提示录入人员的相关属性,提示必须是注解@Label所标注的中文名称。√
* 请编写PersonDisplay,负责显示人员信息,显示时的属性名称必须为注解@Label所标注的中文名称√,
* PersonInput类与PersonDisplay类实现了共同的接口PersonAction,接口PersonAction有方法process,方法process的签名为:public Person process(Person person);√
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Label {String value();
}
//注解处理器接口
public interface PersonAction {public Person process(Person person) throws IllegalAccessException;
}
public class Person {@Label("姓名")String name; //姓名@Label("性别")String sex; //性别@Label("年龄")Integer age; //年龄@Label("身份证号")String idNo; //身份证号@Label("是否已婚")Boolean isMarried; //是否已婚public Person() {}public Person(String name, String sex, Integer age, String idNo, boolean isMarried) {this.name = name;this.sex = sex;this.age = age;this.idNo = idNo;this.isMarried = isMarried;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getIdNo() {return idNo;}public void setIdNo(String idNo) {this.idNo = idNo;}public Boolean isMarried() {return isMarried;}public void setMarried(Boolean married) {isMarried = married;}
}
import java.lang.reflect.Field;/*** 负责显示人员信息,显示时的属性名称必须为注解@Label所标注的中文名称,*/
public class PersonDisplay implements PersonAction {@Overridepublic Person process(Person person) throws IllegalAccessException {Class clazz = person.getClass();Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {//获取Label注解的value值if (field.isAnnotationPresent(Label.class)) {String name = field.getAnnotation(Label.class).value();System.out.print(name + ":");}//获取属性的值Object obj = field.get(person);System.out.println(obj);}return person;}
}
import java.lang.reflect.Field;
import java.util.Scanner;/*** 负责提示录入人员的相关属性,提示必须是注解@Label所标注的中文名称。*/
public class PersonInput implements PersonAction {@Overridepublic Person process(Person person) throws IllegalAccessException {Scanner input = new Scanner(System.in);Class clazz = person.getClass();//获取Class对象Field[] fields = clazz.getDeclaredFields();//通过Class对象获取Field对象//遍历获取的person对象的所有字段for (Field field : fields) {Object obj = field.get(person);if (obj == null) {String s = field.getAnnotation(Label.class).value();System.out.print("请输入" + s + ":");String s1 = input.next();if (field.getType().getName().contains("String")) {//获取的字段是String类型field.set(person, s1);} else if (field.getType().getName().contains("Integer")) {//获取的字段是Integer类型field.set(person, Integer.parseInt(s1));} else if (field.getType().getName().contains("Boolean")) {//获取字段是Boolean类型field.set(person, Boolean.parseBoolean(s1));}}}return person;}
}
public class text {public static void main(String[] args) throws IllegalAccessException {Person person = new Person();PersonInput personInput = new PersonInput();personInput.process(person);PersonDisplay personDisplay = new PersonDisplay();personDisplay.process(person);}
}
3.2 experiment2
2.在第一题目的基础上,编写注解@Column,
// 属性有Label 表示类的属性的显示名称,
// Nullable 表示是否允许属性值为空,
// MaxLength 表示文本属性的最大长度,
// MinLength表示文本属性的最小长度,
// MaxValue表示最大值,
// MinValue表示最小值,
// 把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。
// 第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。
// 并利用JDBC,实现数据库操作。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;// 2.在第一题目的基础上,编写注解@Column,
// 属性有Label 表示类的属性的显示名称,
// Nullable 表示是否允许属性值为空,
// MaxLength 表示文本属性的最大长度,
// MinLength表示文本属性的最小长度,
// MaxValue表示最大值,
// MinValue表示最小值,
// 把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。
// 第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。
// 并利用JDBC,实现数据库操作。
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {Label label(); // 表示类的属性的显示名称,boolean Nullable() default false;// Nullable 表示是否允许属性值为空int MaxLength() default 100;// MaxLength 表示文本属性的最大长度int MinLength() default 0;// MinLength表示文本属性的最小长度int MaxValue() default 999999999;// MaxValue表示最大值int MinValue() default 0;// MinValue表示最小值}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Label {String value();
}
package homework4.experiment;import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;/*** 把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。* 第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。* 并利用JDBC,实现数据库操作。*/
public class CreateSQL {static PreparedStatement pd = null;static ResultSet rs;static Scanner input = new Scanner(System.in);public String CreateTable(Person person) {Class<? extends Person> clazz = person.getClass();Field[] fields = clazz.getDeclaredFields();Label name = clazz.getAnnotation(Column.class).label();StringBuilder sql = new StringBuilder("create table if not exists " + name.value() + "(\n");for (Field field : fields) {String str = field.getAnnotation(Column.class).label().value();int maxLength = field.getAnnotation(Column.class).MaxLength();//如果时Integer类型if (field.getType().getName().contains("Integer")) {sql.append(str).append(" int,\n");}//如果是Boolean或者String类型if (field.getType().getName().contains("String") || field.getType().getName().contains("Boolean")) {sql.append(str).append(" varchar(").append(maxLength).append("),\n");}//添加主键if (str.equals("身份证号")) {sql = new StringBuilder(sql.substring(0, sql.length() - 2));//截取字符串sql.append(" primary key,\n");}}sql = new StringBuilder(sql.substring(0, sql.length() - 2));sql.append("\n);");System.out.println(sql);return sql.toString();}public String InsertInf(Person person) {Class<? extends Person> clazz = person.getClass();Label name = clazz.getAnnotation(Column.class).label();StringBuilder sql = new StringBuilder("insert into " + name.value() + " values(");Field[] fields = clazz.getDeclaredFields();for (int i = 0; i < fields.length; i++) {Field field = fields[i];String value = field.getAnnotation(Column.class).label().value();System.out.println("请输入" + value + ": ");String str = input.next();//根据注解@Column的配置进行校验if (!isTrue(field, str)) {i--;continue;}//判断性别输入是否输入正确if (value.equals("性别")) {if (!str.equals("男") && !str.equals("女")) {System.out.println("您输入的性别不符合规范请重新输入!");i--;continue;}}//判断是否结婚输入是否正确if (value.equals("是否结婚")) {if (!str.equals("是") && !str.equals("否")) {System.out.println("您输入的结婚情况不符合规范请重新输入!");i--;continue;}}if (!isContainNum(str)) {sql.append("'").append(str).append("'").append(", ");} else {sql.append(str).append(", ");}}sql = new StringBuilder(sql.substring(0, sql.length() - 2));sql.append(");");System.out.println(sql);return sql.toString();}public String deleteInf(Person person) {Class<? extends Person> clazz = person.getClass();Label name = clazz.getAnnotation(Column.class).label();StringBuilder sql = new StringBuilder("delete from " + name.value() + " where ");Field[] fields = clazz.getDeclaredFields();String value = fields[0].getAnnotation(Column.class).label().value();System.out.println("请输入您要删除的" + value + ": ");String str = input.next();if (!isContainNum(str)) {sql.append(value).append(" = ").append("'").append(str).append("'");} elsesql.append(value).append(" = ").append(str).append(";");System.out.println(sql);return sql.toString();}//更新操作public String updateInf(Person person) {Class<? extends Person> clazz = person.getClass();Label tableName = clazz.getAnnotation(Column.class).label();String sql = "update " + tableName.value() + " set ";Field[] fields = clazz.getDeclaredFields();String[] values = new String[fields.length];System.out.println("请输入要修改的姓名:");String str2 = input.nextLine();System.out.println("请选择您要修改的属性:");for (int i = 0; i < values.length; i++) {values[i] = fields[i].getAnnotation(Column.class).label().value();System.out.println((i + 1) + "--" + values[i]);}String choice = input.nextLine();int choiceNum = Integer.parseInt(choice);String str1;while (true) {System.out.println("请输入修改后的值:");str1 = input.nextLine();if (isTrue(fields[choiceNum - 1], str1)) {break;}}switch (choiceNum) {case 1:if (!isContainNum(str1)) {sql += values[0] + " = " + "\"" + str1 + "\"";} else {sql += values[0] + " = " + str1;}break;case 2:if (!isContainNum(str1)) {sql += values[1] + " = " + "\"" + str1 + "\"";} else {sql += values[1] + " = " + str1;}break;case 3:if (!isContainNum(str1)) {sql += values[2] + " = " + "\"" + str1 + "\"";} else {sql += values[2] + " = " + str1;}break;case 4:if (!isContainNum(str1)) {sql += values[3] + " = " + "\"" + str1 + "\"";} else {sql += values[3] + " = " + str1;}break;case 5:if (!isContainNum(str1)) {sql += values[4] + " = " + "\"" + str1 + "\"";} else {sql += values[4] + " = " + str1;}break;default:break;}if (!isContainNum(str2)) {sql += " where " + fields[0].getAnnotation(Column.class).label() + " = " + "\"" + str2 + "\"";} else {sql += " where " + fields[0].getAnnotation(Column.class).label() + " = " + str2;}System.out.println(sql);return sql;}//根据注解@Column的配置进行校验public boolean isTrue(Field f, String str) {String value = f.getAnnotation(Column.class).label().value();boolean nullable = f.getAnnotation(Column.class).Nullable();int maxLength = f.getAnnotation(Column.class).MaxLength();int minLength = f.getAnnotation(Column.class).MinLength();int maxValue = f.getAnnotation(Column.class).MaxValue();int minValue = f.getAnnotation(Column.class).MinValue();if (!nullable && str.isEmpty()) {System.out.println("输入的信息不能为空!请重新输入");return false;}if (maxLength == 0) {int num;try {num = Integer.parseInt(str);} catch (Exception e) {System.out.println("您输入的" + value + "不符合规范!请重新输入");return false;}if (num < minValue || num > maxValue) {System.out.println("您输入的" + value + "不符合规范!请重新输入");return false;}} else {int len = str.length();if (len > maxLength || len < minLength) {System.out.println("您输入的" + value + "不符合规范!请重新输入");return false;}}return true;}public static boolean isContainNum(String str) {for (int i = 0; i < str.length(); i++) {if (str.charAt(i) > '0' && str.charAt(i) < '9') {return true;}}return false;}
}
public class demo {public static void main(String[] args) {Person person = new Person();Class<? extends Person> c = person.getClass();Label l = c.getAnnotation(Column.class).label();System.out.println(l.value());}
}
package homework4.experiment;import java.sql.PreparedStatement;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Scanner;/*** 把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。* 第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。* 并利用JDBC,实现数据库操作。*/
public class ExecuteSQL {static PreparedStatement ps = null;static CreateSQL sql = new CreateSQL();static Scanner input = new Scanner(System.in);static Person person = new Person();public static void main(String[] args) throws Exception {mainMenu();closeConnection();}public static void mainMenu() throws Exception {System.out.println("请选择您要进行的操作:");System.out.println("1--自动生成表Person");System.out.println("2--增加数据");System.out.println("3--删除数据");System.out.println("4--修改数据");System.out.println("5--退出程序");Scanner sc = new Scanner(System.in);int choice = sc.nextInt();switch (choice) {case 1:createTable();mainMenu();break;case 2:insert();mainMenu();break;case 3:delete();mainMenu();break;case 4:update();mainMenu();break;case 5:break;default:System.out.println("请输入正确的选项!");mainMenu();break;}}//建表public static void createTable() throws Exception {System.out.println("生成表中......");String create = sql.CreateTable(person);ps = MySqlDAO.preparedStatement(create);ps.executeUpdate();System.out.println("成功生成");}//向表中添加信息public static void insert() throws Exception {try {String insertSQL = sql.InsertInf(person);ps = MySqlDAO.preparedStatement(insertSQL);ps.executeUpdate();} catch (SQLIntegrityConstraintViolationException e) {System.out.println("您输入的身份证号码有重复,请重新输入");insert();}}//删除信息1public static void delete() throws Exception {String deleteSQL = sql.deleteInf(person);ps = MySqlDAO.preparedStatement(deleteSQL);ps.executeUpdate();}//更新信息public static void update() throws Exception {String updateSQL = sql.updateInf(person);ps = MySqlDAO.preparedStatement(updateSQL);ps.executeUpdate();}public static void closeConnection() throws Exception {ps.close();MySqlDAO.getConnection().close();}}
package homework4.experiment;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;public class MySqlDAO {public static Connection getConnection() throws Exception {String driverName = "com.mysql.cj.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/demo";String userName = "root";String password = "";//自行填写密码Class.forName(driverName);Connection con = DriverManager.getConnection(url, userName, password);return con;}public static PreparedStatement preparedStatement(String sql) throws Exception {return getConnection().prepareStatement(sql);}
}
package homework4.experiment;/*** 1.创建Person类,Person的属性有:* String name 姓名* String sex 性别* Integer age 年龄,* String idNo 身份证号* Boolean isMarried 是否已婚* 请生成相应的getter、setter方法。请编写注解@Label,表示所注解对象的中文名称,√* 请把@Label注解标注在Person类和Person的每个属性上面。√* 请编写PersonInput类,负责提示录入人员的相关属性,提示必须是注解@Label所标注的中文名称。√* 请编写PersonDisplay,负责显示人员信息,显示时的属性名称必须为注解@Label所标注的中文名称√,* PersonInput类与PersonDisplay类实现了共同的接口PersonAction,接口PersonAction有方法process,方法process的签名为:public Person process(Person person);√*/
@Column(label = @Label("Person"))
public class Person {@Column(label = @Label("姓名"))String name; //姓名@Column(label = @Label("性别"))String sex; //性别@Column(label = @Label("年龄"), MaxValue = 120)Integer age; //年龄@Column(label = @Label("身份证号"))String idNo; //身份证号@Column(label = @Label("是否已婚"))Boolean isMarried; //是否已婚public Person() {}public Person(String name, String sex, Integer age, String idNo, boolean isMarried) {this.name = name;this.sex = sex;this.age = age;this.idNo = idNo;this.isMarried = isMarried;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getIdNo() {return idNo;}public void setIdNo(String idNo) {this.idNo = idNo;}public Boolean isMarried() {return isMarried;}public void setMarried(Boolean married) {isMarried = married;}
}
四、TCP、UDP
4.1 experiment1
请分别采用TCP、UDP协议编程实现一对一的文件上传。
TCP:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;public class Client {public static void main(String[] args) throws Exception {//1.创建一个socket连接Socket socket = new Socket(InetAddress.getByName("localhost"), 9000);//2.创建一个输出流OutputStream os = socket.getOutputStream();//3.文件流,读入文件FileInputStream fis = new FileInputStream(new File("E:\\学习\\代码\\AdvancedJAVA\\src\\homework5\\experiment1\\header-logo.png"));//4.写出文件byte[] buffer = new byte[1024];int lens;while ((lens = fis.read(buffer)) != -1) {os.write(buffer, 0, lens);}//通知服务器,我已经传输完了,已经结束了。socket.shutdownOutput();//我已经传输完了// 确定服务器接收完毕,才能够断开连接InputStream is = socket.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer2 = new byte[1024];int lens2;while ((lens2 = is.read(buffer2)) != -1) {baos.write(buffer2, 0, lens2);}System.out.println(baos.toString());//5.关闭资源baos.close();fis.close();os.close();socket.close();}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;public class Server {public static void main(String[] args) throws IOException {//1创建服务ServerSocket serverSocket = new ServerSocket(9000);//2监听客户端的连接Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端。//3获取输入流InputStream is = socket.getInputStream();//4文件输出,管道输出流FileOutputStream fos = new FileOutputStream(new File("receive.png"));byte[] buffer = new byte[1024];int lens;while ((lens = is.read(buffer)) != -1) {fos.write(buffer, 0, lens);}//通知客户端我接受完毕了OutputStream os = socket.getOutputStream();os.write("我接收完毕了,你可以断开了".getBytes(StandardCharsets.UTF_8));//关闭资源os.close();fos.close();is.close();socket.close();serverSocket.close();}
}
UDP:
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;public class receive {public static void main(String[] args) throws Exception {//开放端口DatagramSocket socket = new DatagramSocket(9090);//接收数据(包)byte[] buffer = new byte[1024];DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接收socket.receive(packet);//将得到的packet进行拆包int len = packet.getLength();byte[] data = packet.getData();String str = new String(data, 0, len);//利用FileOutputStream将数据写入到文件中String targetPath = "E:\\学习\\代码\\AdvancedJAVA\\src\\homework5\\experiment1\\21.png";FileOutputStream fos = new FileOutputStream(targetPath);fos.write(str.getBytes());//关闭相关流System.out.println("文件上传完毕");fos.close();socket.close();//关闭连接socket.close();}
}
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;//不需要连接服务器
public class send {public static void main(String[] args) throws Exception {//1.建立一个socketDatagramSocket socket = new DatagramSocket();//2.建立一个包//发送给谁InetAddress localhost = InetAddress.getByName("localhost");int port = 9090;FileInputStream fis = new FileInputStream("E:\\学习\\代码\\AdvancedJAVA\\src\\homework5\\experiment1\\2.png");byte[] buffer = new byte[1024];int lens;String str = "";while ((lens = fis.read(buffer)) != -1) {str += new String(buffer, 0, lens);}buffer = str.getBytes();DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localhost, port);//3.发送包socket.send(packet);//关闭流socket.close();}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;//不需要连接服务器
public class UDPClient {public static void main(String[] args) throws Exception {//建立一个SocketDatagramSocket socket = new DatagramSocket();//建个包String msg = "你好啊,服务器!";//发送给谁InetAddress address = InetAddress.getByName("localhost");int port = 9090;//数据,数据的起始长度,要发送给谁DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, address, port);//发送包socket.send(packet);//关闭socket.close();}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;public class UDPReceive {public static void main(String[] args) throws Exception {//开放端口DatagramSocket socket = new DatagramSocket(9090);//接收数据(包)byte[] buffer = new byte[1024];DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接收socket.receive(packet);System.out.println(packet.getAddress().getHostAddress());System.out.println(new String(packet.getData(), 0, packet.getLength()));socket.close();}
}
4.2 experiment2
2.编写一对多的聊天程序,程序由服务器和客户端两部分构成,两部分的交互方式如下:
a.客户端发送命令:<register name=”xu”/> 给服务器端注册用户,服务器端如果允许注册,则返回消息:<result command=”register” state=”ok” />,否则返回消息:<result command=”register” state=”error” message=”” />
b.客户端发送命令:<login name=”xu”/> 给服务器端进行登录, 服务器端如果允许登录,则返回消息:<result command=” login ” state=”ok” />,否则返回消息:<result command=”login” state=”error” message=”” />;
c.客户端发送命令:<message from=”xu” to=”zhang” message=”this is a test”> 给服务器端,服务器端收到命令后返回消息:<result command=” message ” state=”ok” />;
d.服务器向指定客户端发送命令:<message from=”xu” to=”zhang” message=”this is a test”>,如果客户端收到消息,则返回:<result command=” message ” state=”ok” />,如果message命令中的 from属性为空,则表示由服务器发送的消息。
e.客户端发送命令:<logout name=”xu”/> 给服务器端进行注销登录, 服务器端如果允许注销登录,则返回消息:<result command=” logout ” state=”ok” />,否则返回消息:<result command=”loginout” state=”error” message=”” />;
程序可以采用GUI,也可采用命令行的方式。
package homework5.experiment2;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;public class Client01 {private static String user;public static void main(String[] args) throws IOException {System.out.println("————————欢迎来到魏乐天设计的聊天界面窗口————————");Socket socket = new Socket(InetAddress.getByName("localhost"), 8888);Scanner scanner = new Scanner(System.in);while (true) {InputStreamReader reader = new InputStreamReader(socket.getInputStream());BufferedReader bufferedReader = new BufferedReader(reader);PrintWriter writer = new PrintWriter(socket.getOutputStream());System.out.println("输入相应数字选择您要进行的操作");System.out.println("1--注册用户");System.out.println("2--登陆账户");System.out.println("3--发送信息");System.out.println("4--登出账户");System.out.println("5--接收信息");System.out.println("其他数字--退出系统");int choice = scanner.nextInt();String instruction = "";if (choice == 1) {System.out.print("请输入您想要注册的账户名称:");String name = scanner.next();instruction = "<register name=\"" + name + "\"/> ";writer.println(instruction);writer.flush();} else if (choice == 2) {System.out.print("请输入您想要登录的账户名称:");user = scanner.next();instruction = "<login name=\"" + user + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 3) {System.out.print("请输入您想要发送的用户名称:");String toUser = scanner.next();System.out.println(toUser);System.out.println("你说:");String message = scanner.next();System.out.println(message);instruction = "<message from=\"" + user + "\" to=\"" + toUser + "\" message=\"" + message + "\">";writer.println(instruction);writer.flush();} else if (choice == 4) {System.out.print("请输入您想要登出的账户:");String name = scanner.next();instruction = "<logout name=\"" + name + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 5) {System.out.println("等待接受消息中...");String response0 = bufferedReader.readLine();String[] strings = response0.split("\"");String fromUser = strings[7];String message = strings[5];System.out.println(fromUser + "说:" + message);continue;} else {instruction = "<quit>";writer.println(instruction);writer.flush();break;}String response = bufferedReader.readLine();String[] strings = response.split("\"");String command = strings[1];String state = strings[3];if (command.equals("register")) {if (state.equals("ok")) {System.out.println("注册成功!");} else {System.out.println("已存在该用户,注册失败请重新注册");}} else if (command.equals("login")) {if (state.equals("ok")) {System.out.println("登陆成功!");} else {System.out.println("该用户不存在(或重复登陆),请重新登录");}} else if (command.equals("logout")) {if (state.equals("ok")) {System.out.println("成功退出账户!");} else {System.out.println("该账户不存在(未登录),请重试");}} else if (command.equals("message")) {if (state.equals("ok")) {System.out.println("成功发送消息!");} else {System.out.println("您对话的用户不存在(未登录),请重试");}}}socket.close();System.out.println("---成功退出系统---");}
}
package homework5.experiment2;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;public class Client02 {private static String user;public static void main(String[] args) throws IOException {System.out.println("————————欢迎来到魏乐天设计的聊天界面窗口————————");Socket socket = new Socket(InetAddress.getByName("localhost"), 8888);Scanner scanner = new Scanner(System.in);while (true) {InputStreamReader reader = new InputStreamReader(socket.getInputStream());PrintWriter writer = new PrintWriter(socket.getOutputStream());BufferedReader bufferedReader = new BufferedReader(reader);System.out.println("请选择您要进行的操作");System.out.println("1--注册用户");System.out.println("2--登陆账户");System.out.println("3--发送信息");System.out.println("4--登出账户");System.out.println("5--接收信息");System.out.println("其他数字--退出系统");int choice = scanner.nextInt();String instruction = "";if (choice == 1) {System.out.print("请输入您想要注册的账户名称:");String name = scanner.next();instruction = "<register name=\"" + name + "\"/> ";writer.println(instruction);writer.flush();} else if (choice == 2) {System.out.print("请输入您想要登录的账户名称:");user = scanner.next();instruction = "<login name=\"" + user + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 3) {System.out.print("请输入您想要发送的用户名称:");String toUser = scanner.next();System.out.println(toUser);System.out.println("你说:");String message = scanner.next();System.out.println(message);instruction = "<message from=\"" + user + "\" to=\"" + toUser + "\" message=\"" + message + "\">";System.out.println(instruction);writer.println(instruction);writer.flush();} else if (choice == 4) {System.out.print("请输入您想要登出的账户:");String name = scanner.next();instruction = "<logout name=\"" + name + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 5) {System.out.println("等待接受消息中...");String response0 = bufferedReader.readLine();String[] strings = response0.split("\"");String fromUser = strings[7];String message = strings[5];System.out.println(fromUser + "说:" + message);continue;} else {instruction = "<quit>";writer.println(instruction);writer.flush();break;}String response = bufferedReader.readLine();String[] strings = response.split("\"");String command = strings[1];String state = strings[3];if (command.equals("register")) {if (state.equals("ok")) {System.out.println("注册成功!");} else {System.out.println("已存在该用户,注册失败请重新注册");}} else if (command.equals("login")) {if (state.equals("ok")) {System.out.println("登陆成功!");} else {System.out.println("该用户不存在(或重复登陆),请重新登录");}} else if (command.equals("logout")) {if (state.equals("ok")) {System.out.println("成功退出账户!");} else {System.out.println("该账户不存在(未登录),请重试");}} else if (command.equals("message")) {if (state.equals("ok")) {System.out.println("成功发送消息!");} else {System.out.println("您对话的用户不存在(未登录),请重试");}}}socket.close();System.out.println("---成功退出系统---");}
}
package homework5.experiment2;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;public class Client03 {private static String user;public static void main(String[] args) throws IOException {System.out.println("————————欢迎来到魏乐天设计的聊天界面窗口————————");Socket socket = new Socket(InetAddress.getByName("localhost"), 8888);Scanner scanner = new Scanner(System.in);while (true) {InputStreamReader reader = new InputStreamReader(socket.getInputStream());BufferedReader bufferedReader = new BufferedReader(reader);PrintWriter writer = new PrintWriter(socket.getOutputStream());System.out.println("请选择您要进行的操作");System.out.println("1--注册用户");System.out.println("2--登陆账户");System.out.println("3--发送信息");System.out.println("4--登出账户");System.out.println("5--接收信息");System.out.println("其他数字--退出系统");int choice = scanner.nextInt();String instruction = "";if (choice == 1) {System.out.print("请输入您想要注册的账户名称:");String name = scanner.next();instruction = "<register name=\"" + name + "\"/> ";writer.println(instruction);writer.flush();} else if (choice == 2) {System.out.print("请输入您想要登录的账户名称:");user = scanner.next();instruction = "<login name=\"" + user + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 3) {System.out.print("请输入您想要发送的用户名称:");String toUser = scanner.next();System.out.println(toUser);System.out.println("你说:");String message = scanner.next();System.out.println(message);instruction = "<message from=\"" + user + "\" to=\"" + toUser + "\" message=\"" + message + "\">";writer.println(instruction);writer.flush();} else if (choice == 4) {System.out.print("请输入您想要登出的账户:");String name = scanner.next();instruction = "<logout name=\"" + name + "\"/>";writer.println(instruction);writer.flush();} else if (choice == 5) {System.out.println("等待接受消息中...");String response0 = bufferedReader.readLine(); //当没有客户端发送消息时会在这里阻塞,直到收到消息String[] strings = response0.split("\"");String fromUser = strings[7];String message = strings[5];System.out.println(fromUser + "说:" + message);continue;} else {instruction = "<quit>";writer.println(instruction);writer.flush();break;}String response = bufferedReader.readLine();String[] strings = response.split("\"");String command = strings[1];String state = strings[3];if (command.equals("register")) {if (state.equals("ok")) {System.out.println("注册成功!");} else {System.out.println("已存在该用户,注册失败请重新注册");}} else if (command.equals("login")) {if (state.equals("ok")) {System.out.println("登陆成功!");} else {System.out.println("该用户不存在(或重复登陆),请重新登录");}} else if (command.equals("logout")) {if (state.equals("ok")) {System.out.println("成功退出账户!");} else {System.out.println("该账户不存在(未登录),请重试");}} else if (command.equals("message")) {if (state.equals("ok")) {System.out.println("成功发送消息!");} else {System.out.println("您对话的用户不存在(未登录),请重试");}}}socket.close();System.out.println("---成功退出系统---");}
}
package homework5.experiment2;import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;public class Server {//利用图存储用户的登录状态static Hashtable<String, Boolean> user = new Hashtable<>();//利用图存储用户登录的客户端static Hashtable<String, PrintWriter> client = new Hashtable<>();public static void main(String[] args) throws IOException {//服务器在本机8888端口进行监听,等待连接ServerSocket serverSocket = new ServerSocket(8888);System.out.println("服务器在本机8888端口进行监听,等待连接...");while (true) {Socket socket = serverSocket.accept();System.out.println("成功监听到客户端" + socket.getPort());SocketHandler handler = new SocketHandler(socket);Thread thread = new Thread(handler);thread.start();}}
}
package homework5.experiment2;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;public class SocketHandler implements Runnable {private Socket socket;public SocketHandler(Socket socket) {this.socket = socket;}@Overridepublic void run() {try {InputStreamReader reader = new InputStreamReader(socket.getInputStream());BufferedReader bufferedReader = new BufferedReader(reader);PrintWriter writer = new PrintWriter(socket.getOutputStream());PrintWriter toWriter = null;while (true) {String request = bufferedReader.readLine();if (request == null) {continue;}String line = "";String[] strings = request.split("\"");String name = strings[1];if (request.startsWith("<register")) {if (!Server.user.containsKey(name)) {Server.user.put(name, false);line = "<result command=\"register\" state=\"ok\" />";} else {line = "<result command=\"register\" state=\"error\" message=\"\" />";}writer.println(line);writer.flush();} else if (request.startsWith("<login")) {if (Server.user.containsKey(name) && !Server.user.get(name)) {line = "<result command=\"login\" state=\"ok\" />";Server.user.put(name, true);Server.client.put(name, writer);} else {line = "<result command=\"login\" state=\"error\" message=\"\"/>";}writer.println(line);writer.flush();} else if (request.startsWith("<message")) {String toUser = strings[3];String message = strings[5];if (Server.user.containsKey(toUser) && Server.user.get(toUser)) {toWriter = Server.client.get(toUser);System.out.println(toUser);System.out.println(toWriter);line = "<result command= \"message\" state=\"ok\" message = \"" + message + "\" form = \"" + name + "\"/>";toWriter.println(line);toWriter.flush();} else {line = "<result command= \"message\" state=\"error\" message=\"\" />";}writer.println(line);writer.flush();} else if (request.startsWith("<logout")) {if (Server.user.containsKey(name) && Server.user.get(name)) {Server.user.put(name, true);line = "<result command= \"logout\" state=\"ok\" />";} else {line = "<result command=\"logout\" state=\"error\" message=\"\" />";}writer.println(line);writer.flush();break;}}//关闭相关流writer.close();toWriter.close();bufferedReader.close();socket.close();} catch (IOException e) {e.printStackTrace();}}
}
相关文章:
【高级Java】高级Java实验
一、反射与动态代理1、(4分)请通过反射技术,为附件中的Person.class生成相应的.java代码,java代码中的方法的方法体为空,即方法内部代码不用生成。请注意生成的java代码的格式。2、(3分)请为第1…...
SYN480R 解码
目录1.空载情况下2.当有按键被按下3.数据帧分析4.同步码5.数据码6.对24位数据帧分析1.空载情况下 在空载情况下,syn480r 输出引脚,输出的是杂乱无序的波形 2.当有按键被按下 按下按键,会连续输出相同的脉冲波形,放大分析 3.数据…...
ASP .NET(基于.NET 6.0)源码解读
这几天一直在琢磨在我现有技术认知基础上,未来如何做技术提升。 日思夜想,我整理出了我自己的一套学习规划方案,并希望在实施过程中能够不断调整学习方案与方式,以接近自我提升的效率最大化。 从以下几个大的方面来得到提升&…...
阿里工作7年,一个30岁女软件测试工程师的心路历程
简单的先说一下,坐标杭州,14届本科毕业,算上年前在阿里巴巴的面试,一共有面试了有6家公司(因为不想请假,因此只是每个晚上去其他公司面试,所以面试的公司比较少) 其中成功的有4家&am…...
学生党必备的 Keychron 无线机械键盘
学生党必备的 Keychron 无线机械键盘 由于专业需要,之间的键盘使用起来不太舒服,于是准备重新买一个适合工作学习的键盘,于是通过朋友介绍了解到了keychron k3pro,当时也看到网上一些资料说道这款键盘比较到位,今天就来带大家了解…...
FPGA MAX 10 10M50系列10M50DAF484C8G/10M50DAF484C7G/10M50DCF484C7G规格
介绍MAX 10器件是单芯片、非易失性低成本可编程逻辑器件(pld),用于集成最优的系统组件集。MAX 10设备的亮点包括:内部存储双配置闪存用户闪存即时支持集成模数转换器(adc)支持Nios II单芯片软核处理器MAX 10设备是系统管理、I/O扩展、通信控制平面、工业、汽车和消费…...
【codequ】Java学习路线整理(韩顺平)
文章目录Java学习路线一、Java基础1.建立编程思想Java概述变量运算符控制结构数据、排序和查找面向对象编程(基础)面向对象编程(中级)项目&学以致用2.提升编程能力3.分析需求,代码实现能力Java8新特性二、Java高级…...
服务器容器配置日志(Linux+x86_64+Ubuntu18.04+CUDA11.0+python3.7)
一、创建并进入容器 (平台使用教学详细,这部分略写) 登上服务器后,打开终端输入如下进入自己建的容器 ssh -p XXXXX root10.XXX.XXX.XXX //按自己的宿主机端口写二、安装Conda(miniconda3) (…...
2023年美赛赛题思路分析
2023年的赛题A-F题的整体难度不算太难,难度在于数据的收集上。整体难度上来看,难度上F题难度最小,建议直接上手。本次先给大家分享一些数据网站,在对各题做简单的思路分析。1、美国国家海洋和大气管理局Homepage | National Ocean…...
[C++]服务器与客户端建立连接与检测断开的demo
该程序在IP127.0.0.1以及端口5000环境下测试 有一段时间没有在Windows下用C进行网络编程了,这段日子都在做QT的网络编程和OpenCV的图像识别。 今天重新写个Windows下C的,基于TCP的双端连接建立与断开检测的demo,巩固下自己Windows下的网络编程…...
包教包会vue3+ts状态管理工具pinia
一、Pinia介绍 定义:pinia是和vuex一样的状态管理工具 语法:和 Vue3 一样,它实现状态管理有两种语法:选项式API 和 组合式API 支持:vue2、typeScript、devtools 二、使用步骤 1.安装 pnpm add pinia yarn add pin…...
Generated columns cannot be used in COPY
错误如下DBD::Pg::db do failed: ERROR: column "transtype" is a generated columnsec., avg: 2520 recs/sec), REPORTSINTERMEDIATETABLE in progress.DETAIL: Generated columns cannot be used in COPY. at /usr/local/share/perl5/Ora2Pg.pm line 15125.FATAL: …...
Amazon S3简介
前言: 这段时间来到了某大数据平台,做平台技术底座封装和一些架构等等,有结构化数据也有非结构数据,涉及到很多技术,自己也私下花时间去研究了很多,有很多纯技术类的还是需要梳理并记录,巩固以及…...
MySQL索引类型——有五种
文章目录前言一、MySQL中的索引类型有以下几种1.1 普通索引1.1.1 直接创建索引1.1.2 修改结构的方式添加索引1.1.3 创建表的时候同时创建索引1.1.4 删除索引1.2 唯一索引1.2.1 创建唯一索引1.2.2 修改表结构1.2.3 创建表的时候直接指定1.3 主键索引1.4 组合索引1.5 全文索引1.5…...
CloudCompare 二次开发(5)——非插件中的PCL环境配置(均匀采样为例)
目录 一、概述二、CMakeLists.txt三、源码编译四、代码示例五、结果展示一、概述 在进行CloudCompare二次开发的时候,可以直接在CloudCompare的核心功能中添加自己的算法,比插件式的算法集成要方便得多。因此,这里主要记录CloudCompare非插件式二次开发配置PCL,并给出具体开…...
停车辅助系统的技术和变化
各种各样的停车辅助系统已经存在了很长时间,但用户经常在不知道什么技术以及它是如何工作的情况下使用它们。 今天我们依次来谈谈停车辅助系统是什么,怎么发展以及如何应用的。 1.手信号 您可能会想,“为什么手信号是停车辅助系统&#x…...
扬帆优配|日均客运量恢复,民航业加速复苏,外资买入2股超亿元
春运民航客运量康复至疫情前七成。 2月16日,民航局举行2月例行新闻发布会。会上介绍,自1月7日至2月15日,春运40天,民航运送旅客5523万人次,日均客运量138万人次,同比去年春运添加39%,康复至2019…...
【PyTorch】教程:torch.nn.ModuleDict
Containers-ModuleList CLASS torch.nn.ModuleDict(modulesNone) 将所有的子模块放到一个字典中。 ModuleDict 可以像常规 Python 字典一样进行索引,但它包含的模块已正确注册,所有 Module 方法都可以看到。 ModuleDict 是一个有序字典。 Parameters …...
Git、小乌龟、Gitee的概述与安装应用超详细(组长与组员多人开发版本)
目录 一、概述 1.什么是Git? 2.Git历史来源 3.Git的优点? 4.什么是版本控制? 5.版本控制工具种类? 6.Git工作机制 7.Git、小乌龟、Gitee、凭据管理器的简单介绍 二、Git下载安装 下载Git 安装Git 安装完成后查看版本 三、下载小…...
【java 高并发编程之JUC】高阶JUC特性总结
1 线程中断机制 1.1 什么是中断? 首先 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。所以,Thread.stop, Thread.suspend, Thread.resume 都已经被废弃了。 其次 在Java中没有办法立即停止一条线程,然…...
行业分析| 智能无人自助设备
智能无人自助设备运用二维码技术、音视频通信技术和AI智能技术等相结合,提供了无人超市、自动售货机、智能快递柜等。当下很多商业地区或社区,都放置了智能无人自助设备,不仅可以为商家节省时间和精力、提升运营环境,也可以为众多…...
使用契约测试得不偿失?试试契约先行开发
契约维护的难题 如今微服务凭借其灵活、易开发、易扩展等优势深入人心,不同服务之间的集成和交互日渐繁多且复杂。这些服务之间交互的方式是多样的,常见的有 HTTP 请求和消息队列。在它们交互的过程中,会有服务的版本演进,交互信…...
函数编程之Function
文章目录前言一、Function是什么?二、Function 怎么用?1.简单使用2.真正的强大之处总结前言 在java8之后,我已经习惯了开始用stream()方式编程,但是对于新引入的其他功能,还是不清楚,今天经历了一个编程问题后,让我对于Function() 这个函数有了新的认知; 一、Func…...
Vue 双向绑定原理
Vue2 双向绑定原理 mvvm 双向绑定,采用数据劫持结合发布者-订阅者模式的方式,通过 Object.defineProperty() 来 劫持各个属性的 setter、getter,在数据变动时发布消息给订阅者,触发相应的监听回调。 几个要点: 1&#…...
【数据治理-03】无规矩不成方圆,聊聊如何建立数据标准
无规矩,不成方圆!数据标准(Data Standards)是保障数据的内外部使用和交换的一致性和准确性的规范性约束,作为数据治理的基石,是绕不开的一项工作,如此重要的活如何干,咱们一起聊聊。…...
dos常用命令
DOS(磁盘操作系统)命令,是DOS操作系统的命令,是一种面向磁盘的操作命令,主要包括目录操作类命令、磁盘操作类命令、文件操作类命令和其它命令。 使用技巧 DOS命令不区分大小写,比如C盘的Program Files&…...
解决原生template标签在Vue中失效的问题
文章目录前言一、事件未绑定的原因二、如何处理原生template标签总结前言 需要原生Javascript three.js的数据标注平台加入Vue框架. 本来挺顺利的, 我直接在mounted周期做了初始化, 然后剩下的操作还是交给JavaScript文件执行, 最后发现里面有很明显的事件触发问题. 一、事件…...
节能降耗方案-医院能源管理系统平台的研究与应用分析
摘要:综合性医院作为大型公共机构,能耗高的问题日益突出,构建能耗监控平台对医院能耗量化管理以及效果评估已经成为迫切需要。建立智能能耗监控平台,对采集的能耗数据进行分析,实现对医院能耗平台监控,为医…...
Redis学习【7】之发布_订阅命令和事务
文章目录一 发布/订阅命令1.1 消息系统1.2 subscribe1.3 psubscribe1.4 publish1.5 unsubscribe1.6 punsubscribe1.7 pubsub1.7.1 pubsub channels1.7.2 pubsub numsub1.7.3 pubsub numpat二 Redis 事务2.1 Redis 事务特性Redis 事务实现2.1.1 三个命令2.1.2 基本使用2.2. Redi…...
MySQL8.0 optimizer_switch变化
Optimizer_switch变量是支持对优化器行为的控制。是一组值标志,每个标志都有一个on或off的值,以指示是否启用或禁用相应的行为。 MySQL8.0里除了熟悉的hash join重大变化之外,其他方面也有优化。 mysql> SHOW VARIABLES LIKE OPTIMIZER_…...
政府制作网站收费/八百客crm系统登录入口
往期热门文章:1、牛客网:为什么不能将实数作为 HashMap 的 key? 2、RedisJson发布官方性能报告,性能碾压ES和Mongo 3、分布式数据一致性思考-B端系统一致性 4、Java字符串拼接的五种方法,哪种性能最好? 5、…...
景安网络网站建设/bing搜索 国内版
IT在数据化转型旗帜下的一个重大转换就是将大型的、整体的应用架构分拆成为细小独立的,功能级的微服务架构。这些微服务软件包运行在容器内,同时封装了服务的所有代码和依赖关系,可以独立运行,并轻易地在服务器环境之间迁移。也是…...
wordpress文章自动tag/sem投放是什么意思
Android接入WebView(一)——基本用法 Android接入WebView(二)——与JavaScript交互 Android接入WebView(三)——浏览器书签与历史记录与二维码分享 Android接入WebView(四)——浏…...
南昌行业网站建设/网站推广有哪些方式
一、什么是HQL(NHibernate Query Language)查询语言 定义:NHibernate查询语言(HQL,NHibernate Query Language)是NHibernate特有的基于面向对象的SQL查询语言,它具有继承、多态和关联等特性。 它如何运行:HQL查询的是通过…...
婺源网站建设/百度经验怎么赚钱
soft 温柔的,和蔼的,宽厚的,温和的 英语释义:not forceful, loud, or easily noticed soft形容人的时候,多指性情温和的、宽厚的、心肠软的、婉转的; soft形容物的时候,可指事物的表面的柔软…...
店铺运营/seo软件代理
使用Codec Engine开发DaVinci系统,最令人头痛的莫过于调试。由于evm6446开发过程分成DSP端和GPP端,因此我们无法使用IDE下的调试工具对程序进行跟踪调试。为此,TI在Codec Engine中提供了一套名为Generic Trace Support 的模块,专门…...