LPB*_*LPB 2 html java jsp getparameter
我正在开始JSP.我有以下HTML表单.
<form method='POST' enctype='multipart/form-data'>
<input type="text" name="sittingPlaces">
<textarea name="invitees"></textarea>
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
以及以下java代码.
if (request != null && request.getContentType() != null) {
int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces"));
String invites = request.getParameter("invitees");
}
Run Code Online (Sandbox Code Playgroud)
我收到错误
int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces"));
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?谢谢负载.
request.getParameter("sittingPlaces")使用以下方法检查字符串是否为有效数字:
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false; // The string isn't a valid number
}
return true; // The string is a valid number
}
Run Code Online (Sandbox Code Playgroud)
或者您可以在代码中实现它:
if (request != null && request.getContentType() != null) {
String sittingPlacesStr = request.getParameter("sittingPlaces");
try {
int sittingPlaces = Integer.parseInt(sittingPlacesStr);
String invites = request.getParameter("invitees");
} catch (NumberFormatException | NullPointerException e) {
// handle the error here
}
}
Run Code Online (Sandbox Code Playgroud)
您遇到的问题NumberFormatException是抛出,因为Java无法转换为您String,Integer因为它不代表有效的Integer.您应该使用try-catch语句(就像上面的示例方法一样)来过滤该异常,因为您无法控制来自客户端的请求.
Additionaly:
您还应检查request.getParameter("sittingPlaces")表达式是否返回有效字符串,而不是null:String.Staces = request.getParameter("sittingPlaces");
if (sittingPlaces != null {
// Continue your code here
} else {
// The client request did not provide the parameter "sittingPlaces"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4610 次 |
| 最近记录: |