分析】该案例使用JSP、Servlet、JavaBean三种技术集成,实现系统的设计,JSP主要完成信息的提交和显示;Servlet主要完成对请求数据的获取与处理;JavaBean主要用于业务处理并实现数据的存储。
【设计】该程序需要设计:
(1)输入表单页面input.jsp:将该页面的请求参数信息,传给Servlet。
(2)接收运算请求的Servlet,CaculateServlet.java:该Servlet接受input.jsp的请求信息,并创建JavaBean对象实例,然后调用JavaBean的业务处理方法,完成业务处理,形成新的结果,并将结果在request范围内实现属性数据共享,然后转向输出信息页面output.jsp。
(3)封装复数运算的JavaBean,Complex.java:该JavaBean有2个属性,并有完成加运算的方法。
(4)显示结果的页面output.jsp:接受Servlet传递的共享数据,并显示。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="caculateServlet" method="post">
请输入第一个复数的实部:<input type="text" name="r1"><br>
请输入第一个复数的虚部:<input type="text" name="i1"><br>
请输入第二个复数的实部:<input type="text" name="r2"><br>
请输入第二个复数的虚部:<input type="text" name="i2"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Complex;
/**
* Servlet implementation class CaculateServlet
*/
@WebServlet("/caculateServlet")
public class CaculateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double r1=Double.parseDouble(request.getParameter("r1"));
double i1=Double.parseDouble(request.getParameter("i1"));
double r2=Double.parseDouble(request.getParameter("r2"));
double i2=Double.parseDouble(request.getParameter("i2"));
Complex c1=new Complex(r1,i1);
Complex c2=new Complex(r2,i2);
String result=c1.add(c2).toString();
request.setAttribute("outputMessage", result);
request.getRequestDispatcher("output.jsp").forward(request, response);;
}
}
package beans;
public class Complex {
private double real;
private double ima;
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getIma() {
return ima;
}
public void setIma(double ima) {
this.ima = ima;
}
public Complex(double real, double ima) {
this.real = real;
this.ima = ima;
}
public Complex() {}
public Complex add(Complex a) {
return new Complex(this.real+a.real,this.ima+a.ima);
}
public String toString() {
String r=null;
if(ima<0) {
r=""+real+ima+"i";
}else {
r=real+"+"+ima+"i";
}
return r;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=request.getAttribute("outputMessage") %>
</body>
</html>