【原创】chatGPT是来帮助我们的,还是来取代我们的?

概述

chatGPT的火爆,一种消极论调随之蔓延,它将取代编程人员,
我不知道未来怎样,至少目前它是人类的助手,如我们的字典,如我们的书籍,如我们的谷歌、百度,如我们的开发工具。
可以辅助我们编程,提高我们的工作效率,避免我们去记忆一些死背硬记的代码,而辅助我们多些创意。

1、java代码

1.1、写个HelloWorld,让chatGPT找错误

private class Hello {
    public statit void main(String[] args) {
        system.out.println("Hello World.");
    }
}

1.2、以下是Java读写D盘txt文件的示例代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWriteExample {
    public static void main(String[] args) {
        String filename = "D:\\test.txt";
        
        // 写文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            writer.write("Hello, world!\n");
            writer.write("This is a test file for Java file I/O.\n");
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }
        
        // 读文件
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }
    }
}

注:需要注意文件路径的斜杠要用双反斜杠,即 D:\\test.txt

1.3、以下是Java获取图片信息的示例代码:

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageInfoExample {
    public static void main(String[] args) {
        File file = new File("image.jpg");
        try {
            // 读取图片文件
            BufferedImage image = ImageIO.read(file);
            // 获取图片宽度和高度
            int width = image.getWidth();
            int height = image.getHeight();
            // 获取图片类型
            int type = image.getType();
            // 获取图片文件大小
            long size = file.length();
            // 输出图片信息
            System.out.println("Width: " + width);
            System.out.println("Height: " + height);
            System.out.println("Type: " + type);
            System.out.println("Size: " + size + " bytes");
        } catch (IOException e) {
            System.err.println("Failed to read image file: " + file);
            e.printStackTrace();
        }
    }
}

注:需要注意 ImageIO.read 方法在读取图片文件时可能会抛出 IOException 异常。

1.4、java的jdbc代码

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 建立连接
            String url = "jdbc:mysql://localhost:3306/mydatabase";
            String user = "root";
            String password = "password";
            conn = DriverManager.getConnection(url, user, password);

            // 查询数据
            String sql = "SELECT * FROM mytable";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            // 处理结果集
            while (rs.next()) {
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println("Name: " + name + ", Age: " + age);
            }

            // 关闭连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}

1.5、优化下代码,能适应高并发

import java.sql.*;
import javax.sql.DataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class JdbcExample {
    private static DataSource ds;

    public static void main(String[] args) {
        initDataSource();
        Connection conn = null;
        try {
            // 获取连接
            conn = ds.getConnection();

            // 查询数据
            String sql = "SELECT * FROM mytable";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            // 处理结果集
            while (rs.next()) {
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.println("Name: " + name + ", Age: " + age);
            }

            // 关闭连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private static void initDataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("password");
        mysqlDataSource.setInitialPoolSize(5);
        mysqlDataSource.setMaxPoolSize(10);
        ds = mysqlDataSource;
    }
}

2、前端代码

2.1、写个登录页面

<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<style>
		body {
			background-color: #f2f2f2;
			font-family: Arial, Helvetica, sans-serif;
		}
		form {
			width: 350px;
			margin: 0 auto;
			padding-top: 80px;
			border: 1px solid #ccc;
			border-radius: 5px;
			box-shadow: 0px 2px 3px rgba(0,0,0,0.1);
			background-color: white;
		}
		form label {
			font-weight: bold;
			display: block;
			margin: 10px 0;
			text-align: center;
		}
		form input[type=text], form input[type=password] {
			width: 80%;
			padding: 10px;
			margin: 10px auto;
			display: block;
			font-size: 1em;
			border: 1px solid #ccc;
			border-radius: 3px;
		}
		form input[type=submit] {
			background-color: #4CAF50;
			color: white;
			padding: 10px 20px;
			margin: 10px auto;
			border: none;
			border-radius: 3px;
			cursor: pointer;
			display: block;
			font-size: 1em;
		}
	</style>
</head>
<body>
	<form>
		<label for="username">Username:</label>
		<input type="text" id="username" name="username" required>
		<label for="password">Password:</label>
		<input type="password" id="password" name="password" required>
		<input type="submit" value="Log in">
	</form>
</body>
</html>

2.2、优化下,加上js代码

<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<style>
		body {
			background-color: #f2f2f2;
			font-family: Arial, Helvetica, sans-serif;
		}
		form {
			width: 350px;
			margin: 0 auto;
			padding-top: 80px;
			border: 1px solid #ccc;
			border-radius: 5px;
			box-shadow: 0px 2px 3px rgba(0,0,0,0.1);
			background-color: white;
		}
		form label {
			font-weight: bold;
			display: block;
			margin: 10px 0;
			text-align: center;
		}
		form input[type=text], form input[type=password] {
			width: 80%;
			padding: 10px;
			margin: 10px auto;
			display: block;
			font-size: 1em;
			border: 1px solid #ccc;
			border-radius: 3px;
		}
		form input[type=submit] {
			background-color: #4CAF50;
			color: white;
			padding: 10px 20px;
			margin: 10px auto;
			border: none;
			border-radius: 3px;
			cursor: pointer;
			display: block;
			font-size: 1em;
		}
		.error-msg {
			color: #ff0000;
			text-align: center;
			margin: 10px;
			font-size: 0.8em;
			display: none;
		}
	</style>
</head>
<body>
	<form id="login-form" onsubmit="return submitForm()">
		<label for="username">Username:</label>
		<input type="text" id="username" name="username" required>
		<label for="password">Password:</label>
		<input type="password" id="password" name="password" required>
		<input type="submit" value="Log in">
		<div class="error-msg" id="error-msg"></div>
	</form>
	<script>
		function submitForm() {
		  // 获取表单数据
		  const username = document.getElementById("username").value;
		  const password = document.getElementById("password").value;
		  
          // 做表单验证
		  if (username === "") {
		    document.getElementById("error-msg").style.display = "block";
		    document.getElementById("error-msg").innerHTML = "Username cannot be empty";
		    return false;
		  }
		  if (password === "") {
		    document.getElementById("error-msg").style.display = "block";
		    document.getElementById("error-msg").innerHTML = "Password cannot be empty";
		    return false;
		  }

		  // 异步提交表单数据
		  const xhr = new XMLHttpRequest();
		  xhr.onreadystatechange = function() {
		    if (xhr.readyState === 4) {
		      if (xhr.status === 200) {
		        // 处理登录成功的情况
		        location.href = "/success";
		      } else {
		        // 处理登录失败的情况
		        document.getElementById("error-msg").style.display = "block";
		        document.getElementById("error-msg").innerHTML = xhr.responseText;
		      }
		    } 
		  };
		  xhr.open("POST", "/login", true);
		  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		  xhr.send("username=" + username + "&password=" + password);

		  return false;
		}
	</script>
</body>
</html>

2.3、再优化,使用vue框架

<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
	<div id="login-form" style="margin: 0 auto; padding-top: 80px; width: 360px;">
		<el-form ref="form" :model="form" size="medium" :rules="rules">
			<el-form-item label="Username" prop="username">
				<el-input v-model="form.username" placeholder="Please input username"></el-input>
			</el-form-item>
			<el-form-item label="Password" prop="password">
				<el-input type="password" v-model="form.password" placeholder="Please input password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm">Log in</el-button>
			</el-form-item>
			<el-form-item v-show="errorMsg" style="color: red">
				{{ errorMsg }}
			</el-form-item>
		</el-form>
	</div>
	<script src="https://unpkg.com/vue/dist/vue.js"></script>
	<script src="https://unpkg.com/element-ui/lib/index.js"></script>
	<script>
		new Vue({
			el: '#login-form',
			data() {
				return {
					form: {
						username: '',
						password: ''
					},
					rules: {
						username: [
							{ required: true, message: 'Please input username', trigger: 'blur' }
						],
						password: [
							{ required: true, message: 'Please input password', trigger: 'blur' }
						]
					},
					errorMsg: ''
				}
			},
			methods: {
				submitForm() {
					this.$refs.form.validate((valid) => {
						if (valid) {
							const username = this.form.username;
							const password = this.form.password;

							// 发送表单数据
							this.$http.post('/login', { username, password })
								.then(response => {
									// 登录成功,跳转到指定页面
									if (response.data.code === 0) {
										location.href = '/success';
									} else {
										this.errorMsg = response.data.msg;
									}
								}).catch(error => {
									console.log(error);
								});
						} else {
							return false;
						}
					});
				}
			},
		});
	</script>
</body>
</html>

3、三大框架代码

3.1、 MyBatis Mapper类代码

好的,这是一个简单的MyBatis mapper类的示例:

import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.example.demo.model.User;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users")
    List<User> findAll();
}

这个mapper类使用了@Mapper注解,表明这是一个MyBatis的Mapper类。它定义了一个方法findAll(),该方法将在数据库中查询所有用户记录。@Select注解指定了查询语句,它返回一个包含User对象的List。

在实际应用中,Mapper类通常被注入到Service类中使用。在这个例子中,如果需要查询用户记录,可以注入UserMapper并调用它的findAll()方法。MyBatis会将SQL查询转换为Java对象,并将结果映射到User类的实例中。

3.2、 Spring Service类代码

好的,这是一个简单的Spring Service类的示例:

import org.springframework.stereotype.Service;

@Service
public class ExampleService {
   
   public String getMessage() {
      return "Hello World!";
   }
}

这个Service类有一个@Service注解,它告诉Spring框架这是一个服务类。该类有一个方法getMessage(),它返回一个字符串"Hello World!"。

在实际应用中,服务类通常被创建为单例,可以在应用程序的整个生命周期中重用。在这个例子中,如果其他组件需要获取"Hello World!"消息,可以注入ExampleService并调用它的getMessage()方法。

3.3、 SpringMVC Controller 类代码

好的,这是一个简单的Spring MVC控制器类的示例:

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ExampleController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(ModelMap model) {
        model.addAttribute("message", "Hello World!");
        return "index";
    }
}

这个控制器类有一个@RequestMapping注解,它告诉Spring MVC当请求路径为"/“时应该调用home()方法。该方法在模型参数中添加一个键值为"message"的属性,并将其值设置为"Hello World!”。最后,该方法返回视图名称"index",在这种情况下,它指向一个视图文件index.jsp。当请求到达控制器时,Spring MVC将此模型属性传递给该视图文件,以便它在呈现HTML时使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值