【问题标题】:request.getParameter("name") returns null in servletrequest.getParameter("name") 在 servlet 中返回 null
【发布时间】:2021-12-10 09:01:56
【问题描述】:

String selected = req.getParameter("name") 返回 null。我需要来自所选单选按钮的值。我应该如何得到它?谢谢!

这是 HTML 文件中的格式:

<form th:method="POST" th:action="@{/select}">
  <ul th:each="o: ${orders}" style="list-style-type: none">
      <input th:text="${o.getDescription()}" th:value="${o.getName()}" type="radio" name="color"><br>
  </ul>
  <br/>
  <input value="Submit" type="submit">
</form>

这是我的 servlet:

@WebServlet(urlPatterns = "/select")
public class SelectServlet extends HttpServlet {

    private final SpringTemplateEngine springTemplateEngine;

    public SelectServlet(SpringTemplateEngine springTemplateEngine) {
        this.springTemplateEngine = springTemplateEngine;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WebContext context = new WebContext(req, resp, getServletContext());
        String selected = req.getParameter("color");
        context.setVariable("selectedOption", selected);
        this.springTemplateEngine.process("selectSize.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/select");
    }
}

我已经阅读了很多其他类似问题的答案,但没有一个能解决我的问题。

【问题讨论】:

  • 你没有参数name,你有参数color
  • 对不起,问题中的错字,仍然不起作用。
  • 发帖时,您是否选择了任何单选按钮?
  • 是的,我选择了一个按钮。
  • 请求参数在一个请求期间有效。我假设您希望他们能够跨越您在doPost 中所做的重定向。那是行不通的。使用会话属性或以它们将持续存在的方式将它们存储在其他地方。目前尚不清楚您为什么要重定向。

标签: java spring spring-boot servlets


【解决方案1】:

您正在从表单 (method=POST) 发送一个 post 请求,但是在 servlet 中您已经在 doGet() 中编写了代码,因此您的代码不会被 servlet 执行,因为 servlet 将执行 @987654323 @ 方法,所以你应该在doPost() 中编写代码。我希望这能解决您的问题。

【讨论】:

  • 我在 doPost() 方法中重定向请求。
猜你喜欢
  • 2021-01-27
  • 2014-09-21
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多