JSP表单传递action参数至Servlet时获取为null的解决方法咨询
嘿,我之前也遇到过类似的问题,给你几个靠谱的解决方案,应该能搞定:
最稳妥的方式:用隐藏域传递action参数
当你用GET提交表单时,浏览器会把表单里的输入参数拼到action URL后面,但有时候原来URL里带的查询参数可能会被意外忽略或者解析出错。换成隐藏域的方式就稳多了,不管GET还是POST都能正常传递:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController"> <!-- 新增隐藏域传递action参数 --> <input type="hidden" name="action" value="listCurrency"> Currency code: <input type="text" name="currencyCode" id="currencyCode"> <br> <input type="submit" value="Search"> </form>
这样提交后,request.getParameter("action")肯定能拿到listCurrency,同时currencyCode的参数也会一起带过去。
检查你的action URL是否正确解析
可能是EL表达式${pageContext.request.contextPath}没渲染对,导致最终的URL里根本没带上?action=listCurrency。你可以右键查看页面的源代码,看看form的action属性最终变成了啥样——正常应该是/你的项目名/CurrencyController?action=listCurrency这种格式。
如果确实没渲染出后面的参数,你可以先临时写死项目名测试:
<form method="GET" action ="/YourProjectName/CurrencyController?action=listCurrency">
要是这样能拿到参数,那说明是EL表达式的配置有问题,比如web.xml的版本是不是没设置对(要支持EL的话,至少是Servlet 2.4及以上版本)。
确认Servlet的映射是否匹配
还要检查下你的Servlet配置,不管是web.xml里的<url-pattern>还是注解@WebServlet里的路径,都得和form里的action路径对应上。比如如果Servlet映射的是/CurrencyController/*,那你的action就得写成${pageContext.request.contextPath}/CurrencyController/xxx,不然Servlet都匹配不到,更别说拿参数了。
另外,你可以在Servlet的doGet方法里加两行日志,看看请求的完整URL和参数:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 打印完整请求信息,方便排查 System.out.println("请求URL:" + request.getRequestURL()); System.out.println("查询参数:" + request.getQueryString()); String action = request.getParameter("action"); System.out.println("拿到的action:" + action); // 你的业务逻辑... }
从日志里就能一眼看出参数有没有传过来,到底是URL的问题还是Servlet的问题。
内容的提问来源于stack exchange,提问作者farahm

