JSP(JavaServer Pages)是一种基于Java技术的服务器端编程技术,用于创建动态网页。下面是一个简单的JSP论坛代码示例,包括用户发帖和显示帖子的功能。
JSP允许在HTML页面中嵌入Java代码,通过服务器端的处理生成动态内容。它通常与Servlet一起使用,Servlet负责业务逻辑处理,而JSP负责显示。
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PostServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String content = request.getParameter("content");
String author = request.getParameter("author");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/forum", "username", "password");
PreparedStatement ps = conn.prepareStatement("INSERT INTO posts(title, content, author) VALUES (?, ?, ?)");
ps.setString(1, title);
ps.setString(2, content);
ps.setString(3, author);
ps.executeUpdate();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("viewPosts.jsp");
}
}
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Forum Posts</title>
</head>
<body>
<h1>Forum Posts</h1>
<a href="postForm.jsp">Add New Post</a>
<ul>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/forum", "username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM posts ORDER BY created_at DESC");
while (rs.next()) {
%>
<li>
<strong><%= rs.getString("title") %></strong> by <%= rs.getString("author") %> at <%= rs.getTimestamp("created_at") %><br>
<%= rs.getString("content") %>
</li>
<%
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</ul>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add New Post</title>
</head>
<body>
<h1>Add New Post</h1>
<form action="PostServlet" method="post">
Title: <input type="text" name="title"><br>
Content: <textarea name="content" rows="10" cols="50"></textarea><br>
Author: <input type="text" name="author"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
通过以上步骤,你可以创建一个简单的JSP论坛系统。如果有更多具体问题或需要进一步的帮助,请提供详细信息。
领取专属 10元无门槛券
手把手带您无忧上云