1. 該實例主要告訴我們怎麼樣在JSP代碼中調用JavaBean構件
2. 使用JavaBean的優點是簡化了JSP代碼,界面代碼和邏輯代碼互相分離,便於程序員查看和調試
3. 該實例需要五個文件:login.jsp、test.jsp、userbean.class
4. 首先看一下login.jsp
<html>
<center>
<form method=post action="http://127.0.0.1:8000/test.jsp">
username<input type="text" name="username"><p>
password<input type="password" name="password"><p>
<input type="submit" value="注冊">
</form>
</center>
</html>
--------------------------------------------------------------------------------
5. test.jsp代碼如下:
<html>
<jsp:useBean id="hello" class="userbean" scope="session" />
<jsp:setProperty name="hello" property="*" />
your username is:<jsp:getProperty name="hello" property="username"/><p>
your password is:<jsp:getProperty name="hello" property="password"/><p>
<%
out.println(hello.insert());
%>
</html>
--------------------------------------------------------------------------------
6. JavaBean構件userbean.java代碼如下:
import java.sql.*;
public class userbean
{
private String username;
private String password;
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
public String insert()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection dbcon = DriverManager.getConnection("jdbc:odbc:test","sa","");
PreparedStatement stat = dbcon.prepareStatement("insert login values(?,?)");
stat.setString(1,username);
stat.setString(2,password);
stat.executeUpdate();
return "success";
}
catch(Exception e)
{
System.out.println(e);
return e.toString();
}
}
}
--------------------------------------------------------------------------------
7. 配置方法如下:
login,test放在j2ee的public_html中,userbean.class放在j2ee\lib\classes中