JSP(JavaServer Pages)是一种用于创建动态Web内容的技术。它允许开发者在HTML或XML文档中嵌入Java代码片段和表达式,从而实现动态内容的生成。JSP页面在服务器端被编译成Servlet,然后执行并生成HTML响应返回给客户端。
// LoginServlet.java
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 验证用户名和密码
if (UserService.validateUser(username, password)) {
request.getSession().setAttribute("user", username);
response.sendRedirect("dashboard.jsp");
} else {
request.setAttribute("error", "Invalid credentials");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
// QuestionServlet.java
@WebServlet("/questions")
public class QuestionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Question> questions = QuestionService.getAllQuestions();
request.setAttribute("questions", questions);
request.getRequestDispatcher("questions.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 处理添加、编辑或删除题目的逻辑
}
}
<!-- exam.jsp -->
<form action="submitExam" method="post">
<c:forEach items="${questions}" var="question">
<p>${question.text}</p>
<c:forEach items="${question.options}" var="option">
<input type="radio" name="answer_${question.id}" value="${option}">${option}<br>
</c:forEach>
</c:forEach>
<input type="submit" value="Submit">
</form>
通过以上设计和实现,可以构建一个功能完善、性能优良的JSP考试系统。
领取专属 10元无门槛券
手把手带您无忧上云