编写简单的servlet程序,通过index.jsp页面从文框框输入圆的半径,提交后由servlet中的circlearea.java处理求出圆面积,并转回index.jsp输出结果。
时间: 2023-04-24 14:05:35 浏览: 582
以下是一个简单的servlet程序,实现从index.jsp页面获取圆的半径,计算圆面积并返回结果:
1. 在Web应用程序的WebContent目录下创建一个名为index.jsp的文件,输入以下代码:
```
<html>
<head>
<title>计算圆面积</title>
</head>
<body>
<h1>计算圆面积</h1>
<form action="CircleAreaServlet" method="post">
请输入圆的半径:<input type="text" name="radius"><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
2. 创建一个名为CircleAreaServlet的servlet,实现计算圆面积的功能。在servlet中添加以下代码:
```
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CircleAreaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double radius = Double.parseDouble(request.getParameter("radius"));
double area = Math.PI * radius * radius;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>圆面积计算结果</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>圆面积计算结果</h1>");
out.println("<p>半径为 " + radius + " 的圆的面积为 " + area + "</p>");
out.println("</body>");
out.println("</html>");
}
}
```
3. 在web.xml文件中添加servlet和servlet-mapping元素,将CircleAreaServlet映射到/index.jsp页面的表单提交:
```
<servlet>
<servlet-name>CircleAreaServlet</servlet-name>
<servlet-class>CircleAreaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CircleAreaServlet</servlet-name>
<url-pattern>/CircleAreaServlet</url-pattern>
</servlet-mapping>
```
4. 启动Tomcat服务器,访问http://localhost:808/项目名/index.jsp,输入圆的半径并提交,即可看到计算结果。
阅读全文