我在JSP中有以下表单
<form method="POST" action="${pageContext.request.contextPath}/">
<div class="form-group col-md-3 col-md-offset-1">
<input type="number" name="minPrice" id="minPrice" title="Minimum Price" class="form-control"
placeholder="Minimum Price"/>
</div>
<div class="form-group col-md-3">
<input type="number" name="maxPrice" id="maxPrice" title="Maximum Price" class="form-control"
placeholder="Maximum Price"/>
</div>
<div class="form-group col-md-3">
<input type="text" name="company" id="company" title="Company" class="form-control"
placeholder="Company"/>
</div>
<button type="submit" class="btn btn-danger">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</form>
还有我的servlet中的doPost()
方法:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Float minPrice , maxPrice;
try {
minPrice = Float.parseFloat(request.getParameter("minPrice"));
}
catch (Exception ex) {
minPrice = null;
}
try {
maxPrice = Float.parseFloat(request.getParameter("maxPrice"));
}
catch (Exception ex) {
maxPrice = null;
}
String company;
try {
company = request.getParameter(request.getParameter("company"));
}
catch (Exception ex) {
company = null;
}
System.out.println(minPrice + " " + maxPrice + " " + company);
Connection conn = MyUtils.getStoredConnection(request);
String errorString = null;
List<Car> list = null;
try {
list = DBUtils.getCars(conn);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
if (minPrice != null && maxPrice != null) {
if (maxPrice < minPrice) {
errorString = "";
}
}
if (list != null) {
System.out.println(list.size());
Iterator<Car> iter = list.iterator();
while (iter.hasNext()) {
Car car = iter.next();
if (minPrice != null) {
//System.out.println("Min is not null");
if (car.getCostPerDay() < minPrice) {
iter.remove();
continue;
}
}
if (maxPrice != null) {
//System.out.println("Max is not null");
if (car.getCostPerDay() > maxPrice) {
iter.remove();
}
}
if (company != null) {
if (!car.getCompany().equalsIgnoreCase(company))
iter.remove();
}
}
System.out.println(list.size());
}
request.setAttribute("errorString", errorString);
request.setAttribute("productList", list);
RequestDispatcher dispatcher = request.getServletContext()
.getRequestDispatcher("/WEB-INF/views/carListView.jsp");
dispatcher.forward(request, response);
}
当我输入minPrice或maxPrice或两者都输入时,可以看到输出,如System.out.println()消息中所示,如下所示:
当maxPrice为10000时:
null 10000.0 null
当minPrice为4000时:
4000.0 null null
当公司是Maruti Suzuki时:
null null null
我已经在FORM中设置了公司的名称属性,以便可以通过Servlet对其进行访问,就像我对minPrice和maxPrice所做的一样,仍然无法在Servlet中获取其值。我不知道我要去哪里错了
答案 0 :(得分:2)
为什么要像在getParameter
中的getParameter
一样
request.getParameter(request.getParameter("company"));
更改为
company = request.getParameter("company");
也我建议您不要只是吞下例外情况