深入学习 checkplan 类业务逻辑
- 从请求中获取参数
在 checkplan 类(通常是一个 Servlet)中,我们可以使用 HttpServletRequest 对象来获取客户端请求中携带的参数。HttpServletRequest 提供了多个方法来获取参数,最常用的是 getParameter 方法。
以下是一个示例代码片段,展示如何从请求中获取名为 planId 的参数
`import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/checkplan")
public class checkplan extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取名为 planId 的参数
String planId = request.getParameter("planId");
if (planId != null && !planId.isEmpty()) {
// 处理 planId 参数
} else {
// 参数为空的处理逻辑
}
}
}2. 调用 Dao 类中的方法进行数据库操作 在 checkplan 类中,为了进行数据库操作,我们需要创建 Dao 类的实例,并调用其相应的方法。假设我们有一个 PlanDao 类,其中包含根据 planId 查询计划信息的方法。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/checkplan")
public class checkplan extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String planId = request.getParameter("planId");
if (planId != null && !planId.isEmpty()) {
// 创建 Dao 类实例
PlanDao planDao = new PlanDao();
// 调用 Dao 类的方法进行数据库查询
Plan plan = planDao.getPlanById(Integer.parseInt(planId));
if (plan != null) {
// 处理查询到的计划信息
} else {
// 未查询到计划信息的处理逻辑
}
}
}
}3. 将数据传递给 JSP 页面 为了将从数据库中查询到的数据传递给 JSP 页面,我们可以使用 HttpServletRequest 对象的 setAttribute 方法。在 JSP 页面中,可以使用 EL 表达式或 JSP 脚本获取这些属性。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/checkplan")
public class checkplan extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String planId = request.getParameter("planId");
if (planId != null && !planId.isEmpty()) {
PlanDao planDao = new PlanDao();
Plan plan = planDao.getPlanById(Integer.parseInt(planId));
if (plan != null) {
// 将查询到的计划信息存储到 request 中
request.setAttribute("plan", plan);
// 转发到 JSP 页面
request.getRequestDispatcher("/planDetails.jsp").forward(request, response);
}
}
}
}在 planDetails.jsp 页面中,可以使用以下方式获取 plan 对象:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
计划详情
计划名称: ${plan.planName}
计划描述: ${plan.planDescription}
`