(1)ch07_8_Add2:
package ch07_8;
public class ch07_8_Add2{
private int a;
private int b;
public ch07_8_Add2(int d1,int d2){
this.a=d1;
this.b=d2;
}
public int getA(){return a;}
public void setA(int a){this.a=a;}
public int getB(){return b;}
public void setB(int b){this.b=b;}
public int sum(){
int c,s=0;
if(a>b){c=a;a=b;b=c;}
int x=a;
while(x<=b){
s+=x;
++x;
}
return s;
}
}
(2)ch07_8_tijiao:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>提交任意2个整数给Servlet的页面</title>
</head>
<body>
<h3>按下列格式要求,输入两个整数数据:</h3><br>
<form action="ch07_8_servlet_yunsuan" method="post">
数据1:<input name="shuju1"><br><br>
数据2:<input name="shuju2"><br><br>
<input type=submit value="提交">
</form>
</body>
</html>
(3)cho7_8_servlet_yunsuan:
package ch07_8;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ch07_8_servlet_yunsuan extends HttpServlet {
public ch07_8_servlet_yunsuan() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GB2312");
String s1=request.getParameter("shuju1");
String s2=request.getParameter("shuju2");
int d1=Integer.parseInt(s1);
int d2=Integer.parseInt(s2);
ch07_8_Add2 two=new ch07_8_Add2(d1,d2);
int sum=two.sum();
request.setAttribute("d1", d1);
request.setAttribute("d2", d2);
request.setAttribute("sum", sum);
request.getRequestDispatcher("ch07_8_show.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
// Put your code here
}
}
(4)ch07_8_show:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>只显示两数之间累加值的页面</title>
</head>
<body>
<%String s1=request.getParameter("shuju1");
String s2=request.getParameter("shuju2");
Integer d1=(Integer)request.getAttribute("d1");
Integer d2=(Integer)request.getAttribute("d2");
Integer sum=(Integer)request.getAttribute("sum");
%>
<p><%=d1 %>加到<%=d2 %>的和值是:<%=sum %></p>
<p>现在的时间是:<%=new Date() %></p>
</body>
</html>