2017.11.4 JavaWeb-----基于JavaBean+JSP求任意两数代数和(改进的在JSP页面中无JSP脚本代码的)+网页计数器JavaBean的设计与使用
修改后的JSP中不含有JSP脚本代码这使得JSP程序的清晰性、简单
1.设计JavaBean 的Add.java 类
package beans;
public class Add {
private int shuju1;
private int shuju2;
private int sum;
public Add(){}
public int getshuju1(){return shuju1;}
public int getShuju1() {
return shuju1;
}
public void setShuju1(int shuju1) {
this.shuju1 = shuju1;
}
public int getShuju2() {
return shuju2;
}
public void setShuju2(int shuju2) {
this.shuju2 = shuju2;
}
public int getSum(){return shuju1+shuju2;}
public void setSum(int sum){this.sum=sum;}
}
2.用户输入界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>提交任意两个整数的页面</title>
</head>
<body>
<h3>按下列格式要求,输入两个整数:</h3><br>
<form action="show.jsp" method="post"></form>
加数:<input name="shuju1"><br><br>
被加数:<input name="shuju2"><br><br>
<input type="submit" value="提交">
</body>
</html>
3.显示正确的结果界面:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>利用JavaBean+JSP求两数和</title>
<body>
<jsp:useBean id="c" class="beans.Add" scope="request"/>
<jsp:setProperty name="c" property="*"/> /为c对象的属性赋值
<p>调用jsp:property 做标签显示结果值:<br/>
<jsp:getProperty name="c" property="shuju1"/>+ <jsp:getProperty name="c" property="shuju2"/>
=<jsp:setProperty name="c" property="sum"/><br>
</p>
</body>
</html>
例题:设计一个JavaBean记载网页的访问量,在动态页面访问该JavaBean,实现网页计数。假如要统计两个网页的总共访问量.
1.//编写JavaBean类,计数器 Counter.java
package beans;
public class Counter {
private int count;
public Counter()
{
count=0;
}
public int getCount()
{
count++;
return count;
}
public void setCount(int count)
{
this.count = count;
}
}
2.//第一个页面 counter1.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>网页访问数量</title>
</head>
<body>
<jsp:useBean id="counter" class="beans.Counter" scope="application"/>
这次访问的是第一个页面:counter1.jsp!<br/>
两页面共被访问次数:
<jsp:getProperty name="counter" property="count"/>
</body>
</html>
3.//第二个页面 counter2.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>网页访问数量</title>
</head>
<body>
<jsp:useBean id="counter" class="beans.Counter" scope="application"/>
这次访问的是第2个页面!<br>
两页面共被访问次数:
<jsp:getProperty name="counter" property="count"/>
</body>
</html>