我的第一個JSP程式 eclipse
阿新 • • 發佈:2019-02-07
首先新建一個動態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。