我正在学习 servlet,并尝试创建这个基本计算器。我试图将所有异常添加到字符串中,并将该字符串作为错误消息打印在网页上。我只包括代码的基本部分
public class Calculator extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String x = request.getParameter("x");
String y = request.getParameter("y");
DecimalFormat df = new DecimalFormat("#,###.##");
String errorMsg = "";
if (x != null && y == null) {
errorMsg = errorMsg.concat("Y cannot be blank\n");
}
else if (x == null && y != null) {
errorMsg = errorMsg.concat("X cannot be blank");
}
out.println("<!doctype html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Calculator</title>");
out.println("</head>");
out.println("<body>");
if (!errorMsg.equalsIgnoreCase("")) {
out.println("<h2>"+errorMsg+"</h2>");
}
out.println("<form>");
out.println("<table border='1' style='background-color:#999'>");
out.println("<tr><td>X </td> <td><input type='text' id='xValue' name='x' /></td></tr>");
out.println("<tr><td>Y </td> <td><input type='text' id='yValue' name='y' /></td></tr>");
out.println("<tr><td colspan='2'>");
out.println("<input type='submit' id='plusButton' value='+' name='add' />");
out.println("<input type='submit' id='minusButton' value='-' name='sub' />");
out.println("<input type='submit' id='mulButton' value='*' name='mul' />");
out.println("<input type='submit' id='divButton' value='/' name='div' />");
out.println("</table>");
out.println("</form></body></html>");
}
}
如果我在 X 和 Y 文本字段中输入字母,我应该会收到一条错误消息。更具体地说,我应该在两个单独的行上收到两个错误消息。但是我让他们都在同一条线上。在命令行上,我将它们放在不同的行上。我在这里做错了什么?