java web开发 环境准备 Lomboz+struts+Sqlserver2k+tomcat

来源:互联网 发布:php无限分类原理 编辑:程序博客网 时间:2024/06/05 01:09

1.      环境准备

1.1.      软件安装

1.    先到以下网站下载相应软件

l           Eclipse (Lomboz): http://lomboz.objectweb.org/downloads/download.php

l           tomcat: http://tomcat.apache.org/download-55.cgi

l           SQL Server 2000 SP4:
英文版:

http://www.microsoft.com/downloads/details.aspx?FamilyID=8e2dfc8d-c20e-4446-99a9-b7f0213f8bc5&DisplayLang=en
中文版:
http://www.microsoft.com/downloads/details.aspx?FamilyID=8e2dfc8d-c20e-4446-99a9-b7f0213f8bc5&DisplayLang=zh-cn

l           SQL Server 2000 Driver for JDBC Service Pack 3
http://www.microsoft.com/downloads/details.aspx?FamilyID=07287b11-0502-461a-b138-2aa54bfdc03a&DisplayLang=en

l           Struts: http://struts.apache.org/download.cgi 

2.    安装SQL Server 2000

1.         安装SQL Server 2000

2.         安装SQL Server 2000 SP4

3.    安装Eclipse:解压Eclipse包即可

4.    安装tomcat

1.         安装Tomcat

2.         复制SQL Server 2000 Driver for JDBC的驱动包msbase.jar, mssqlserver.jar, msutil.jar${Tomcat}/common/lib目录

5.    安装Struts,解压struts包即可

1.2.      测试环境

1.2.1.      测试Tomcat

1.         运行${Tomcat}/bin/tomcat.exe

2.         打开http://127.0.0.1:8080/ ,如果出现tomcat的欢迎界面,那么就运行成功了。

 

1.2.2.      Eclipse中设置Tomcat

1.         打开Windows/Preferences选择项

2.         Web Services/Server and Runtime中选择Tomcat Server

3.         Server/Installed Runtimes中加入Tomcat Server

 

1.2.3.      测试SQL Server的连接

1.         运行以下代码

import java.sql.DriverManager;

 

public class SqlserverConnect {

    private java.sql.Connection  con = null;

    private final String url = "jdbc:microsoft:sqlserver://";

    private final String serverName= "127.0.0.1";

    private final String portNumber = "1433";

    private final String databaseName= "db_library";

    private final String userName = "libuser";

    private final String password = "libuser";

    // Informs the driver to use server a side-cursor,

    // which permits more than one active statement

    // on a connection.

    private final String selectMethod = "cursor";

   

    // Constructor

    public SqlserverConnect(){}

   

    private String getConnectionUrl(){

      //return url+serverName+":"+portNumber;

         return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";

    }

   

    private java.sql.Connection getConnection(){

         try{

              //Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

              DriverManager.registerDriver(new  com.microsoft.jdbc.sqlserver.SQLServerDriver());  

              con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);

              if(con!=null) System.out.println("Connection Successful!");

         }catch(Exception e){

              e.printStackTrace();

              System.out.println("Error Trace in getConnection() : " + e.getMessage());

        }

         return con;

     }

 

    /*

         Display the driver properties, database details

    */

 

    public void displayDbProperties(){

         java.sql.DatabaseMetaData dm = null;

         java.sql.ResultSet rs = null;

         try{

              con= this.getConnection();

              if(con!=null){

                   dm = con.getMetaData();

                   System.out.println("Driver Information");

                   System.out.println("/tDriver Name: "+ dm.getDriverName());

                   System.out.println("/tDriver Version: "+ dm.getDriverVersion ());

                   System.out.println("/nDatabase Information ");

                   System.out.println("/tDatabase Name: "+ dm.getDatabaseProductName());

                   System.out.println("/tDatabase Version: "+ dm.getDatabaseProductVersion());

                   System.out.println("Avalilable Catalogs ");

                   rs = dm.getCatalogs();

                   while(rs.next()){

                        System.out.println("/tcatalog: "+ rs.getString(1));

                   }

                   rs.close();

                   rs = null;

                   closeConnection();

              }else System.out.println("Error: No active Connection");

         }catch(Exception e){

              e.printStackTrace();

         }

         dm=null;

    }    

   

    private void closeConnection(){

         try{

              if(con!=null)

                   con.close();

              con=null;

         }catch(Exception e){

              e.printStackTrace();

         }

    }

    public static void main(String[] args) throws Exception

      {

      SqlserverConnect myDbTest = new SqlserverConnect();

         myDbTest.displayDbProperties();

      }

}

 

如果出现以下运行结果,则运行成功。

Connection Successful!

Driver Information

    Driver Name: SQLServer

    Driver Version: 2.2.0040

 

Database Information

    Database Name: Microsoft SQL Server

    Database Version: Microsoft SQL Server  2000 - 8.00.2039 (Intel X86)

    May  3 2005 23:18:38

    Copyright (c) 1988-2003 Microsoft Corporation

    Personal Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

 

Avalilable Catalogs

    catalog: db_library

    catalog: master

    catalog: msdb

    catalog: Northwind

    catalog: pubs

    catalog: tempdb

1.2.4.      测试Struts

1.    Lomboz里新建一个Dynamic Web Project

2.    Project Facets中勾选Struts,其他步骤按照提示选择即可。

3.    建立以下类:

GetParameterForm

package cn.ac.ict;

import org.apache.struts.action.ActionForm;

 

public class GetParameterForm extends ActionForm{

    private String valuw="null";

    private String pass="null";

 

    public GetParameterForm() {

       }

    public void setValu(String s) {

       valuw = s;

       }

    public String getValu() {

       return valuw;

       }

    public String getPass() {

       return pass;

    }

    public void setPass(String pass) {

       this.pass = pass;

    }

       }

 

ShowAction

package cn.ac.ict;

 

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.*;

import org.apache.struts.util.*;

 

public final class ShowAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response)

           throws Exception {

       Locale locale = getLocale(request);

       MessageResources messages = getResources(request);

       HttpSession session = request.getSession();

       GetParameterForm userform = (GetParameterForm) form;

       // if (userform.getValu().equals("success")) {

       System.out.println("userform.getValu():"+userform.getValu());

       System.out.println("userform.getPass():"+userform.getPass());

       if (userform.getValu().equals("ben")& userform.getPass().equals("grace")) {

           return (mapping.findForward("success"));

       } else {

           return (mapping.findForward("fail"));

       }

    }

}

 

4.    建立以下JSP文件

index.jsp

<%@ page contentType="text/html;charset=gb2312"%>

<%@ page import="java.util.*,java.sql.*,java.text.*,java.io.*"%>

 

<form name="form1" method="post" action="showinput.do">

输入bengrace将返回到"success"页面,否则返回到"fail"页面<br>

<br>

input:<input type="text" name="valu"><br>

password:<input type="text" name="pass">

<input type="submit"

    value="submit"></form>

<br>

<a href="success.do">success</a>

<br>

<a href="fail.do">fail</a>

 

success.jsp

<%@ page contentType="text/html;charset=gb2312"%>

 

success!

 

fail.jsp

<%@ page contentType="text/html;charset=gb2312"%>

 

fail!

 

5.    配置Struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>

 

<!DOCTYPE struts-config PUBLIC

          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"

          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

<!-- ========== Form Bean Definitions =================================== -->

       <form-beans>

              <form-bean name="GetParameterForm" type="cn.ac.ict.GetParameterForm"/>

       </form-beans>

 

<!-- ========== Global Forward Definitions ============================== -->

       <global-forwards>

              <forward name="success" path="/success.do"/>

              <forward name="fail" path="/fail.do"/>

       </global-forwards>

 

<!-- ========== Action Mapping Definitions ============================== -->

       <action-mappings>

       <action path="/showinput"

                     type="cn.ac.ict.ShowAction"

                     name="GetParameterForm"

                     scope="request"

                     input="/index.jsp" >

                     <forward

                name="success"

                path="/success.jsp"/>

                     <forward

                name="fail"

                path="/fail.jsp"/>

        </action>

       </action-mappings>

 

</struts-config>

 

6.    配置Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>

    firstStruts</display-name>

    <servlet>

       <servlet-name>action</servlet-name>

       <servlet-class>

       org.apache.struts.action.ActionServlet</servlet-class>

       <init-param>

           <param-name>config</param-name>

           <param-value>/WEB-INF/struts-config.xml</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

       <servlet-name>action</servlet-name>

       <url-pattern>*.do</url-pattern>

    </servlet-mapping>

    <welcome-file-list>

       <welcome-file>index.html</welcome-file>

       <welcome-file>index.htm</welcome-file>

       <welcome-file>index.jsp</welcome-file>

       <welcome-file>default.html</welcome-file>

       <welcome-file>default.htm</welcome-file>

       <welcome-file>default.jsp</welcome-file>

    </welcome-file-list>

</web-app>

7.    运行项目

 

8.    如果出现以下画面输入用户名和密码后转到success画面则为成功

 

 

1.2.5.      Web连接数据库

1.    建立一个Web项目如1.2.4“测试Struts”中所示

2.    Tomcat设置数据库数据源。

运行Web项目后Lomboz会在package Explorer中加入“Server”文件夹,打开该文件夹中的Server.xml,在Web项目的Context参数中加入Datasource的设置。

<Context docBase="jdbcsample" path="/jdbcsample" reloadable="true"

    source="org.eclipse.jst.j2ee.server:jdbcsample">

    <Resource name="jdbc/libdatasource" auth="Container" type="javax.sql.DataSource"                   driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"     url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=db_library"

    username="libuser" password="libuser" maxActive="20" maxIdle="10"

                     maxWait="-1" />

</Context>

3.    建立以下类

TomcatConnectionAction

package cn;

import com.microsoft.jdbc.sqlserver.SQLServerDriver;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.servlet.http.*;

import javax.naming.InitialContext;

import javax.rmi.PortableRemoteObject;

import org.apache.struts.action.*;

import java.sql.*;

import java.util.ArrayList;

import javax.sql.DataSource;

 

public class TomcatConnectionAction extends Action {

    private DataSource datasource;

    protected Connection conn = null;   

    public ArrayList customerList = new ArrayList();

    private final static String SUCCESS = "success";

    private final static String FAIL = "fail";

   

    public ActionForward execute(ActionMapping mapping, ActionForm  form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

 

    java.sql.Connection myConnection;

       try {

           String JNDIName = "java:comp/env/jdbc/libdatasource";

           InitialContext ctx = new InitialContext();

           Object objref = ctx.lookup(JNDIName);

           datasource = (DataSource) PortableRemoteObject.narrow(objref,

                  DataSource.class);

           conn = datasource.getConnection();

       }catch(Exception ex){ex.printStackTrace();return (mapping.findForward(FAIL));}

       return (mapping.findForward(SUCCESS));

    }

}

 

4.    建立以下JSP文件

index.jsp

<%@ page contentType="text/html;charset=gb2312"%>

<%@ page import="java.util.*,java.sql.*,java.text.*,java.io.*"%>

 

<br>

<a href="connect_tomcat.do">connect database by Tomcat</a>

 

5.    配置Struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>

<struts-config>

    <action-mappings>

       <action path="/connect_tomcat" type="cn.TomcatConnectionAction"

           scope="request" input="/index.jsp">

           <forward name="success" path="/success.jsp" />

           <forward name="fail" path="/fail.jsp" />

       </action>    

    </action-mappings>

</struts-config>

 

6.    配置Web.xml1.2.4的配置一样

7.    运行Web项目,如果点击“connect database by Tomcat”连接后转向success则成功

 

原创粉丝点击