JSP学习笔记(五)-----JSP中使用JavaBean

类别:Java 点击:0 评论:0 推荐:

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>

<br><br>

password<input type=password name=password>

<br><br>

<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"/>

<br><br>

your password is:<jsp:getProperty name="hello" property="password"/>

<br><br>

<%

       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 void setPassword(String password)

       {

              this.password=password;

       }

       public String getUsername()

       {

              return username;

       }

       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中

 

 

本文地址:http://com.8s8s.com/it/it15871.htm