【发布时间】:2017-10-06 00:35:27
【问题描述】:
在我的项目中,我有以下文件:
- pole.jsp 包含一个表单和一个提交
- results.jsp 我显示结果的地方(它只有一个标题)
- 我在pole.jsp 和results.jsp 中设置标题的PollServlet
这里是文件: poll.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Poll Page</title>
</head>
<body>
<form action="/poll?action=pole" method="POST">
<div>
<a><h2><% out.print(request.getAttribute("oldTitle").toString());%>
</h2></a><br>
</div>
<br><br>
<input type="submit" name = "submit"value="submit">
</form>
</body
results.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Results</title>
</head>
<body >
<form action="/poll?action=results" method="POST">
<a><% out.print(request.getAttribute("title"));%></a>
</form>
</body>
</html>
PollServlet.java
@WebServlet(name = "PollServlet", urlPatterns = {"/poll"})
public class PollServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("pole")) {
request.setAttribute("oldTitle","new tile for poll.jsp ");
getServletConfig().getServletContext().getRequestDispatcher(
"/poll.jsp").forward(request, response);
} else if (action.equals("results")) {
/* set the title for results.jsp */
request.setAttribute("title","title for results.jsp");
getServletConfig().getServletContext().getRequestDispatcher(
"/results.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,
}
问题似乎出现在 servlet 的 doGet() 方法中。我只能设置第一个项目(poll.jsp)标题的值,而不是第二个(results.jsp)我做错了什么,如何正确实现?谢谢!
【问题讨论】:
-
我在您的 doGet 方法中看不到任何条件。我认为的问题是您正在使用调度程序转发,因此我认为第二个属性正在设置。要验证这一点,您可以在第一个和第二个 setAttribute 方法之间尝试一个记录器。
-
我可以看看你更新的代码
-
在哪里初始化action的值,其次在else if where是条件。
-
就像你有action = PollServlet?action=results一样,你为什么不把pole.jsp中的action改成PollServlet?action=pole。我认为使用当前代码,您只会输入 else 块。如果请求来自 result.jsp
-
等一下,当您使用 http 发布方法时,您正在 doGet 中进行更改。你能把它改成GET并检查吗?另一个替代方法是更改 doPost 方法并使用 request.setAttribute("action",????);还记得删除 ?action=??
标签: java jsp spring-mvc servlets jakarta-ee