我正在使用一个春季启动项目,我试图在控制器中创建一个具有动态参数数量的路由。路由是这样的:
@RequestMapping(value = "/addItem", method = RequestMethod.POST)
public String addItem(ModelMap model, @RequestParam Map<String,String> allRequestParams) {
String stringId = allRequestParams.get("id");
System.out.println(stringId);
long id = Long.valueOf(stringId);
System.out.println(id);
...
}
我需要将id参数转换为Long
,我已经尝试使用Long.valueOf(stringId)
和Long.parseLong(stringId)
这样做,但是当我使用参数id
作为1调用路由时,我得到此错误:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NumberFormatException: For input string: "1
"] with root cause
java.lang.NumberFormatException: For input string: "1
我像这样从表单中调用路由:
<form method="POST" action="addItem">
<div class="form-group">
<table id="details" class="table table-responsive">
<tr id="type">
<th class="text-left select-title">Type* :</th>
<td>
<select name="id" id="input" class="form-control form-control-sm inv-select" required>
<option value="" disabled selected>Selected...</option>
<%@ include file = "common/dropdown.jsp" %>
</select>
</td>
</tr>
<tr id="component1">
<th class="text-left select-title">Type of Component * :</th>
<td>
<select id="select" name="component1" class="form-control form-control-sm inv-select" required>
<option value="" disabled selected>Selected...</option>
<%@ include file = "common/dropdown.jsp" %>
</select>
</td>
<th class="text-left quant-title">Quantity * :</th>
<td class="quantity-field">
<input name="quantity1" type="number" step="any" placeholder="Quantity" class="quantity-input" required>
</td>
</tr>
<tr class="table-row">
<td>
<button onclick="addComponent()" id="add-component" class="btn btn-md btn-outline-success"> + Add Component</button><br>
</td>
<td>
<button onclick="removeComponent()" id="rem-component" class="btn btn-md btn-outline-danger"> - Remove Component</button><br>
</td>
</tr>
<tr>
<th>
<input type="submit" name="submit" id="submit">
</th>
</tr>
</table>
</div>
</form>
控制器路由中的print语句用于调试,并且只打印第一个print语句。我怎样才能正确地将字符串转换为长?
您说字符串是"1rn"
。
但是,Long.valueOf()
只适用于仅由数字组成的字符串。
trim()
:
Long.valueOf(stringId.trim());
我建议你使用Long#parseLong
代替Long#valueOf
,因为它返回long
而不是Long
。这样就摆脱了无用的对象创建。
@RequestMapping(value = "/addItem", method = RequestMethod.POST)
public String addItem(ModelMap model, @RequestParam Map<String,String> allRequestParams) {
String stringId = allRequestParams.get("id");
System.out.println(stringId);
long id = Long.parseLong(stringId.trim());
System.out.println(id);
...
}