servlet.java

来自「weblogic应用全实例」· Java 代码 · 共 236 行

JAVA
236
字号
//定义本接口在包examples.ejb20.basic.beanManaged
package examples.ejb20.basic.beanManaged;
//本类用到的其他类。
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Properties;
import java.util.Vector;
import java.util.Iterator;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weblogic.html.BreakElement;
import weblogic.html.HeadingElement;
import weblogic.html.ServletPage;
import weblogic.html.StringElement;
import javax.rmi.PortableRemoteObject;

/**
 * 这个servlet和Client类类似
 * 这个servlet必须在web.xml文件中注册
 * 使用url http://localhost:7001/examplesWebApp/beanManaged调用这个servlet
 */
public class Servlet extends HttpServlet { 

  static String accountId    = "10020";

  /**
   * service方法
   * @参数 req               HttpServletRequest
   * @参数 res               HttpServletResponse
   * @异常               java.io.IOException
   *                          如果IO错误
   */
  public void service(HttpServletRequest req, HttpServletResponse res)
    throws IOException 
  {
   //设置文档类型
    res.setContentType("text/html");
    OutputStream out = res.getOutputStream();
    String title = "EJBean Bean-managed Persistence Servlet";
    //ServletPage实例
    ServletPage sp = new ServletPage(title);
    //编辑html元素
    sp.getBody()
      .addElement(new HeadingElement(title, 1));
    printElement("", sp);

    // 获取参数 
    // "http://localhost:7001/beanManaged?user=foobar&password=FooBarNone"
   //用户名
    String user     = req.getParameter("user");
    //密码
    String password = req.getParameter("password");

    if(user!=null && password!=null){
      printElement("Using user <b>" + user
                   + "</b> and password <b> " + password + "</b>", sp);
      printElement("", sp);
    } else {
      printElement("No user and password credentials", sp);
      printElement("", sp);
    }
    
    double amount  = 100;
    double balance = 3000;
    Vector v = new Vector();

    try {
      // 获取上下文
      Context ctx = getInitialContext();
      AccountHome home = (AccountHome) ctx.lookup("ejb-beanManaged-AccountHome");

      // 查找Account或创建它
      Account ac = null;
      try {
        printElement("Looking up account " + accountId + "...", sp);
        ac = (Account) home.findByPrimaryKey(accountId);
      } 
      catch (Exception ee) {
      	//异常处理	
        printElement("Did not find " + accountId, sp);
      }

      if (ac == null) {
        printElement("Account " + accountId + 
                           " being created; opening balance is $" + balance, sp);
        //创建远程对象                   
        ac = home.create(accountId, balance);      
      } 
      else {
        printElement("Account " + accountId + " found; balance is $" + ac.balance(), sp);
      }
      printElement("", sp);

     // A部分: 存入和提取大于当前结算的金额,会抛出用户定义的异常

      printElement("Part A: Depositing $" + amount, sp);
      //存入
      balance = ac.deposit(amount);
      printElement("Current balance is $" + balance, sp);
      printElement("", sp);

      amount = balance + 10;
      try {
        printElement("Withdrawing amount greater than current balance. Expecting an exception...", sp);
         //提取
        balance = ac.withdraw(amount);
        printElement("Error: expected an exception.", sp);
      } 
      catch (ProcessingErrorException pe) {
      //用户定义的异常	
        printElement("Received expected Processing Error:<br>" + pe, sp);
      }
      printElement("", sp);

      // B部分: 创建一些新的用户,并给定不同的初始结算
      // 查找结算大于给定值的所有账号
      // 最后,删除所有新的账号

      int numAccounts = 5;
      printElement("Part B: Creating " + numAccounts + " new accounts...", sp);
      long now = System.currentTimeMillis();
      for (int i = 0; i < numAccounts; i++) {
        String id = "" + now + i;  // 唯一的账号id
        balance = i*100; // 初始结算
        v.addElement(home.create(id, balance)); 
        printElement("Created account: " + id + 
                           "; balance is $" + balance, sp);
      }
      printElement("", sp);

      if (v.size() == numAccounts) {
        printElement("" + numAccounts + " accounts successfully created", sp);
      }
      else {
        printElement("Error: Only " + v.size() + 
                           " accounts were created successfully", sp);
      }
      printElement("", sp);

      double balanceGreaterThan = 200;
      printElement("Querying for accounts with a balance greater than " +
                         balanceGreaterThan + "...", sp);
//调用主接口的方法   
      Collection col = home.findBigAccounts(balanceGreaterThan);

      if(col.isEmpty()) {
        log("No accounts were found with a balance greater than " +balanceGreaterThan);
      }
    
      Iterator it = col.iterator();
      while (it.hasNext()) {
      	//每个账号	
        Account accountGT =
          (Account) PortableRemoteObject.narrow(it.next(),Account.class);
          //打印每个账号的主键
          log("Account " + accountGT.getPrimaryKey() + "; balance is $" + accountGT.balance());
          Thread.sleep(1000);
      }
      printElement("", sp);


      printElement("Removing accounts just created...", sp);
      for (int i = 0; i < numAccounts; i++) {
        String id = "" + now + i; 
         //清除所有账号
        ((Account)(v.elementAt(i))).remove();
        printElement("Removed account: " +id, sp);
      }
      printElement("", sp);

    // 捕获异常
    } 
    catch (ProcessingErrorException pe) {
      printElement("Unexpected Processing Error: " + pe, sp);
    }
    catch (Exception e) {
    	其它异常
      printElement(":::::::::::::: Unexpected Error :::::::::::::::::", sp);
      e.printStackTrace();
    }
    finally {
      printElement("End beanManaged.Servlet...", sp);
    }

    sp.output(out);
    out.flush();
  }
  
  /**
   * 基本的servlet信息
   */
  public String getServletInfo() {
    return "EJBean Servlet";
  }

  /**
   * 打印一个bean的HTML信息
   */
  static private void printAccount(Account account, ServletPage sp)
    throws RemoteException, IOException {
    printElement("Account " + account.getPrimaryKey() + 
                 "; balance is $" + account.balance(), sp);
  }

  /**
   * 打印消息给浏览器
   */
  static private void printElement(String message, ServletPage sp) 
    throws IOException {
    sp.getBody()
      .addElement(new BreakElement())
      .addElement(new StringElement(message));
  }

  /**
   * 获取当前用户、密码和url的初始化上下文。
   *
   * @return                  上下文
   * @异常               java.lang.Exception if there is
   *                          an error in getting the Context
   */
  static public Context getInitialContext() throws Exception {
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
        "weblogic.jndi.WLInitialContextFactory");
    return new InitialContext(p);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?