基于JSP与JavaBean的小型加法程序出现500错误求助
Let's walk through exactly what's causing that internal server error and fix your code step by step:
What's Triggering the 500 Error?
Null parameter parsing on initial load
When you first openMiniAdd.jsp, there are nonum1ornum2parameters in the request. Your code tries to callInteger.parseInt(null)(even in a try-catch) and uses<jsp:setProperty>to assign these null values to primitiveintfields in your bean. Since primitives can't holdnull, this throws an unhandled exception that crashes the page.Invalid sum parameter assignment
You're trying to set the bean'ssumproperty usingrequest.getParameter("sum"), but your form never sends asumparameter. Again, this tries to assignnullto anintfield, causing another exception.Encoding issues (minor but important)
UsingISO-8859-1charset can lead to weird encoding bugs if users input non-ASCII characters, so switching toUTF-8is a good practice.
Fixed Code Implementation
First, Update Your JavaBean (SumBean2.java)
Let's add a method to handle the sum calculation directly in the bean (keeps business logic clean and separated from the JSP):
package add; import java.io.Serializable; public class SumBean2 implements Serializable { private int num1; private int num2; private int sum; public SumBean2(){ } // Getters and setters public int getNum1() { return num1; } public void setNum1(int num1) { this.num1 = num1; } public int getNum2() { return num2; } public void setNum2(int num2) { this.num2 = num2; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } // Add this method to calculate sum internally public void calculateSum() { this.sum = this.num1 + this.num2; } }
Then, Fix the JSP (MiniAdd.jsp)
We'll add null safety checks, remove invalid property assignments, and improve user experience:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="add.SumBean2"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Sum Calculator</title> </head> <body> <form action="MiniAdd.jsp" method="get"> <label>Number 1</label><input type="text" name="num1" value="${SumNumber.num1}"><br> <label>Number 2</label><input type="text" name="num2" value="${SumNumber.num2}"><br> <input type="submit" value="Calculate Sum"/> <input type="reset" value="Reset"/> </form> <jsp:useBean id="SumNumber" class="add.SumBean2" scope="session"/> <% // Only process input if the form was submitted (parameters exist) String num1Str = request.getParameter("num1"); String num2Str = request.getParameter("num2"); if (num1Str != null && num2Str != null && !num1Str.isEmpty() && !num2Str.isEmpty()) { try { int num1 = Integer.parseInt(num1Str); int num2 = Integer.parseInt(num2Str); SumNumber.setNum1(num1); SumNumber.setNum2(num2); SumNumber.calculateSum(); // Use the bean's calculation method } catch (NumberFormatException e) { out.println("<p style='color:red;'>Oops! Please enter valid whole numbers only.</p>"); } } %> <%-- Show the result only after form submission --%> <% if (num1Str != null && num2Str != null && !num1Str.isEmpty() && !num2Str.isEmpty()) { %> <h3>Calculated Sum = <jsp:getProperty name="SumNumber" property="sum"/></h3> <% } %> </body> </html>
Key Improvements Made
- Null safety: We only parse parameters and update the bean if the form was actually submitted (no more null values being forced into primitive
intfields). - Cleaner logic: The sum calculation is now handled by the JavaBean, following best practices for separation of concerns.
- User feedback: Added an error message for invalid inputs (like letters instead of numbers).
- Retained input values: Used Expression Language (
${SumNumber.num1}) to keep the user's entered values in the form after submission. - UTF-8 encoding: Fixed potential character encoding issues.
内容的提问来源于stack exchange,提问作者ash2608

