用MVC模式实现三角形面积

软件:myeclipse8.5

项目名称:MVC

 

Sample8_1.jsp是输入三解形三条边的界面:

showResult.jsp是输入面积的界面:

程序如下:

Sample8_1.jsp

<%@ page contentType="text/html;charset=GB2312" %>

<HTML><BODY ><FONT size=2>
<FORM action="HandleArea" Method="post">
<P>输入三角形的边A:<Input type=text name="a">
<P>输入三角形的边B:<Input type=text name="b">
<P>输入三角形的边C:<Input type=text name="c">
<Input type=submit value="提交">

</FONT></BODY></HTML>

 

showResult.jsp

<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="mybean.Area" %>
<jsp:useBean id="data" type="mybean.Area" scope="request"/>
<HTML><BODY>
<jsp:getProperty name="data" property="mess"/>:
<jsp:getProperty name="data" property="area"/>
</BODY></HTML>

 

Area.java

package mybean;
public class Area{
double a,b,c,area;
String mess;
public void setMess(String mess){
this.mess=mess;
}
public String getMess(){
return mess;
}
public void setA(double a){
this.a=a;
}
public void setB(double b){
this.b=b;
}
public void setC(double c){
this.c=c;
}
public void setArea(double s){
area=s;
}
public double getArea(){
return area;
}
}

 

HandleArea.java

package myservlet;
import mybean.Area;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HandleArea extends HttpServlet{

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
Area dataBean=new Area(); //创建Javabean对象
request.setAttribute("data",dataBean);//将dataBean存储到request对象中
try{ double a=Double.parseDouble(request.getParameter("a"));
double b=Double.parseDouble(request.getParameter("b"));
double c=Double.parseDouble(request.getParameter("c"));
dataBean.setA(a); //将数据存储在dataBean中
dataBean.setB(b);
dataBean.setC(c);
double s=-1;
double p=(a+b+c)/2.0;
if(a+b>c&&a+c>b&&b+c>a)
s=Math.sqrt(p*(p-a)*(p-b)*(p-c));
dataBean.setArea(s); //将数据存储在dataBean中
dataBean.setMess("三角形面积");
}
catch(Exception e){
dataBean.setArea(-1);
dataBean.setMess(""+e);
}
RequestDispatcher dispatcher=request.getRequestDispatcher("showResult.jsp");
//请求showResult.jsp显示dataBean中的数据:
dispatcher.forward(request,response);
}
}

posted @ 2023-05-18 11:17  bobo哥  阅读(240)  评论(0编辑  收藏  举报