面向对象程序设计期末项目总结
开发前准备
- Mysql
- Navicat
- TomCat
- IDEA
一,配置项目环境
右键项目名,添加新模块
命名后右键新建的模块
选中Web模块
到此项目创建完毕,接下来是配置环境。
打开IDEA–>File找到Project Structure
添加所要用到的jar包
- mysql-connector-j-8.0.31
- servlet-api
二,编写服务端与客户端
要求:编写服务器端(端口为21000)与客户端,客户端发送4个整数给服务端,服务器端计算四个整数的平均值返回给客户端
右键src新建包名为exam
- 新建ExamServer类实现服务器端
public class ExamServer {
public static void main(String args[]) {
ServerSocket server = null;
ServerThread thread;
Socket you = null;
while (true) {
try {
server = new ServerSocket(21000);
} catch (IOException e1) {
System.out.println("正在监听"); //ServerSocket对象不能重复创建
}
try {
System.out.println(" 等待客户呼叫");
you = server.accept();
System.out.println("客户的地址:" + you.getInetAddress());
} catch (IOException e) {
System.out.println("正在等待客户");
}
if (you != null) {
new ServerThread(you).start(); //为每个客户启动一个专门的线程
}
}
}
}
class ServerThread extends Thread {
Socket socket;
DataOutputStream out = null;
DataInputStream in = null;
String s = null;
ServerThread(Socket t) {
socket = t;
try {
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
}
}
public void run() {
while (true) {
try {
double num[]=new double[4];
for (int i = 0; i < num.length; i++) {
double a = in.readDouble();//堵塞状态,除非读取到信息
System.out.println("接收到的数为:"+a);
num[i]=a;
}
double result = (num[0] + num[1] + num[2] + num[3])/4;
System.out.println("四个整数的平均数为:"+result);
out.writeDouble(result);
for (int i = 0; i < num.length; i++) {
out.writeDouble(num[i]);
}
} catch (IOException e) {
System.out.println("客户离开");
e.printStackTrace();
return;
}
}
}
}
- 新建ExamClient类实现客户端:
public class ExamClient {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Socket mysocket = null;
DataInputStream in = null;
DataOutputStream out = null;
Thread readData;
Read read = null;
try {
mysocket = new Socket();
read = new Read();
readData = new Thread(read);
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
System.out.print("输入端口号:");
int port = scanner.nextInt();
if (mysocket.isConnected()) {
} else {
InetAddress address = InetAddress.getByName(IP);
InetSocketAddress socketAddress = new InetSocketAddress(address, port);
mysocket.connect(socketAddress);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
read.setDataInputStream(in);
readData.start();
}
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
System.out.print("输入四个整数(放弃请输入N):");
while (scanner.hasNext()) {
double a = 0;
try {
a = scanner.nextDouble();
} catch (InputMismatchException exp) {
System.exit(0);
}
try {
out.writeDouble(a);
} catch (Exception e) {
}
}
}
}
class Read implements Runnable {
DataInputStream in;
public void setDataInputStream(DataInputStream in) {
this.in = in;
}
public void run() {
double result = 0;
while(true) {
try{ result = in.readDouble();
double arr[] = new double[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.readDouble();
}
StringJoiner sj = new StringJoiner(",");
for (int i = 0; i < arr.length; i++) {
sj.add(arr[i] + "");
}
String descp = sj.toString();
System.out.println("计算四个整数的平均数为:"+result);
System.out.print("输入四个整数(放弃请输入N):");
}
catch(IOException e) {
System.out.println("与服务器已断开"+e);
break;
}
}
}
}
三,实现连接数据库
要求:
我们需要在本地创建名为studentdb的数据库
这里用的是Navicat
注意要给id选上自动递增。
在src下新建包名sdstudentapp.dal
- 新建DBUtil类
编写JDBC连接数据库。
public class DBUtil {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/studentdb?characterEncoding=gbk";
private static Connection con = null;
private static Statement smt = null;
private static ResultSet rs = null;
private static Connection createConnection() {
try {
Class.forName(driver);
return DriverManager.getConnection(URL, "root", "123456");
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (java.lang.ClassNotFoundException e) {
System.out.println("Can't load Driver");
}
return null;
}
public static int runUpdate(String sql) throws SQLException {
int count = 0;
if (con == null) {
con = createConnection();
}
if (smt == null) {
smt = con.createStatement();
}
count = smt.executeUpdate(sql);
if (smt != null) {
smt.close();
smt = null;
}
if (con != null) {
con.close();
con = null;
}
return count;
}
public static ResultSet runQuery(String sql) throws SQLException {
if (con == null) {
con = createConnection();
}
if (smt == null) {
smt = con.createStatement();
}
return smt.executeQuery(sql);
}
public static void realeaseAll() {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (smt != null) {
try {
smt.close();
smt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
con = null;
} catch (SQLException ex) {
Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void closeConnection(Connection conn) {
System.out.println("...");
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
注:在mysql-connector-java 5
以后的版本中(不包括5) 使用的都是com.mysql.cj.jdbc.Driver
在sdstudentapp.dal下新建包名Entity
新建Record类实现
public class Record {
int id;
double result;
String operNum;
String operName;
String descp;
public Record() {
}
public Record(int id, double result, String operNum, String operName, String descp) {
this.id = id;
this.result = result;
this.operNum = operNum;
this.operName = operName;
this.descp = descp;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
public String getOperNum() {
return operNum;
}
public void setOperNum(String operNum) {
this.operNum = operNum;
}
public String getOperName() {
return operName;
}
public void setOperName(String operName) {
this.operName = operName;
}
public String getDescp() {
return descp;
}
public void setDescp(String descp) {
this.descp = descp;
}
@Override
public String toString() {
return "Record{" + "id=" + id + ", result=" + result + ", operNum=" + operNum + ", operName=" + operName + ",descp=" + descp +'}';
}
}
在sdstudent.dal下创建dao层,可以对Record类进行管理,例如添加,查询等操作
新建RecordDao接口
import java.util.List;
import sdstudentapp.dal.Entity.Record;
public interface RecordDao {
public boolean addRecord(Record record);
public List<Record> getAllRecord();
}
创建接口实现类
在sdstudent.dal下创建daoimpl层
新建RecordDaoImpl类主要用来实现RecordDao接口中提供的方法
public class RecordDaoImpl implements RecordDao {
@Override
public boolean addRecord(Record record) {
String insert = "insert into exam(result,operNum,operName,descp) "
+"values('"+record.getResult()+"','"+record.getOperNum()+"','"+record.getOperName()+"','"+record.getDescp()+"')";
//insert into exam(resule,operNum,operName) values (2,'222',zzz)
try {
DBUtil.runUpdate(insert);
return true;
} catch (SQLException ex) {
Logger.getLogger(UserDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
@Override
public List<Record> getAllRecord() {
String select="select * from exam order by id desc";
try {
List<Record> records = new ArrayList<Record>();
ResultSet rs=DBUtil.runQuery(select);
while(rs.next())
{
Record record = new Record();
record.setId(rs.getInt("id"));
record.setResult(rs.getDouble("result"));
record.setOperNum(rs.getString("operNum"));
record.setOperName(rs.getString("operName"));
record.setDescp(rs.getString("descp"));
records.add(record);
}
DBUtil.realeaseAll();
return records;
} catch (SQLException ex) {
Logger.getLogger(UserDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return null; //To change body of generated methods, choose Tools | Templates.
}
}
完善ExamClient类,将数据添加到数据库中。
通过调用Record中的set,get方法创建Record类,再创建RecordDao来实现对数据库添加的操作。
class Read implements Runnable {
DataInputStream in;
public void setDataInputStream(DataInputStream in) {
this.in = in;
}
public void run() {
double result = 0;
while(true) {
try{ result = in.readDouble();
double arr[] = new double[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.readDouble();
}
StringJoiner sj = new StringJoiner(",");
for (int i = 0; i < arr.length; i++) {
sj.add(arr[i] + "");
}
String descp = sj.toString();
System.out.println("计算四个整数的平均数为:"+result);
System.out.print("输入四个整数(放弃请输入N):");
Record record = new Record();
record.setId(1);
record.setResult(result);
record.setOperNum("学号");
record.setOperName("姓名");
record.setDescp(descp);
RecordDao recordDao = new RecordDaoImpl();
boolean flag = recordDao.addRecord(record);
if(flag == true){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
}
catch(IOException e) {
System.out.println("与服务器已断开"+e);
break;
}
}
}
}
四,编写Servlet
要求:
在src下创建包名为webapp
新建showResultServlet类
public class showResultServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet showResultServlet</title>");
out.println("</head>");
out.println("<body>");
RecordDao recordDao=new RecordDaoImpl();
List<Record> records=recordDao.getAllRecord();
Record record=records.get(0);
out.println("<h2>"+record.toString()+"</h2>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
之后要对Servlet进行配置
进入web–>WEB-INF中打开web.xml
配置Servlet和Servlet-mapping
<servlet>
<servlet-name>showResultServlet</servlet-name>
<servlet-class>webapp.showResultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showResultServlet</servlet-name>
<url-pattern>/showResultServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
配置好之后需要对TomCat进行配置:
完成上面这几步之后就可以运行服务器端和用户端以及小猫咪了