JSP入门教程(2)第二课:用HTML表单 Request和Response对象在你制作的JSP原代码中起作用。到于request对象到底怎么用,我要在接下来详细的讲给你听。 如何创建表单 用HTML定义一些有代表性的表单做成一个JSP文件,然后用JSP标签在表单和服务器端对象(通常都用Bean)传递数据。一般情况下是这么干的: 1、 写JSP原文件,创建一些HTML的表单并命名。 2、 在Java文件里写Bean,定义属性,GET或者SET方法来配合已经被你指定好名字的表单。 3、 回到JSP原文件中,增加<jsp:useBean>标签来创建一个或者调用一个现成的Bean。 4、 增加<jsp:setProperty>标签设置HTML表单中需要SET方法的Bean的属性。 5、 增加<jsp:getProperty>标签设置HTML表单中需要GET方法的Bean的属性。 6、 如果需要处理更多的用户数据,用request对象。 说了半天你可能看不懂,其实看一个例子你就懂了。 先看一个简单的hello的例子吧: 这段程序其实还是计算机程序里那个最经典的“hello,world”的程序,只不过呢,我使他挠了一点弯儿,使他看起来比较智能和复杂。首先你输入你的名字,然后Duke跟你说:“hello!” 看看代码吧: dukebanner.html <table border="0" width="400" cellspacing="0" cellpadding="0"> <tr> <td height="150" width="150"> </td> <td width="250"> </td> </tr> <tr> <td width="150"> </td> <td align="right" width="250"> <img src="duke.waving.gif"> </td> </tr></table><br> 主JSP文件:hellouser.jsp <%@ page import="hello.NameHandler" %> <jsp:useBean id="mybean" scope="page" class="hello.NameHandler" /> <jsp:setProperty name="mybean" property="*" /> <html> <head><title>Hello, User</title></head> <body bgcolor="#ffffff" background="background.gif"> <%@ include file="dukebanner.html" %> <table border="0" width="700"> <tr><td width="150"> </td> <td width="550"> <h1>My name is Duke. What's yours?</h1></td></tr> <tr><td width="150" </td><td width="550"> <form method="get"> <input type="text" name="username" size="25"> <br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </td></tr> </form> </table> <% If ( request.getParameter("username") != null ) { %> <% @ include file="response.jsp" %> <% } %> </body></html> 回应文件:response.jsp <table border="0" width="700"> <tr> <td width="150"> </td> <td width="550"> <h1>Hello, <jsp:getProperty name="mybean" property="username" />! </h1> </td> </tr> </table> 处理数据的Bean:(namehandler.java) package hello; public class NameHandler { private String username; public NameHandler() { username = null; } public void setUsername( String name ) { username = name; } public String getUsername() { return username; } } 建立HTML表单 一个HTML的窗分为三个部分:<form>标签,输入方法,提交按钮发数据到服务器。一般的HTML页面里,是这么写的<form method=get action=someurl>,在其他的页面里的action属性可能是其他特殊的CGI程序或者其他能处理数据的程序,那么在JSP里边是怎么用的呢,呵,如果你想把数据发到Bean里的话那么你可以省略action里边的东里了,直接写<jsp:useBean>标签或者其他特定的JSP文件了。接下来的那些表单和普通的HTML差不多了,<input>的方法,然后加一个提交按钮,可能还有一个Reset按钮,对了,别忘了,还得给每一个input表单加一个名字。 上一篇:JSP在Windows 2000下的安装 下一篇:JSP的安装、启动及简单示例 更多相关文章
|
推荐文章
精彩文章
|