request.getParameter is null



我需要获取request.getParameter("action"),它是我在JSP页面中使用的,以便定义应该执行的命令(<input type="hidden" name="action" value="open_list"/>(。结果是null。问题出在哪里?或者我如何用另一种方式传递命令?

CommandFactory.java

public class CommandFactory {
public Command defineCommand(HttpServletRequest request) {
Command current = new ErrorCommand();
String action = request.getParameter("action");
if (action == null || action.isEmpty()) {
return current;
}
try {
CommandEnum currentEnum = CommandEnum.valueOf(action.toUpperCase());
current = currentEnum.getCommand();
} catch (IllegalArgumentException e){
request.setAttribute("wrongAction", action);
}
return current;
}
}

MainServlet.java

public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MainServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CommandFactory client = new CommandFactory();
Command command = client.defineCommand(request);
String page = command.execute(request, response);
if (page != null) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
dispatcher.forward(request, response);
}else {
response.sendRedirect(PageURL.ERROR_PAGE);
}
}
}

JSP页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form name="hotelList" method="GET" action="/MainServlet">
<input type="hidden" name="action" value="open_list"/>
<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>ADDRESS</th>
<th>RATING</th>
<th>OWNERNAME</th>
</tr>
<c:forEach items="${list}" var="hotel">
<tr>
<td>${hotel.id}</td>
<td>${hotel.name}</td>
<td>${hotel.address}</td>
<td>${hotel.rating}</td>
<td>${hotel.ownerName}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>

我试图重现您的问题,您无法控制页面上的type="submit"

当您单击提交按钮时,它将在servlet中更正您的request.getParameter("action")

<form name="hotelList" method="GET" action="MainServlet">
<input type="hidden" name="action" value="open_list"/>
<input type="submit" value="Send">
</form>

相关内容

最新更新