首先新建一个动态web项目,New->others->web->Dynamic Web Project,然后在WebContent中新建一个index.jsp。
代码如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" import = "java.util.*" import = "java.lang.Integer.*"
pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
int first = 0;
int second = 0;
if(request.getParameter("first")!=null)//这里应该先对参数进行判断,否则报错
{
first = Integer.parseInt(request.getParameter("first"));
second = Integer.parseInt(request.getParameter("second"));
}
int sum = first + second;
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>my first test</title>
<script type ="text/javascript">
function check()
{
if(this.document.forms[0].first.value.length == 0)
alert("please input the first integer");
else this.document.forms[0].submit();
}
</script>
</head>
<body>
<center>Now time is: <%=new java.util.Date()%></center>
<font size="2">
<jsp:include flush="true" page="footer.jsp"></jsp:include><br>
<form action ="index.jsp" method="post">
please input the first:<input type = "text" name="first"/><br>
please input the second:<input type = "text" name="second"/><br>
the sum: <%=sum %><br><!-- 注意这里的%和=是不能分开的撒 -->
<input type = "button" value="sum" onclick = "check()"/><br>
</form>
</font>
</body>
</html>
注意两个注释的地方,一个是用java处理request参数的时候,应该首先判断request得到的参数,否则会报错(不知道为什么会报错额?),第二个地方是在求和的地方,<%= sum%>中%和=要连在一起,否则编译不通过。
整个程序有三部分内容
1.居中显示时间
2.用include动作标签嵌入footer.jsp,这个footer里面简单来说就是<%out.print("this is including")%>;
3.是在界面中有两个输入框,分别输入加数被加数,然后点击sum求和。求和时调用check()方法对输入参数进行判断,通过后sumit到action=index.jsp进行求和处理,处理结束后返回sum。