servlets - 检查 request.getParameter 是否包含字符串值或整数
问题描述
我正在尝试使用两个不同的值进行搜索,整数(sin)和姓氏(字符串)我已经能够保存两者,但是如何检查它是否是字符串这是我的代码:
if (request.getParameter("search") != null) {
String search = request.getParameter("search");
int searchSin = Integer.getInteger(request.getParameter("search"));
//If it is a string
request.setAttribute("employees", employeeService.getEmployeesLastName(search));
//else if it is an integer
request.setAttribute("employees", employeeService.getEmployeesSIN(search));
}
解决方案
试试下面的代码
if (request.getParameter("search") != null) {
String search = request.getParameter("search");
//it is an integer
if(isInteger(search)){
int searchSin = Integer.getInteger(search);
request.setAttribute("employees", employeeService.getEmployeesSIN(searchSin));
}
//else if it is a string
else{
request.setAttribute("employees", employeeService.getEmployeesLastName(search));
}
}
// check if one string is a integer
private boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}