java jsp异常错误
我得到一个错误“jsp文件中的17:/index.jsp Void方法无法返回值”我认为我的异常代码是错误的。当用户没有输入任何数字时,我不知道如何返回空字符串。有什么建议吗
<%@ page import="java.io.*"%><%@
page import="java.util.*"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<%
String sum = (String) session.getAttribute("sum");
sum = "5";
session.setAttribute("sum",sum);
int isum = Integer.parseInt(sum);
try {
isum=Integer.parseInt(request.getParameter("number"));
} catch (NumberFormatException nfe) {return "";}
if(request.getParameter("number")!=null && Integer.parseInt(request.getParameter("number"))==isum)
{
if(request.getParameter("submit") != null){
out.print("Hello");}
}
%>
<body>
<title>MAIN</title>
<form action="index.jsp" method="post">
Enter 5 = <input type="text" name="number">
<input type="submit" value="continue" name="submit">
</form>
</body>
</html>
# 1 楼答案
您写入JSP的所有代码都将编译到
_jspService
方法中。如下面所示,签名具有void
返回类型您应该删除下一行的
return
语句:因为您处理的是网页,所以应该向用户显示适当的消息,而不是
return
一个值。在您的情况下,这将是一条错误消息最重要的是
您不应该在2012年编写的任何JSP代码中使用Scriptlet。了解更先进的技术,如JSTL和DO也考虑使用servlet。
# 2 楼答案
您误解了一个基本的编程概念:void方法不能返回任何值。选中此行:
这是你的错误。JSP不能返回值。相反,您应该处理异常,比如在日志中发布它。现在,我将在控制台中打印它: