在应用程序中内嵌tomcat7.0

经过一上午的摸索,终于搞定了如何内嵌tomcat7.0。其实挺简单的,主要在于与以前版本不同,tomcat7.0只要新建一个对象,就可以完成JSP服务器的启动与关闭,这个关键的类就是Tomcat;

以下是我今天的写的相关代码。IDE用的是Eclipse

主要的结构为:

在应用程序中内嵌tomcat7.0_第1张图片

以下是三个JAVA类的代码:

EmbededTomcat.java --->封装TOMCAT

package org.lee; import org.apache.catalina.LifecycleException; import org.apache.catalina.startup.Tomcat; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import java.io.File; import javax.servlet.ServletException; public class EmbededTomcat { private final Log log=LogFactory.getLog(getClass()); private Tomcat tomcat=new Tomcat(); private int port; public EmbededTomcat(int port){ this.port=port; } public void start()throws Exception{ String projectPath=new File("").getAbsolutePath(); tomcat.setPort(port); try{ tomcat.addWebapp("",projectPath+"/web"); }catch(ServletException e){ e.printStackTrace(); log.error(e.getMessage()); throw e; } try{ tomcat.start(); }catch(LifecycleException e){ e.printStackTrace(); log.error(e.getMessage()); throw e; } log.info("Tomcat started."); } public void stop()throws Exception{ try{ tomcat.stop(); } catch(LifecycleException ex){ ex.printStackTrace(); log.error(ex.getMessage()); throw ex; } log.info("Tomcat stoped"); } public void setPort(int port){ this.port=port; } public int getPort(){ return this.port; } }

MainFrame.java ---》主窗体

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MainFrame.java * * Created on 2011-11-27, 7:58:59 */ package org.lee; import java.awt.Toolkit; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; /** * * @author Administrator */ public class MainFrame extends javax.swing.JFrame implements WindowListener{ private EmbededTomcat et; private int port=8000; private boolean flag=false; private int DESKTOP_WIDTH; private int DESKTOP_HEIGHT; /** Creates new form MainFrame */ public MainFrame() { initComponents(); jTextField1.setText(String.valueOf(port)); DESKTOP_WIDTH=Toolkit.getDefaultToolkit().getScreenSize().width; DESKTOP_HEIGHT=Toolkit.getDefaultToolkit().getScreenSize().height; setLocation((DESKTOP_WIDTH-getWidth())/2,(DESKTOP_HEIGHT-getHeight())/2); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel1.setText("端口号:"); jButton1.setText("进 入"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("退 出"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton4.setText("关 于"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(86, 86, 86) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE) .addComponent(jButton4) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: //使用第三方线程 EDT new Thread(new Runnable(){ public void run(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ /**------start------------ */ try{ if(jTextField1.getText().equals("")){ JOptionPane.showMessageDialog(rootPane, "璇疯緭鍏ョ鍙e彿"); } else{ port=Integer.parseInt(jTextField1.getText()); et=new EmbededTomcat(port); if(flag==true){ startIE(); } else{ et.start(); startIE(); flag=true; } } /**------end------------ */ } catch(Exception e){ JOptionPane.showMessageDialog(rootPane, e.getMessage()); } } }); } }).start(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: try{ if(et!=null){ et.stop(); } System.exit(0); } catch(Exception e){ JOptionPane.showConfirmDialog(rootPane, e.getMessage()); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: Aboutus about=new Aboutus(this,true); about.setLocation((DESKTOP_WIDTH-about.getWidth())/2,(DESKTOP_HEIGHT-about.getHeight())/2); about.setVisible(true); }//GEN-LAST:event_jButton4ActionPerformed /* * 启动IE */ public void startIE()throws IOException{ Runtime.getRuntime().exec("C://Program Files//Internet Explorer//IEXPLORE.EXE "+ "http://localhost:"+port); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent arg0) { // TODO Auto-generated method stub try{ if(et!=null){ et.stop(); } } catch(Exception ex){ ex.printStackTrace(); } } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } }

Aboutus.java ---》软件信息面板

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * aboutus.java * * Created on 2011-11-27, 9:23:54 */ package org.lee; /** * * @author Administrator */ public class Aboutus extends javax.swing.JDialog { /** Creates new form aboutus */ public Aboutus(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel1.setText("SuperSoft"); jLabel2.setText("Version:1.0"); jLabel3.setText("the software is protected."); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(301, Short.MAX_VALUE) .addComponent(jButton1) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addContainerGap(280, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addContainerGap(292, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addContainerGap(190, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE) .addComponent(jButton1) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }

生成可执行的JAR文件便可运行此JAVA应用了。如果觉得要使程序大众化,即在不安装JDK或JRE的情况下使用,可参考我在

http://blog.csdn.net/tomyjohn/archive/2011/05/27/6449831.aspx这所写的如何用EXE文件启动JAR。

看到这里你好像有些想法了,如果可以这样做的话,是不是以后我所写的软件,可以不用做成C/S了,直接做成B/S,而且便于使用。如是再加上一两个内嵌的数据库,即可实现100%的可移植。

下面我将会学习如何使用db4o这个开源的面向对象的内嵌数据库。

你可能感兴趣的:(tomcat,exception,layout,Constructor,templates,variables)