Java Development Environment Tomcat (7.0) Data Source Configuration tutorial

Source: Internet
Author: User
Tags auth mysql in stmt create database java web mysql command line port number tomcat

A datasource (data source) object is configured under Tomcat's Java Web container. The Javx.sql.DataSource interface in JDBC is responsible for establishing a connection to the database, in which the database connection is obtained directly from the data source. The DataSource object is managed by the servlet container Tomcat, which actually obtains the database connection by selecting an idle connection from the connection pool. It is implemented based on Jndi (Java naming and directory interfaces) in Java.

One , all projects share a connection pool

1, configure the data source context.xml:

There are context.xml files in Tomcat's Conf directory, which is the configuration data source.

Content in tomcat->conf->context.xml file configuration:

<resource

Name= "Jdbc/mysql"

Auth= "Container"

Type= "Javax.sql.DataSource"

Maxactive= "20"

Maxidel= "10"

maxwait= "1000"

Username= "Root"

password= "Admin"

Driverclassname= "Com.mysql.jdbc.Driver"

Url= "Jdbc:mysql://127.0.0.1:3306/user" >

</Resource>

Add JDBC driver to Tomcat's Lib directory

2. Configure Jndi Resource reference Web.xml:
Add the following in the project's Web.xml <web-app> </web-app>:

<resource-ref>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.datasource </res-type>
<res-auth>Container</res-auth>
</resource-ref>

Use the relatively simple Jndi resource access way lookup method, as follows:

Context Sourcectx = new InitialContext ();
DataSource ds = (DataSource) sourcectx.lookup ("Java:comp/env/jdbc/mysql");
conn = Ds.getconnection ();

OK, here's the database link to get the


second, each Web project is configured independently of its own connection pool:Put the XML content into a specific project directory

1, configure the data source context.xml:
In the project directory Meta-inf, create context.xml, in fact this configuration and tomcat/conf/context.xml this file is the same, you can directly copy the context.xml file over

The contents are as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<context path= "/" >
<resource
Name= "Jdbc/mysql"
Type= "Javax.sql.DataSource"
Driverclassname= "Com.mysql.jdbc.Driver"
Maxidle= "2"
maxwait= "5000"
Username= "Root"
password= "Admin"
Url= "Jdbc:mysql://localhost:3306/user"
Maxactive= "4"/>
</Context>


And then import the JDBC driver into the Lib folder under Web-inf.

2. Configure Jndi Resource reference Web.xml:

And in the project Web.xml <web-app> </web-app> Join

<resource-ref>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>


JNDI fetch data source, Database link:

Context Initcontext = new InitialContext ();
Context Envcontext = (context) initcontext.lookup ("java:/comp/env");
DataSource ds = (DataSource) envcontext.lookup ("Jdbc/mysql");
Connection conn = Ds.getconnection ();

Element attribute Description **********************

Description of the properties of the <Resource> element:

Name: Specifies the Jndi name of the resource resource;

Auth: Optional Fill container or application, designate resource manager;

Type: Specifies the Java class name of the resource resource;

Maxactive: Sets the maximum number of active state connections in the database connection pool, and 0 is unrestricted;

Maxidle: Sets the maximum number of idle-state connections in the database connection pool, and 0 is unrestricted;

Maxwait: Sets the maximum wait time for the idle state connection in the database connection pool, the timeout throws an exception, and 1 can wait indefinitely;

Username: Specifies the user name of the database;

Password: Specifies the password to connect to the database;

Driverclassname: Specifies the driver implementation class name of the JDBC drive for the database (here is the MySQL database connection);
URL: The URL that connects to the database.

*******************************************************

The child element description of the <resource-ref> element:

Description: Description of the referenced Jndi resource;

Res-ref-name: The name of the referenced Jndi resource, consistent with the name attribute in the <Resource> element above;

Res-type: The class name of the referenced Jndi resource, consistent with the type attribute in the above <Resource> element;
Res-auth: Refers to the manager of the resource, the Auth attribute in the above <Resource> element is consistent;



a local data source configured with Tomcat 7.0 for Java environment

Configure the content of the local data source for Tomcat 7.0, for the Java EE Environment, where MySQL is used


1. Configure MySQL-driven JDBC

(1) Download MySQL JDBC driver, here is the Mysql-connector-java-5.1.17-bin.jar.

(2) Copy the jar file to the Lib directory of the Web application.

2. Download and install MySQL

MySQL is required here version of more than 5.1, I installed is mysql-essential-5.1.65-win32.msi.

Choose Custom Mode when installing, when arrive the configuration to choose GBK encoding way, username root (default), password 123456 (custom bar).

After the installation is complete, you can open the My.ini file under the MySQL installation directory to view the modifications:


For example, the port number here is 3306, the default character encoding is GBK and so on.

Then configure the path of the database in the environment variable:

%PATH%; F:\software\J2EE\MySQL\bin

You can then open the MySQL command line to view it in a variety of ways:

A: You can search for MySQL in the Start menu, and then open the MySQL Command line Client.


Enter password 123456 when open:


Method Two: Can also be in the Bin directory Mysql.exe (directly open words will flash back) to copy a shortcut to a disk such as F disk, and then open with CMD. Note Direct input Mysql.exe You must enter a username and password because no password is denied access:


And then enter

Mysql> Select Version (), current_date;

You can view version information and an ex-date.

Input

Mysql>quit

Can exit the MySQL program, of course, enter exit can directly exit the command line window.

3. Create a database and table

Can be established through the MySQL statement, can be processed through SQL batch import script, can also use the graphical interface of the MySQL management software import.

Here are two ways to do that:

Method One: Build by MySQL statement

Open Mysql.exe like 2, and enter the following command

1 Create and select a database Java EE

mysql> CREATE DATABASE java ee;

mysql> use Java EE;

2 Create a table in the Java EE database news_inf

Mysql>create Table News_inf

-> (news_id int primary key auto_increment,

-> news_title varchar (255));

3 Insert data into table News_inf

Mysql>insert into News_inf values

-> (null, ' Jimmy Lee '),

-> (null, ' is SB ');

4 View the contents of the database

mysql> use Java EE;

Mysql> show TABLES;

You can see one more table News_inf in Java EE.


If you want to delete database Java EE, you can enter

drop database Java EE;

Method Two: Direct import script

First, create an SQL file with the following code:

drop database Java EE;
Create DATABASE Java EE;
Use Java EE;

CREATE TABLE News_inf
(
news_id int primary Key auto_increment,
News_title varchar (255)
);

INSERT INTO News_inf
Values
(NULL, ' Jimmy Lee '),
(NULL, ' is SB ');

Copy the file to a convenient path, such as the F disk directory.

Then open Mysql.exe, and enter

Mysql>source F:/test.sql;

You can then see the Command Line window enter query OK information.

4. Deploying programs and configuring local data sources

(1) Deployment of programs to Tomcat, there are many ways, in (a) already said, here no longer repeat.

First look at the code for the JSP program:

<%--
Website: <a href= "Http://www.111cn.net" > Yun-Habitat Community </a>
Version 1.0
Copyright (C), 2001-2012, Yeeku. H.lee
This are protected by copyright laws.
Program Name:
Date:
--%>

<%@ page contenttype= "text/html; CHARSET=GBK "language=" java "errorpage=" "%>
<%@ page import= "javax.naming.*,java.sql.*,javax.sql.*"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<title> test Tomcat Data source </title>
<body>
<%
Initializes the context, using InitialContext to initialize the context
Context Ctx=new InitialContext ();
/*
Finds a data source through Jndi, which is java:comp/env/jdbc/dstest, divided into two parts
Java:comp/env is tomcat-fixed, and the Jndi bindings provided by Tomcat must be prefixed with this prefix
Jdbc/dstest is the name of the data source when the data source is defined
*/
DataSource ds= (DataSource) ctx.lookup ("Java:comp/env/jdbc/dstest");
Getting a database connection
Connection conn=ds.getconnection ();
Get statement
Statement stmt=conn.createstatement ();
Execute query, return Resulteset object
ResultSet rs=stmt.executequery ("SELECT * from News_inf");
while (Rs.next ())
{
Out.println (rs.getstring (1)
+ "T" + rs.getstring (2) + "<br/>");
}
%>
</body>

Here is a direct use of the example code of Mr. Li Gang, an author of the Crazy Java book. Here the local data source corresponds to the Jndi custom name of Jdbc/dstest.

(2) Modify the Web.xml file in the Web-inf directory of the current project and add the following child elements to the Web element:

Auth= "Container"

Type= "Javax.sql.DataSource"

Driverclassname= "Com.mysql.jdbc.Driver"

Url= "Jdbc:mysql://localhost:3306/javaee"

Username= "Root"

Password= "123456"

Maxactive= "5"

Maxidle= "2"

maxwait= "10000"/>

Where name specifies the Jndi name, Driverclassname is the type of the Jndi. The URL specifies its path (3306 for the MySQL program's port, Java EE for the database to be accessed), username and password to match the custom username password. Additional information The code comments above are described in detail.

The purpose is to configure a Jndi (Java Naming and directory interface for this project to be named for the Java objects that you create).

If you run it immediately, you will find the following error:

Org.apache.jasper.JasperException:javax.servlet.ServletException:javax.naming.NameNotFoundException:Name JDBC is Not bound in the context

The reason is that the jndi created does not find a declaration of the variable in Tomcat's context environment.

(3) Configure Tomcat's Context.xml

It is also necessary to add the above resource element to the context.xml in the Tomcat's Conf directory. Some information says that a new XML file should be created in the Catalina/localhost directory, which is not required.

Now restart Tomcat Startup.bat, and then open this program to see the contents of the News_inf table in the database Java EE:


This is the way to configure a local data source for Tomcat 7.0, which is limited to programs in one project, and if you need to configure a global data source, Then you have to modify Tomcat's Server.xml file, quoting the textbook: This could lead to the destruction of Tomcat systems, so you should avoid using global data sources as much as possible.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.