0

我收到错误“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>
4

2 回答 2

1

All code you write into your JSP will be compiled into the _jspService method. As you can see below, the signature has void return type.

public void _jspService(HttpServletRequest request, 
   HttpServletResponse  response) 
     throws IOException, ServletException {

}

You should remove the return statement at the below line:

} catch (NumberFormatException nfe) {return "";} 

Since you're dealing with web pages, instead of returning a value, you should show the user an appropriate message. In your case, it will be an error message.

} catch (NumberFormatException nfe) {
    out.println("Error!");
}

Most Importantly

You should not use scriptlets in any JSP code you write in 2012. Learn about more advanced techniques such as JSTL and do consider using Servlets too.

于 2012-04-22T20:09:35.697 回答
0

You're misunderstanding a basic programming concept: a void method can't return any value. Check this line:

catch (NumberFormatException nfe) {
    return "";
}

There's your error. A JSP can't return a value. Instead, you should do something with the exception like post it in your log. for now, I'll just print it in the console:

catch (NumberFormatException nfe) {
    System.out.println("Error parsing the number: " + nfe.getMessage());
}
于 2012-04-22T20:09:28.907 回答