java代码是写在servlet里吗
时间: 2024-03-14 14:45:46 浏览: 18
是的,通常情况下,Java代码是写在Servlet中的。Servlet是Java Web开发中常用的一个技术,它可以接收HTTP请求并生成HTTP响应,用于处理Web应用程序中的动态内容。在Servlet中,可以编写Java代码来获取数据库中的数据,并将数据传递给JSP页面,以便在前端页面中显示。
以下是一个简单的示例代码,假设Servlet的名称为CommentServlet:
```
public class CommentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取评论表中的数据
List<Comment> commentList = getCommentList();
//将List对象传递给JSP页面
request.setAttribute("commentList", commentList);
//转发到JSP页面
RequestDispatcher dispatcher = request.getRequestDispatcher("/comment.jsp");
dispatcher.forward(request, response);
}
//获取评论表中的数据
public List<Comment> getCommentList() {
List<Comment> commentList = new ArrayList<Comment>();
try {
//连接数据库
Connection conn = DBUtil.getConnection();
String sql = "select * from comment";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
//遍历结果集,将数据存储到List对象中
while (rs.next()) {
Comment comment = new Comment();
comment.setId(rs.getInt("id"));
comment.setUsername(rs.getString("username"));
comment.setContent(rs.getString("content"));
comment.setTime(rs.getTimestamp("time"));
commentList.add(comment);
}
//关闭连接
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return commentList;
}
}
```
在上述代码中,doGet()方法处理HTTP GET请求,并获取评论表中的数据,然后将数据存储到一个List对象中,并通过request.setAttribute()方法传递给名为comment.jsp的JSP页面。最后,使用RequestDispatcher.forward()方法将请求转发到JSP页面,以便在前端页面中显示评论内容。