So I am currently doing a crud in spring boot and I am stuck at this place where i want to treat null id as 0, I have tried below version and it returns
`java.lang.NumberFormatException: For input string: ""`
@ResponseBody
public String checkMobileEmail(HttpServletRequest req, Model model) {
String mobile = req.getParameter("mobile");
String email = req.getParameter("email");
Long id = Long.parseLong(req.getParameter("id"));
if (req.getParameter("id").equals("")) {
id = 0L;
}
System.err.println("id : " id " mobile : " mobile " email: " email);
return service.findByEmailAndMobile(email,mobile,id);
}
CodePudding user response:
You must avoid Long.parseLong(req.getParameter("id")); before the if condition as follows:
@ResponseBody
public String checkMobileEmail(HttpServletRequest req, Model model) {
String mobile = req.getParameter("mobile");
String email = req.getParameter("email");
String idParameter = req.getParameter("id");
Long id = 0L;
if (idParameter != null && !idParameter.equals("")) {
id = Long.parseLong(idParameter);
}
System.err.println("id : " id " mobile : " mobile " email: " email);
return service.findByEmailAndMobile(email,mobile,id);
}
CodePudding user response:
You need to check if id is empty or null before calling Long.parseLong or it throws an exception.
Long id;
if (StringUtils.hasText(req.getParameter("id")) {
Long.parseLong(req.getParameter("id"));
} else {
id = 0L;
}
You will still end up with an exception if the parameter is neither empty/null or a number. I would recommend to catch the exception and handle it appropriately.
try {
Long.parseLong(req.getParameter("id"))
} catch(NumberFormatException e) {
// log.warn(e)
return Collections.emptyList();
}
