通过表单向servlet提交数据不成功。
在givenumber.jsp页面中输入一个正实数,求其平方根。
但是输入正实数后,点提交时。得不出结果。
givenumber.jsp的代码如下:
<%@page contentType="text/html;charset=GB2312"%>
<Html>
<form action="/servlet/Sqrt" method="get">
<input type="text" name="number"/>
<input type="Submit" name="提交"/>
</form>
</Html>
Servlet的代码如下:
public class Sqrt extends HttpServlet{
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/html;charset=GB2312");
out.println("<html><body>");
String number = req.getParameter("number");
double n=0;
try{
n=Double.parseDouble("number");
out.print("<BR>"+Math.sqrt(n));
}catch (NumberFormatException e) {
}
out.println("</body></html>");
}
}
web.xml的代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>pingfang</servlet-name>
<servlet-class>com.wzh.servlet.Sqrt</servlet-class>
</servlet>
<mapping-servlet>
<servlet-name>pingfang</servlet-name>
<url-pattern>/servlet/Sqrt</url-pattern>
</mapping-servlet>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
[解决办法]
1 把这句 <form action="/servlet/Sqrt" method="get"> 改成:
<form action="servlet/Sqrt" method="get"> //去掉前面的斜杠.
2 把这句 n=Double.parseDouble("number"); 该成:
n=Double.parseDouble(number);
试试.