一、反射与动态代理
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;
}
@Override
public String toString() {
return "PersonRefection{" +
"name='" + name + '\'' +
", sex='" + Gender + '\'' +
", id='" + id + '\'' +
", tel='" + tel + '\'' +
'}';
}
@Override
public 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;
}
@Override
public 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;
}
@Override
public 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 {
@Override
public 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 {
@Override
public 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("'");
} else
sql.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();
}
}
//删除信息1
public 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.建立一个socket
DatagramSocket 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 {
//建立一个Socket
DatagramSocket 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=”” />;文章来源:https://www.toymoban.com/news/detail-436521.html
程序可以采用GUI,也可采用命令行的方式。文章来源地址https://www.toymoban.com/news/detail-436521.html
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;
}
@Override
public 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实验的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!