Java 输入文本验证错误-JSP
我有一个输入文本,比如说它是用来输入价格的。 在用户单击Java 输入文本验证错误-JSP,java,jsp,validation,Java,Jsp,Validation,我有一个输入文本,比如说它是用来输入价格的。 在用户单击insertproducts.jsp上的提交按钮后,doinsertproducts.jsp上有验证代码 输入价格的验证为: 必须填写输入文本 输入文本必须是数字 价格必须大于零 这是第一个代码: if(price.equals("")||price==null){ response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=P
insertproducts.jsp上的提交按钮后,doinsertproducts.jsp
上有验证代码
输入价格的验证为:
必须填写输入文本
输入文本必须是数字
价格必须大于零
这是第一个代码:
if(price.equals("")||price==null){
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be filled.");
return;
}
else{
try{
intprice=Integer.parseInt(price);
}
catch (Exception e) {
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be numeric.");
}
}
我不知道我必须把第二个代码放在哪里来检查输入是否小于1:
if(intprice<1){
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be greater than 0 (zero).");
}
看起来代码没有处理该错误。
是否有任何解决方案可以让代码检测到用户的3个错误?尝试以下方法:
String price = request.getParameter("price").toString();
String errorMessage = "";
if(price != null && price != ""){
try{
intPrice = Integer.parseInt(price);
if(intPrice > 0){
System.out.println("Price " + intPrice + " is greater to 0.");
}else{
System.out.println("Price " + intPrice + " is less then or equal to 0.");
}
}catch(Exception ex){
ex.getMessage();
errorMessage = "Price is not a Number.";
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage);
}
}else{
errorMessage = "Price was not given.";
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage);
}
旁注:if(price.equals(“”| | price==null)
-price==null
无法访问。由于price==null
您将获得NPE。Do如果(“.equals(price))
@MarounMaroun仍然出现错误,问题似乎是代码无法处理文本框中的字符输入。您必须在insertproducts.jsp上通过javascript/jquery处理验证,然后在doinsertproducts.jsp上检查null并获取参数。@ParkashKumar这是我的作业。不允许使用JS/jqueryOk,所以您的意思是只在服务器端处理验证?@noobprogrammer请尝试上面的代码,如果您发现任何困难,请询问我。
String price = request.getParameter("price").toString();
String errorMessage = "";
if(price != null && price != ""){
try{
intPrice = Integer.parseInt(price);
if(intPrice > 0){
System.out.println("Price " + intPrice + " is greater to 0.");
}else{
System.out.println("Price " + intPrice + " is less then or equal to 0.");
}
}catch(Exception ex){
ex.getMessage();
errorMessage = "Price is not a Number.";
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage);
}
}else{
errorMessage = "Price was not given.";
response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage);
}