首页 > 数据库 > MySQL > 正文

Tomcat5.0+MySql配置JDBC,DBCP,SSL

2024-07-24 12:57:15
字体:
来源:转载
供稿:网友
准备环境:

1.j2sdk-1_4_2-windows-i586.exe

//jdk

2.mysql-4.0.20d-win.zip

//mysql数据库

3.mysqlcc-0.9.4-win32.zip

//mysqlgui控制

4.jakarta-tomcat-5.0.27.exe

//tomcat服务器

5.mysql-connector-java-3.0.14-production.zip

//内含mysql驱动

安装步骤:

1.安装jdk

2.安装tomcat

3.安装mysql

4.安装mysqlcc

5.将驱动包解压,拷贝mysql-connector-java-3.0.14-production-bin.jar

到tomcat/common/lib下

或者下载mm.mysql-2.0.14-you-must-unjar-me.jar,

解压后拷贝其中的mm.mysql-2.0.14-bin.jar

tomcat5.0配置 本例使用安装密码 198277

1.配置manager 管理应用程序

在conf/server.xml 中

添加如下:

<service name="catalina">...    <context path="/manager" debug="0" privileged="true"             docbase="/usr/local/kinetic   /tomcat5/server/webapps/manager">    </context></service>


限制ip访问配置

<context path="/manager" debug="0" privileged="true"         docbase="/usr/local/kinetic   /tomcat5/server/webapps/manager">         <valve classname="org.apache.   catalina.valves.remoteaddrvalve"                allow="127.0.0.1"/></context>


测试为:http://localhost:8080/manager/html

2、配置jdbcrealm容器管理安全,以mysql-4.0数据库为例

a.拷贝驱动mm.mysql-2.0.14-bin.jar到common/lib/下

b.在数据库ycg中建表

create table users (  user_name           varchar(15) not null primary key,  user_pass           varchar(15) not null);create table user_roles (  user_name           varchar(15) not null,  role_name           varchar(15) not null,  primary key (user_name, role_name));


c.修改server.xml如下(默认数据库为root,无密码,如果有形如:

connectionurl="jdbc:mysql://localhost/authority?user=dbuser&password=dbpass")      <realm  classname="org.apache.catalina.   realm.jdbcrealm" debug="99"             drivername="    org.gjt.mm.mysql.driver"          connectionurl="jdbc:mysql:    //localhost/ycg?user=root"         connectionname=""    connectionpassword=""              usertable="users"      usernamecol="user_name"     usercredcol="user_pass"          userroletable="user_roles"    rolenamecol="role_name" />


d.在数据库中添加入tomcat的默认配置数据:



e.启动mysql,启动tomcat,此后tomcat将从数据库中读用户规则认证.默认的conf/tomcat-users.xml失效

3.dbcp的配置

a.设置

<parameter>    <name>removeabandoned</name>        <value>true</value>            </parameter>


可使失效的数据连接重新启用.

配套设置

<parameter>    <name>removeabandonedtimeout</name>          <value>60</value>            </parameter>


失效时间

如果要写入日志

设置

<parameter>    <name>logabandoned</name>         <value>true</value>            </parameter>


以上三个默认都是false

b.以mysql为例,配置数据连接池

c.配置新的用户与数据库,必须设定密码,空密码将导致连接失败

e.

指定root密码:

mysqladmin -u root -h localhost password "198277"


(需修改上面的jdbcrealm设置connectionurl="jdbc:mysql://localhost/ycg?user=root&password=198277")

命令mysql进入匿名连接到服务器

密码访问

shell> mysql -h host -u user -penter password: ********//如果root没有密码,以下是不成功的.(试过了) mysql> grant all privileges on *.* to [email protected]     ->   identified by 'javadude'  with grant option;mysql> create database javatest;mysql> use javatest;mysql> create table testdata(    ->   id int not null  auto_increment primary key,    ->   foo varchar(25),     ->   bar int);在conf/server.xml中<host></host>中添加<context path="/dbtest" docbase="dbtest"        debug="5" reloadable="true"   crosscontext="true">  <logger classname="org.apache.  catalina.logger.filelogger"             prefix="localhost_dbtest_log."     suffix=".txt"             timestamp="true"/>  <resource name="jdbc/testdb"               auth="container"               type="javax.sql.datasource"/>  <resourceparams name="jdbc/testdb">    <parameter>      <name>factory</name>      <value>org.apache.commons.dbcp.   basicdatasourcefactory</value>    </parameter>    <!-- maximum number of db connections  in pool. make sure you         configure your mysqld    max_connections large enough to handle         all of your db connections.    set to 0 for no limit.         -->    <parameter>      <name>maxactive</name>      <value>100</value>    </parameter>    <!-- maximum number of idle db connections to retain in pool.         set to 0 for no limit.         -->    <parameter>      <name>maxidle</name>      <value>30</value>    </parameter>    <!-- maximum time to wait for a  db connection to become available         in ms, in this example 10   seconds. an exception is thrown if         this timeout is exceeded.    set to -1 to wait indefinitely.         -->    <parameter>      <name>maxwait</name>      <value>10000</value>    </parameter>    <!-- mysql db username and password for db connections  -->    <parameter>     <name>username</name>     <value>javauser</value>    </parameter>    <parameter>     <name>password</name>     <value>javadude</value>    </parameter>    <!-- class name for the old mm. mysql jdbc driver - uncomment this entry and comment next         if you want to use this driver   - we recommend using connector/j though    <parameter>       <name>driverclassname</name>       <value>org.gjt.mm.mysql.driver</value>    </parameter>     -->        <!-- class name for the official mysql connector/j driver -->    <parameter>       <name>driverclassname</name>       <value>com.mysql.jdbc.driver</value>    </parameter>        <!-- the jdbc connection url for  connecting to your mysql db.         the autoreconnect=true argument    to the url makes sure that the         mm.mysql jdbc driver will    automatically reconnect if mysqld closed the         connection.  mysqld by default    closes idle connections after 8 hours.         -->    <parameter>      <name>url</name>      <value>jdbc:mysql://localhost:3306  /javatest?autoreconnect=true</value>    </parameter>            <parameter>              <name>removeabandoned</name>              <value>true</value>            </parameter>             <parameter>              <name>removeabandonedtimeout</name>              <value>60</value>            </parameter>            <parameter>              <name>logabandoned</name>              <value>true</value>            </parameter>  </resourceparams></context>


f.在web服务中调用.配置web.xml 如:

<web-app 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/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"    version="2.4">  <description>mysql test app</description>  <resource-ref>      <description>db connection</description>      <res-ref-name>jdbc/testdb</res-ref-name>      <res-type>javax.sql.datasource</res-type>      <res-auth>container</res-auth>  </resource-ref></web-app>


g.测试用test.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql"prefix="sql" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c" %><sql:query var="rs"datasource="jdbc/testdb">select id, foo, bar from testdata</sql:query><html>  <head>    <title>db test</title>  </head>  <body>  <h2>results</h2>  <c:foreach var="row" items="${rs.rows}">    foo ${row.foo}<br/>    bar ${row.bar}<br/></c:foreach>  </body></html>


h.新建web应用

下载jakarta-taglibs-standard-1.1.0

copy jstl.jar and standard.jar to your web app's web-inf/lib

dbtest/    web-inf/        web.xml        lib/            jstl.jar            standard.jar    test.jsp


拷贝到webapps/ 下

i.启动mysql,tomcat

访问:

http://localhost:8080/dbtest/test.jsp

显示:

resultsfoo hellobar 12345


4.ssl的配置,以jdk1.4.2为例

a.进入%java_home%/bin

运行命令:keytool -genkey -alias tomcat -keyalg rsa

以tomcat 安装密码为198277,ketool设置密码为198277为例

输入keystore密码: 198277

您的名字与姓氏是什么?

[unknown]: ycg

您的组织单位名称是什么?

[unknown]: nju

您的组织名称是什么?

[unknown]: nju

您所在的城市或区域名称是什么?

[unknown]: nanjing

您所在的州或省份名称是什么?

[unknown]: jiangsu

该单位的两字母国家代码是什么

[unknown]: nd

cn=ycg, ou=nju, o=nju, l=nanjing, st=jiangsu, c=nd 正确吗?

[否]: y

输入的主密码

(如果和 keystore 密码相同,按回车): 198277

b.在你的d:/documents and settings/的当前用户目录下可以找到.keystore文件.将其拷贝到conf/文件夹下.

c.在server.xml 中找到

<!--    <connector port="8443"    maxthreads="150" minsparethreads="25"    maxsparethreads="75"   enablelookups="false"    disableuploadtimeout="true"   acceptcount="100" debug="0"   scheme="https" secure="true"   clientauth="false" sslprotocol="tls" />    -->


去掉注释

添加配置字段:keystorefile="/conf/.keystore" keystorepass="198277"

如:

<connector port="8443"  maxthreads="150" minsparethreads= "25" maxsparethreads="75"  enablelookups="false"   disableuploadtimeout="true"    acceptcount="100" debug="0"  scheme="https" secure="true"     clientauth="false" sslprotocol="tls"  keystorefile="/conf/.keystore"       keystorepass="198277"/>


d.测试为:

https://localhost:8443

e.在自己的程序中添加ssl认证方式为:

在web.xml 中添加

<security-constraint><web-resource-collection><web-resource-name>success</web-resource-name><url-pattern>/</url-pattern><http-method>get</http-method><http-method>post</http-method></web-resource-collection><user-data-constraint><transport-guarantee>confidential</transport-guarantee></user-data-constraint></security-constraint>


f.用上提为例就是

修改web.xml 为

<web-app 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/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"    version="2.4">    <description>mysql test app</description><security-constraint><web-resource-collection><web-resource-name>success</web-resource-name><url-pattern>/</url-pattern><http-method>get</http-method><http-method>post</http-method></web-resource-collection><user-data-constraint><transport-guarantee>confidential</transport-guarantee></user-data-constraint></security-constraint>    <resource-ref>      <description>db connection</description>      <res-ref-name>jdbc/testdb</res-ref-name>      <res-type>javax.sql.datasource</res-type>      <res-auth>container</res-auth>  </resource-ref></web-app>


访问:

https://localhost:8443/dbtest/test.jsp

g.如果与2配置的jdbcrealm结合起来进行表单认证

先在user_roles表中添加user_name:ycg role_name:web-user

在users表中添加user_name:ycg user_pass:198277

然后在web.xml中添加

<auth-constraint><role-name>web-user</role-name></auth-constraint><login-config> <auth-method>basic</auth-method> <realm-name>my member area</realm-name></login-config>


修改后的web.xml如:

<web-app 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/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"    version="2.4">    <description>mysql test app</description><security-constraint><web-resource-collection><web-resource-name>success</web-resource-name><url-pattern>/</url-pattern><http-method>get</http-method><http-method>post</http-method></web-resource-collection><auth-constraint><role-name>web-user</role-name></auth-constraint><user-data-constraint><transport-guarantee>confidential</transport-guarantee></user-data-constraint></security-constraint><login-config> <auth-method>basic</auth-method> <realm-name>my member area</realm-name></login-config>    <resource-ref>      <description>db connection</description>      <res-ref-name>jdbc/testdb</res-ref-name>      <res-type>javax.sql.datasource</res-type>      <res-auth>container</res-auth>  </resource-ref></web-app>


测试:

http://localhost:8080/dbtest/test.jsp

将通过ssl连接,并进行表单认证.用户密码可在user_roles,和users中添加.

5.中文乱码问题:

mysql 默认编码 iso

tomcat request 传输编码 iso

如果要显示中文

在*.jsp中添加

<head><%@ page language="java"contenttype="text/html;charset=gb18030"pageencoding="gb18030"%></head>


如果是数据传输中的乱码(如用servlet从mysql数据库读出的数据)用以下两个转码函数转码,如果不清楚由哪种编码转成哪种编码,就多尝试。

//转码gbk转iso    public string toiso(string input) {        try  {                byte[] bytes = input.getbytes("gbk");                return new string(bytes,"iso8859-1");        }catch(exception ex)   {        }        return input;    }        //转码is0转gbk    public string togbk(string input) {        try {            byte[] bytes =    input.getbytes("iso8859-1");            return new string(bytes,"gbk");        }catch(exception ex) {        }        return input;    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表