Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 270|回复: 0

[jsf学习]学习笔记:使用JSF构建数据库驱动的应用程序

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-10 02:53:39 | 显示全部楼层 |阅读模式
    看了《 使用JSF 构建数据库驱动的应用程序》 一文后,动手做了练习。这是一个 订阅时事通讯的示例 Web 应用程序。订户通过提供他们的电子邮件地址、姓名和首选项进行注册。他们还必须选择一个口令, 以便以后可以更改他们的配置文件。 收获不少。
    1、<!-- index.jsp -->  <jsp:forward page="login.faces"/>
    这个没有什么可说的。

    2、 <!-- login.jsp -->登录页面

      
      
       
       
       

       
      
         <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/HTML" %> <c:remove var="subscriber" scope="session"/> <f:view> <f:loadBundle var="labels" basename="jsfdb.view.res.Labels"/>
    <c:set var="stylesheet"  value="/cwbwebhome/stylesheet.css"/> <html>
    <head>
       <title><h:outputText value="#{labels.login}"/></title>
       <link rel="stylesheet" type="text/css"  href="<c:out value=""/>">
    </head>
    <body>  <h1><h:outputText value="#{labels.login}"/></h1>  <h:outputLink value="subscribe.faces">
         <h:outputText value="#{labels.subscribe}"/>
    </h:outputLink>  <h:form id="login">  <h:messages globalOnly="true" styleClass="message"/>  <p><h:outputLabel for="email"  value="#{labels.email}"/>
    <h:message for="email" styleClass="message"/><br>
    <h:inputText id="email" required="true"  value="#{loginInfo.email}"  size="40" maxlength="80">
        <f:validateLength minimum="1" maximum="80"/>
    </h:inputText>  <p><h:outputLabel for="password"  value="#{labels.password}"/>
    <h:message for="password" styleClass="message"/><br>
    <h:inputSecret id="password" required="true"  value="#{loginInfo.password}"  size="10" maxlength="20">
         <f:validateLength minimum="6" maximum="20"/>
    </h:inputSecret>  <p><h:commandButton id="command"  value="#{labels.login}"  action="#{loginInfo.loginAction}"/>  </h:form> </body>
    </html> </f:view>
          典型的jstl加jsf,看来要好好学习jsp2.0了,赶上不形势啊!
         点击链接 Subscribe可进入subscribe.jsp(如图一),填订单页面。
         命令按钮的"action"绑定到了视图loginInfo Bean的loginAction()方法, loginAction() 方法会根据登录用户的角色(订户或管理员)返回 profile 或 list(导航法则在faces-config.xml文件中定义) , 请求转向订户修改配置文件页面 profile.jsp(图二) 或订户列表页面 list.jsp(图三)。先看看LoginInfoBean.java源码:
    1. package jsfdb.view;
    2. import jsfdb.model.LoginInfo;
    3. import jsfdb.model.Subscriber;
    4. import jsfdb.model.ModelUtils;
    5. import jsfdb.model.err.LoginException;
    6. import jsfdb.model.err.IncorrectPasswordException;
    7. import jsfdb.model.err.UnknownSubscriberException;
    8. public class LoginInfoBean extends LoginInfo {
    9.     public String loginAction() {
    10.          //初始化一个SubscriberBean对象
    11.         SubscriberBean subscriber= (SubscriberBean) ViewUtils.eval("#{subscriber}");
    12.         //获取管理员的邮件地址,管理员的邮件在web.xml文件中配置
    13.         String adminEmail= (String) ViewUtils.eval("#{initParam.adminEmail}");
    14.         try {
    15.             Subscriber selectedSubscriber
    16.                 = ModelUtils.getSubscriberDAO().select(this);//通过数据库验证口令与email
    17.             ModelUtils.copy(selectedSubscriber, subscriber);//订户数据复制进视图bean
    18.             subscriber.setLoggedIn(true);//登录标志设为true
    19.             if (subscriber.getEmail().equals(adminEmail))
    20.                 return "list";//如果是超级管理员,转向list.jsp
    21.             else
    22.                 return "profile";//如果是订户,转向profile.jsp
    23.         } catch (LoginException x) {
    24.             ViewUtils.addExceptionMessage(x);
    25.             return null;
    26.         } catch (UnknownSubscriberException x) {
    27.             ViewUtils.addExceptionMessage(x);
    28.             return null;
    29.         } catch (IncorrectPasswordException x) {
    30.             ViewUtils.addExceptionMessage(x);
    31.             return null;
    32.         }
    33.     }
    34. }
    复制代码



    图一(填订单)
      
      
    <!-- subscribe.jsp -->  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %> <f:view> <f:loadBundle var="labels" basename="jsfdb.view.res.Labels"/>
    <c:set var="stylesheet" value="/cwbwebhome/stylesheet.css"/> <html>
    <head>
    <title><h:outputText value="#{labels.subscribe}"/></title>
        <link rel="stylesheet" type="text/css"  href="<c:out value=""/>">
    </head>
    <body>  <h1><h:outputText value="#{labels.subscribe}"/></h1>  <h:form id="subscribe">  <h:messages globalOnly="true" styleClass="message"/>  <p><h:outputLabel for="email"  value="#{labels.email}"/>
    <h:message for="email" styleClass="message"/><br>
    <h:inputText id="email" required="true"  validator="#{subscriber.emailValidator}"  value="#{subscriber.email}"
    size="40" maxlength="80">
        <f:validateLength minimum="1" maximum="80"/>
    </h:inputText>  <p><h:outputLabel for="password"  value="#{labels.password}"/>
    <h:message for="password" styleClass="message"/><br>
    <h:inputSecret id="password" required="true"  value="#{subscriber.password}"  size="10" maxlength="20" redisplay="true">
        <f:validateLength minimum="6" maximum="20"/>
    </h:inputSecret>
    <h:outputText value="#{labels.passwordDetail}"/>  <p><h:outputLabel for="name" value="#{labels.name}"/>
    <h:message for="name" styleClass="message"/><br>
    <h:inputText id="name" required="true"  value="#{subscriber.name}"  size="40" maxlength="80">
        <f:validateLength minimum="1" maximum="80"/>
    </h:inputText>  <p><h:outputText value="#{labels.newsletters}"/>
    <h:message for="newsletters" styleClass="message"/><br>
    <h:panelGrid id="newsletters"  columns="3" border="0" cellspacing="5">
       <h:panelGroup>
        <h:selectBooleanCheckbox id="manager"  value="#{subscriber.manager}"/>
        <h:outputLabel for="manager"  value="#{labels.manager}"/>
       </h:panelGroup>

       <h:panelGroup>
        <h:selectBooleanCheckbox id="developer" value="#{subscriber.developer}"/>
        <h:outputLabel for="developer" value="#{labels.developer}"/>
       </h:panelGroup>

       <h:panelGroup>
        <h:selectBooleanCheckbox id="administrator" value="#{subscriber.administrator}"/>
        <h:outputLabel for="administrator" value="#{labels.administrator}"/>
       </h:panelGroup>
    </h:panelGrid>  <p><h:outputLabel for="subscriptionType" value="#{labels.subscriptionType}"/>
    <h:message for="subscriptionType" styleClass="message"/><br>
    <h:selectOneMenu id="subscriptionType" value="#{subscriber.subscriptionType}" required="true">
       <f:validateLongRange minimum="1" maximum="3"/>
       <f:selectItem itemLabel="#{labels.daily}" itemValue="#{subscriber.dailyConst}"/>
       <f:selectItem itemLabel="#{labels.weekly}" itemValue="#{subscriber.weeklyConst}"/>
       <f:selectItem itemLabel="#{labels.monthly}" itemValue="#{subscriber.monthlyConst}"/>
    </h:selectOneMenu>  <p><h:commandButton id="command" value="#{labels.subscribe}" action="#{subscriber.subscribeAction}"/>  </h:form> </body>
    </html> </f:view>   这是SubscriberBean.java源码
    1. package jsfdb.view;
    2. import jsfdb.model.Subscriber;
    3. import jsfdb.model.ModelUtils;
    4. import jsfdb.model.err.ProfileException;
    5. import jsfdb.model.err.SubscribeException;
    6. import jsfdb.model.err.UnsubscribeException;
    7. import javax.faces.component.UIComponent;
    8. import javax.faces.component.EditableValueHolder;
    9. import javax.faces.context.FacesContext;
    10. public class SubscriberBean extends Subscriber {
    11.     public final static String INVALID_EMAIL_ID
    12.         = "jsfdb.view.SubscriberBean.INVALID_EMAIL";
    13.     public final static String SELECT_NEWSLETTER_ID
    14.         = "jsfdb.view.SubscriberBean.SELECT_NEWSLETTER";
    15.     private transient boolean loggedIn = false;
    16.     public boolean isLoggedIn() {
    17.         return loggedIn;
    18.     }
    19.     public void setLoggedIn(boolean loggedIn) {
    20.         this.loggedIn = loggedIn;
    21.     }
    22.     public void emailValidator(FacesContext context, UIComponent comp, Object value) {
    23.         String email = (String) value;
    24.         if (email.indexOf("@") == -1) {
    25.             String compId = comp.getClientId(context);
    26.             ViewUtils.addErrorMessage(context, compId, INVALID_EMAIL_ID);
    27.             ((EditableValueHolder) comp).setValid(false);
    28.         }
    29.     }
    30.     public String subscribeAction() {
    31.         if (countNewsletters() == 0) {
    32.             ViewUtils.addErrorMessage(
    33.                 FacesContext.getCurrentInstance(),
    34.                 null, SELECT_NEWSLETTER_ID);
    35.             return null;
    36.         }
    37.         try {
    38.             ModelUtils.getSubscriberDAO().insert(this);
    39.             setLoggedIn(true);
    40.             return "subscribed";
    41.         } catch (SubscribeException x) {
    42.             ViewUtils.addExceptionMessage(x);
    43.             return null;
    44.         }
    45.     }
    46.     public String profileAction() {
    47.         if (!loggedIn)
    48.             return "login";
    49.         if (countNewsletters() == 0) {
    50.             ViewUtils.addErrorMessage(
    51.                 FacesContext.getCurrentInstance(),
    52.                 null, SELECT_NEWSLETTER_ID);
    53.             return null;
    54.         }
    55.         try {
    56.             ModelUtils.getSubscriberDAO().update(this);
    57.             return null;
    58.         } catch (ProfileException x) {
    59.             ViewUtils.addExceptionMessage(x);
    60.             return null;
    61.         }
    62.     }
    63.     public String unsubscribeAction() {
    64.         if (!loggedIn)
    65.             return "login";
    66.         try {
    67.             ModelUtils.getSubscriberDAO().delete(this);
    68.             return "unsubscribed";
    69.         } catch (UnsubscribeException x) {
    70.             ViewUtils.addExceptionMessage(x);
    71.             return null;
    72.         }
    73.     }
    74.     public String cancelAction() {
    75.         if (!loggedIn)
    76.             return "login";
    77.         else
    78.             return "cancel";
    79.     }
    80.     public int getDailyConst() {
    81.         return TYPE_DAILY;
    82.     }
    83.     public int getWeeklyConst() {
    84.         return TYPE_WEEKLY;
    85.     }
    86.     public int getMonthlyConst() {
    87.         return TYPE_MONTHLY;
    88.     }
    89. }
    90. 这是修改配置的页面:
    复制代码



    1. [img]http://img.javaxxz.com/2014/10/10/025325046.jpg[/img]
    2. 图二
    3.      
    复制代码

    再看看list.jsp

       图三  
      <!-- list.jsp -->
    <%@ page contentType="text/html; charset=gb2312" %>  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %> <c:if test="true">
        <c:redirect url="/login.faces"/>
    </c:if>     <c:if test="false">
        <c:redirect url="/profile.faces"/>
    </c:if>
    <sql:setDataSource driver="sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:jsfdb"/>
    <sql:query var="subscriberList" scope="request">
          SELECT * FROM subscribers ORDER BY subscriberEmail
    </sql:query> <f:view> <f:loadBundle var="labels" basename="jsfdb.view.res.Labels"/>
    <c:set var="stylesheet" value="/cwbwebhome/stylesheet.css"/> <html>
    <head>
    <title><h:outputText value="#{labels.list}"/></title>
    <link rel="stylesheet" type="text/css" href="<c:out value=""/>">
    </head>
    <body>  <h1><h:outputText value="#{labels.list}"/></h1>  <h:outputLink value="profile.faces">
        <h:outputText value="#{labels.profile}"/>
    </h:outputLink>  <h:outputLink value="logout.faces">
         <h:outputText value="#{labels.logout}"/>
    </h:outputLink>  <h:form id="list">  <h:dataTable id="table" var="row" value="#{subscriberList}" border="1" cellpadding="5">  <h:column>
        <f:facet name="header">
         <h:outputText value="#{labels.email}"/>
       </f:facet>
       <h:outputText value="#{row.subscriberEmail}"/>
    </h:column>  <h:column>
        <f:facet name="header">
          <h:outputText value="#{labels.password}"/>
         </f:facet>
         <h:outputText value="#{row.subscriberPassword}"/>
    </h:column>  <h:column>
        <f:facet name="header">
         <h:outputText value="#{labels.name}"/>
        </f:facet>
       <h:outputText value="#{row.subscriberName}"/>
    </h:column>  <h:column>
        <f:facet name="header">
          <h:outputText value="#{labels.manager}"/>
        </f:facet>
        <h:outputText value="#{row.managerFlag}"/>
    </h:column>  <h:column>
       <f:facet name="header">
           <h:outputText value="#{labels.developer}"/>
       </f:facet>
       <h:outputText value="#{row.developerFlag}"/>
    </h:column>  <h:column>
       <f:facet name="header">
         <h:outputText value="#{labels.administrator}"/>
       </f:facet>
       <h:outputText value="#{row.administratorFlag}"/>
    </h:column>  <h:column>
        <f:facet name="header">
         <h:outputText value="#{labels.subscriptionType}"/>
        </f:facet>
        <h:outputText value="#{row.subscriptionType}"/>
    </h:column>  </h:dataTable>  </h:form> </body>
    </html> </f:view> 这个页面用jstl标记访问数据库! 数据适配层和数据访问对象DAO    这个应用通过ModelUtils类访问后端数据源, 提供了 SubscriberDAO 接口的两个实现,一个(JDBCSubscriberDAO.java)基于 JDBC API,另一个(TopLinkSubscriberDAO.java)使用 Oracle TopLink。下面是ModelUtils类的源码:
    1. package jsfdb.model;
    2. import jsfdb.model.dao.SubscriberDAO;
    3. import java.beans.BeanInfo;
    4. import java.beans.Introspector;
    5. import java.beans.PropertyDescriptor;
    6. import java.beans.IntrospectionException;
    7. import java.lang.reflect.Method;
    8. import java.lang.reflect.InvocationTargetException;
    9. import java.util.ResourceBundle;
    10. import java.util.MissingResourceException;
    11. import java.util.logging.Level;
    12. import java.util.logging.Logger;
    13. public class ModelUtils {
    14.     public static final String RESOURCES
    15.         = ModelUtils.class.getPackage().getName() + ".res.ModelResources";
    16.     private static ResourceBundle resources;
    17.     private static SubscriberDAO subscriberDAO;
    18.     public static void log(Throwable x) {
    19.         Logger.global.log(Level.SEVERE, x.getMessage(), x);
    20.     }
    21.     public static synchronized ResourceBundle getResources() {
    22.         if (resources == null)
    23.             try {
    24.                 resources = ResourceBundle.getBundle(RESOURCES);
    25.             } catch (MissingResourceException x) {
    26.                 log(x);
    27.                 throw new InternalError(x.getMessage());
    28.             }
    29.         return resources;
    30.     }
    31.     public static String getResource(String key) {
    32.         return getResources().getString(key);
    33.     }
    34.     public synchronized static SubscriberDAO getSubscriberDAO() {
    35.         if (subscriberDAO == null)
    36.             try {
    37.                 Class daoClass = Class.forName(getResource("DAO"));
    38.                 subscriberDAO
    39.                     = (SubscriberDAO) daoClass.newInstance();
    40.             } catch (ClassNotFoundException x) {
    41.                 log(x);
    42.                 throw new InternalError(x.getMessage());
    43.             } catch (IllegalAccessException x) {
    44.                 log(x);
    45.                 throw new InternalError(x.getMessage());
    46.             } catch (InstantiationException x) {
    47.                 log(x);
    48.                 throw new InternalError(x.getMessage());
    49.             }
    50.         return subscriberDAO;
    51.     }
    52.     public static void copy(Object source, Object dest) {
    53.         try {
    54.             Class sourceClass = source.getClass();
    55.             Class destClass = dest.getClass();
    56.             BeanInfo info = Introspector.getBeanInfo(sourceClass);
    57.             PropertyDescriptor props[]
    58.                 = info.getPropertyDescriptors();
    59.             Object noParams[] = new Object[0];
    60.             Object oneParam[] = new Object[1];
    61.             for (int i = 0; i < props.length; i++) {
    62.                 Method getter = props[i].getReadMethod();
    63.                 if (getter == null)
    64.                     continue;
    65.                 Object value = getter.invoke(source, noParams);
    66.                 Method setter = props[i].getWriteMethod();
    67.                 if (setter != null && sourceClass != destClass)
    68.                     try {
    69.                         setter = destClass.getMethod(
    70.                             setter.getName(),
    71.                             setter.getParameterTypes());
    72.                     } catch (NoSuchMethodException x) {
    73.                         setter = null;
    74.                     }
    75.                 if (setter != null) {
    76.                     oneParam[0] = value;
    77.                     setter.invoke(dest, oneParam);
    78.                 }
    79.             }
    80.         } catch (IntrospectionException x) {
    81.             log(x);
    82.             throw new InternalError(x.getMessage());
    83.         } catch (IllegalAccessException x) {
    84.             log(x);
    85.             throw new InternalError(x.getMessage());
    86.         } catch (IllegalArgumentException x) {
    87.             log(x);
    88.             throw new InternalError(x.getMessage());
    89.         } catch (SecurityException x) {
    90.             log(x);
    91.             throw new InternalError(x.getMessage());
    92.         } catch (InvocationTargetException x) {
    93.             log(x.getTargetException());
    94.             throw new InternalError(
    95.                 x.getTargetException().getMessage());
    96.         }
    97.     }
    98. }
    复制代码
         此类的getSubscriberDAO()方法返回 SubscriberDAO 接口的一个实例,该接口定义了在关系数据库中选择、删除、插入、更新 Subscriber 对象的方法。 你的应用中具体使用哪一个后端数据源,在 ModelResources资源包有一个 DAO 参数,用于指定要使用的 DAO 实现. 这是ModelResources.properties文件:
    DAO=jsfdb.model.dao.JDBCSubscriberDAO  # DAO=jsfdb.model.dao.TopLinkSubscriberDAO
    TopLinkSession=JSFDBSession JavaCompEnv=java:comp/env
    DataSource=jdbc/OracleDS SelectStatement=SELECT
    subscriberPassword,
    subscriberName,
    managerFlag,
    developerFlag,
    administratorFlag,
    subscriptionType
    FROM subscribers
    WHERE subscriberEmail=? InsertStatement=INSERT INTO subscribers (
    subscriberEmail,
    subscriberPassword,
    subscriberName,
    managerFlag,
    developerFlag,
    administratorFlag,
    subscriptionType )
    VALUES (?, ?, ?, ?, ?, ?, ?) UpdateStatement=UPDATE subscribers SET
    subscriberPassword=?,
    subscriberName=?,
    managerFlag=?,
    developerFlag=?,
    administratorFlag=?,
    subscriptionType=?
    WHERE subscriberEmail=? DeleteStatement=DELETE FROM subscribers
    WHERE subscriberEmail=? SubscribeException=Subscription failed.
    Please try another email address.
    ProfileException=Couln"t update your profile.
    Please contact the Webmaster.
    UnsubscribeException=Unsubscription failed.
    Please contact the Webmaster.
    LoginException=Login failed.
    Please contact the Webmaster.
    UnknownSubscriberException=Unknown subscriber.
    Please subscribe.
    IncorrectPasswordException=Incorrect password.
    Please try to login again.
    我做这个例子时用了Access数据库
    1. package jsfdb.model.dao;
    2. import jsfdb.model.LoginInfo;
    3. import jsfdb.model.Subscriber;
    4. import jsfdb.model.ModelUtils;
    5. import jsfdb.model.err.IncorrectPasswordException;
    6. import jsfdb.model.err.LoginException;
    7. import jsfdb.model.err.ProfileException;
    8. import jsfdb.model.err.SubscribeException;
    9. import jsfdb.model.err.UnknownSubscriberException;
    10. import jsfdb.model.err.UnsubscribeException;
    11. import java.sql.Connection;
    12. import java.sql.PreparedStatement;
    13. import java.sql.ResultSet;
    14. import java.sql.SQLException;

    15. public class JDBCSubscriberDAO implements SubscriberDAO {
    16.   //  private DataSource dataSource;
    17.     public JDBCSubscriberDAO() {
    18.           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    19.         
    20.            
    21.     }
    22.     private void close(Connection conn, PreparedStatement ps)
    23.             throws SQLException {
    24.         if (ps != null)
    25.             ps.close();
    26.         if (conn != null)
    27.             conn.close();
    28.     }
    29.     public Subscriber select(LoginInfo loginInfo)
    30.             throws LoginException,
    31.             UnknownSubscriberException,
    32.             IncorrectPasswordException {
    33.         Connection conn = DriverManager.getConnection("jdbc:odbc:jsfdb");
    34.         PreparedStatement ps = null;
    35.         try {
    36.             conn = dataSource.getConnection();
    37.             ps = conn.prepareStatement(
    38.                 ModelUtils.getResource("SelectStatement"));
    39.             ps.setString(1, loginInfo.getEmail());
    40.             ResultSet rs = ps.executeQuery();
    41.             if (!rs.next())
    42.                 throw new UnknownSubscriberException();
    43.             String password = rs.getString(1);
    44.             if (!loginInfo.getPassword().equals(password))
    45.                 throw new IncorrectPasswordException();
    46.             Subscriber subscriber = new Subscriber();
    47.             subscriber.setEmail(loginInfo.getEmail());
    48.             subscriber.setPassword(loginInfo.getPassword());
    49.             subscriber.setName(rs.getString(2));
    50.             subscriber.setManager(rs.getBoolean(3));
    51.             subscriber.setDeveloper(rs.getBoolean(4));
    52.             subscriber.setAdministrator(rs.getBoolean(5));
    53.             subscriber.setSubscriptionType(rs.getInt(6));
    54.             return subscriber;
    55.         } catch (SQLException x) {
    56.             ModelUtils.log(x);
    57.             throw new LoginException();
    58.         } finally {
    59.             try {
    60.                 close(conn, ps);
    61.             } catch (SQLException x) {
    62.                 ModelUtils.log(x);
    63.                 throw new LoginException();
    64.             }
    65.         }
    66.     }
    67.     public void insert(Subscriber subscriber)
    68.             throws SubscribeException {
    69.         Connection conn = DriverManager.getConnection("jdbc:odbc:jsfdb");
    70.         PreparedStatement ps = null;
    71.         try {
    72.             conn = dataSource.getConnection();
    73.             ps = conn.prepareStatement(
    74.                 ModelUtils.getResource("InsertStatement"));
    75.             ps.setString(1, subscriber.getEmail());
    76.             ps.setString(2, subscriber.getPassword());
    77.             ps.setString(3, subscriber.getName());
    78.             ps.setBoolean(4, subscriber.isManager());
    79.             ps.setBoolean(5, subscriber.isDeveloper());
    80.             ps.setBoolean(6, subscriber.isAdministrator());
    81.             ps.setInt(7, subscriber.getSubscriptionType());
    82.             int rowCount = ps.executeUpdate();
    83.             if (rowCount != 1)
    84.                 throw new SubscribeException();
    85.         } catch (SQLException x) {
    86.             ModelUtils.log(x);
    87.             throw new SubscribeException();
    88.         } finally {
    89.             try {
    90.                 close(conn, ps);
    91.             } catch (SQLException x) {
    92.                 ModelUtils.log(x);
    93.                 throw new SubscribeException();
    94.             }
    95.         }
    96.     }
    97.     public void update(Subscriber subscriber)
    98.             throws ProfileException {
    99.         Connection conn = DriverManager.getConnection("jdbc:odbc:jsfdb");
    100.         PreparedStatement ps = null;
    101.         try {
    102.             conn = dataSource.getConnection();
    103.             ps = conn.prepareStatement(
    104.                 ModelUtils.getResource("UpdateStatement"));
    105.             ps.setString(1, subscriber.getPassword());
    106.             ps.setString(2, subscriber.getName());
    107.             ps.setBoolean(3, subscriber.isManager());
    108.             ps.setBoolean(4, subscriber.isDeveloper());
    109.             ps.setBoolean(5, subscriber.isAdministrator());
    110.             ps.setInt(6, subscriber.getSubscriptionType());
    111.             ps.setString(7, subscriber.getEmail());
    112.             int rowCount = ps.executeUpdate();
    113.             if (rowCount != 1)
    114.                 throw new ProfileException();
    115.         } catch (SQLException x) {
    116.             ModelUtils.log(x);
    117.             throw new ProfileException();
    118.         } finally {
    119.             try {
    120.                 close(conn, ps);
    121.             } catch (SQLException x) {
    122.                 ModelUtils.log(x);
    123.                 throw new ProfileException();
    124.             }
    125.         }
    126.     }
    127.     public void delete(Subscriber subscriber)
    128.             throws UnsubscribeException {
    129.         Connection conn = DriverManager.getConnection("jdbc:odbc:jsfdb");
    130.         PreparedStatement ps = null;
    131.         try {
    132.             conn = dataSource.getConnection();
    133.             ps = conn.prepareStatement(
    134.                 ModelUtils.getResource("DeleteStatement"));
    135.             ps.setString(1, subscriber.getEmail());
    136.             int rowCount = ps.executeUpdate();
    137.             if (rowCount != 1)
    138.                 throw new UnsubscribeException();
    139.         } catch (SQLException x) {
    140.             ModelUtils.log(x);
    141.             throw new UnsubscribeException();
    142.         } finally {
    143.             try {
    144.                 close(conn, ps);
    145.             } catch (SQLException x) {
    146.                 ModelUtils.log(x);
    147.                 throw new UnsubscribeException();
    148.             }
    149.         }
    150.     }
    151. }
    复制代码


      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/10/025337937.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-26 18:01 , Processed in 0.300190 second(s), 36 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表