用Servlet写个例子,查询mysql数据后返回给前端页面
时间: 2024-03-10 10:49:17 浏览: 87
基于JDBC+MySQL+Servlet+JSP+Java实现简单校园论坛系统.zip
好的,下面是一个使用Servlet查询MySQL数据并返回给前端页面的例子:
1. 首先,需要在项目中导入MySQL驱动包,例如mysql-connector-java-8.0.25.jar。
2. 创建一个Servlet类,例如DataQueryServlet,重写doGet方法,代码如下:
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DataQueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 查询数据
String sql = "SELECT * FROM user";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
// 输出数据到前端页面
out.println("<html>");
out.println("<head><title>Data Query Result</title></head>");
out.println("<body>");
out.println("<table border='1'>");
out.println("<tr><th>User ID</th><th>User Name</th><th>User Age</th></tr>");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td></tr>");
}
out.println("</table>");
out.println("</body></html>");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接和资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
3. 在web.xml文件中配置Servlet,代码如下:
```xml
<web-app>
<servlet>
<servlet-name>dataQueryServlet</servlet-name>
<servlet-class>DataQueryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dataQueryServlet</servlet-name>
<url-pattern>/dataquery</url-pattern>
</servlet-mapping>
</web-app>
```
4. 在浏览器中访问http://localhost:8080/项目名/dataquery,即可看到查询结果。
需要注意的是,以上代码只是一个简单的例子,实际开发中还需要考虑安全性、异常处理、分页等问题。另外,为了使代码更易于维护和扩展,建议使用JDBC工具类和DAO模式等技术。
阅读全文