写出javaweb代码
时间: 2023-07-09 07:29:27 浏览: 108
以下是使用 Java Web 技术和 MySQL 数据库的示例代码,基于 Servlet 和 JSP:
1. 配置数据库连接
在 `WEB-INF` 目录下创建一个名为 `db.properties` 的文件,并添加以下内容:
```properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/your_database_name
jdbc.username=your_database_username
jdbc.password=your_database_password
```
将 `your_database_name`、`your_database_username` 和 `your_database_password` 替换为您的 MySQL 数据库名称、用户名和密码。
2. 创建 DAO 类
创建一个名为 `StudentDao` 的 Java 类,用于与数据库交互并处理学生信息。以下是该类的示例代码:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class StudentDao {
private Connection connection;
public StudentDao() {
try {
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
Class.forName(properties.getProperty("jdbc.driver"));
connection = DriverManager.getConnection(
properties.getProperty("jdbc.url"),
properties.getProperty("jdbc.username"),
properties.getProperty("jdbc.password")
);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM students");
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setEmail(resultSet.getString("email"));
student.setPhone(resultSet.getString("phone"));
students.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
public void addStudent(Student student) {
try {
PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO students (name, email, phone) VALUES (?, ?, ?)"
);
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, student.getEmail());
preparedStatement.setString(3, student.getPhone());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateStudent(Student student) {
try {
PreparedStatement preparedStatement = connection.prepareStatement(
"UPDATE students SET name=?, email=?, phone=? WHERE id=?"
);
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, student.getEmail());
preparedStatement.setString(3, student.getPhone());
preparedStatement.setInt(4, student.getId());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteStudent(int id) {
try {
PreparedStatement preparedStatement = connection.prepareStatement(
"DELETE FROM students WHERE id=?"
);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
该类使用 JDBC API 与 MySQL 数据库进行交互。其中 `getAllStudents()` 方法用于获取所有学生信息,`addStudent()` 方法用于添加新学生,`updateStudent()` 方法用于更新学生信息,`deleteStudent()` 方法用于删除学生信息。每个方法都使用预处理语句来执行 SQL 查询和修改。
3. 创建 Servlet 类
创建一个名为 `StudentServlet` 的 Java 类,用于处理学生信息请求。以下是该类的示例代码:
```java
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentServlet extends HttpServlet {
private StudentDao studentDao;
public void init() {
studentDao = new StudentDao();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
action = "list";
}
switch (action) {
case "list":
listStudents(request, response);
break;
case "add":
addStudent(request, response);
break;
case "edit":
editStudent(request, response);
break;
case "delete":
deleteStudent(request, response);
break;
default:
listStudents(request, response);
break;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
private void listStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Student> students = studentDao.getAllStudents();
request.setAttribute("students", students);
request.getRequestDispatcher("student-list.jsp").forward(request, response);
}
private void addStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Student student = new Student(name, email, phone);
studentDao.addStudent(student);
response.sendRedirect("student?action=list");
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Student student = new Student(id, name, email, phone);
studentDao.updateStudent(student);
response.sendRedirect("student?action=list");
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id);
response.sendRedirect("student?action=list");
}
}
```
该类继承了 `HttpServlet` 类,并覆盖了 `doGet` 和 `doPost` 方法。在 `doGet` 方法中,根据请求参数 `action` 的值调用相应的方法。例如,当 `action` 为 `list` 时,调用 `listStudents()` 方法来获取所有学生信息并将其显示在 JSP 页面上。当 `action` 为 `add` 时,调用 `addStudent()` 方法来添加新学生并重定向到学生列表页面。其他方法(`editStudent()` 和 `deleteStudent()`)类似。
4. 创建 JSP 页面
在 `WebContent` 目录下创建一个名为 `student-list.jsp` 的 JSP 文件,并添加以下内容:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生列表</title>
</head>
<body>
<h1>学生列表</h1>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>电话</th>
<th>操作</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>${student.phone}</td>
<td>
<a href="student?action=edit&id=${student.id}">编辑</a>
<a href="student?action=delete&id=${student.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<hr>
<h2>添加学生</h2>
<form method="post" action="student">
<input type="hidden" name="action" value="add">
<label>姓名:<input type="text" name="name"></label>
<label>邮箱:<input type="text" name="email"></label>
<label>电话:<input type="text" name="phone"></label>
<button type="submit">添加</button>
</form>
</body>
</html>
```
该 JSP 页面使用 JSTL 标签库来循环显示学生信息。在表格中,每个学生都有一个编辑和删除链接。在页面底部,有一个表单用于添加新学生。该表单将请求方法设置为 `post`,并将表单数据提交到 `StudentServlet`。
阅读全文