我在尝试运行代码时收到错误。 无法找到问题所在。 我可能会遗漏一些细节,如果你能纠正它会很棒。
CalculateServlet
import java.io.IOException;
import javax.servlet.*;
@WebServlet(name="CalculateServlet", urlPatterns={"/CalculateServlet"})
public class CalculateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public CalculateServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//assuming request as the object of the HttpServletRequest Class.
//retrieving & storing the values from the textboxes into the String Variables.
String n1 = request.getParameter("fnum");
int num1 = Integer.parseInt(n1); //Converting String into Integer Variable
String n2 = request.getParameter("snum");
int num2 = Integer.parseInt(n2); int ans=0;
//performing calculation according to the selection made from the Radio Buttons named "calc".
if(request.getParameter("calc").equals("Add"))
ans = num1+num2;
if(request.getParameter("calc").equals("Sub"))
ans = num1-num2;
if(request.getParameter("calc").equals("Div"))
ans = num1/num2;
if(request.getParameter("calc").equals("Multi"))
ans = num1*num2;
//assuming response as the object of the HttpServletResponse Class.
//displaying output to the user
response.getWriter().println(ans);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
的index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<form action="CalculateServlet">
<input type="text" name="fnum"/>
<br/>
<input type="text" name="snum"/>
<br/>
Select Operation
<br/>
<input type="radio" name="calc" value="Add"/>Add
<input type="radio" name="calc" value="Sub"/>Subtract
<input type="radio" name="calc" value="Div"/>Divide
<input type="radio" name="calc" value="Multi"/>Multiply
<br/>
<input type="submit" value="Calculate" name="submit"/>
</form>
</body>
</html>
答案 0 :(得分:2)
web.xml
中的网址格式
<servlet-mapping>
<servlet-name>CalculateServlet</servlet-name>
<url-pattern>/CalculateServlet</url-pattern>
</servlet-mapping>
但是你的jsp将其提交给&#34;计算&#34;
<form action="calculate">
将其更改为,
<form action="CalculateServlet">
答案 1 :(得分:0)