• Springboot use tomcat JNDI


    Springboot use tomcat JNDI

    [use database pool :  dbcp Druid bonecp C3P0 proxool]

    [1]apache-tomcat-9.0.0.M9confcontext.xml

    <Context>

    <!-- Default set of monitored resources. If one of these changes, the -->
    <!-- web application will be reloaded. -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
    <!-- dbcp
    <Resource name="jdbc/pg"
    auth="Container"
    factory="org.apache.commons.dbcp.dbcp2.BasicDataSourceFactory"
    type="javax.sql.DataSource"
    username="postgres"
    password="admin"
    url="jdbc:postgresql://localhost/ABC"
    driverClassName="org.postgresql.Driver"
    initialSize="20"
    maxWaitMillis="15000"
    maxTotal="75"
    maxIdle="20"
    maxAge="7200000"
    testOnBorrow="true"
    validationQuery="select 1"
    />
    -->

    <!-- Druid put druid-1.1.10.jar to tomcat lib dir
    <Resource name="jdbc/pg"
    auth="Container"
    factory="com.alibaba.druid.pool.DruidDataSourceFactory"
    type="javax.sql.DataSource"
    username="postgres"
    password="admin"
    url="jdbc:postgresql://localhost/ABC"
    driverClassName="org.postgresql.Driver"
    maxActive="50"
    maxWait="10000"
    removeabandoned="true"
    removeabandonedtimeout="60"
    logabandoned="false"
    filters="stat"
    />
    -->

    <!--bonecp put
    guava-25.1-jre.jar slf4j-api-1.7.25.jar bonecp-0.8.0.RELEASE.jar
    to tomcat lib dir

    <Resource
    name="jdbc/pg"
    auth="Container"
    type="com.jolbox.bonecp.BoneCPDataSource"
    factory="org.apache.naming.factory.BeanFactory"
    driverClass="org.postgresql.Driver"
    username="postgres"
    password="admin"
    jdbcUrl="jdbc:postgresql://localhost/ABC"
    idleConnectionTestPeriod="0"
    idleMaxAge="10"
    partitionCount="1"
    maxConnectionsPerPartition="5"
    minConnectionsPerPartition="1"
    connectionTestStatement=""
    initSQL="select 1"
    />
    -->
    <!-- C3P0 put c3p0.jar -java.jar to tomcat lib dir

    <Resource name="jdbc/pg"
    auth="Container"
    factory="org.apache.naming.factory.BeanFactory"
    type="com.mchange.v2.c3p0.ComboPooledDataSource"
    driverClass="org.postgresql.Driver"
    jdbcUrl="jdbc:postgresql://localhost/ABC"
    user="postgres"
    password="admin"/>
    -->

    <!-- proxool put com.springsource.org.logicalcobwebs.proxool-0.9.1.jar、proxool-cglib.jar、commons-logging-xxx.jar to tomcat lib dir -->

    <Resource name="jdbc/pg"
    auth="Container"
    type="javax.sql.DataSource"
    factory="org.logicalcobwebs.proxool.ProxoolDataSource"
    proxool.alias="test"
    user="postgres"
    password="admin"
    delegateProperties="foo=1,bar=true"
    proxool.jndi-name="postgrejndi"
    proxool.driver-url="jdbc:postgresql://localhost/ABC"
    proxool.driver-class="org.postgresql.Driver"
    proxool.house-keeping-sleep-time="900000"
    proxool.maximum-active-time="5"
    proxool.prototype-count="3"
    proxool.statistics="1m,15m,1d"
    proxool.simultaneous-build-throttle="10"
    proxool.minimum-connection-count="5"
    proxool.maximum-connection-count="15"
    />

    </Context>

    [2] springboot 建立Application.java

    package demo;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.context.web.SpringBootServletInitializer;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @Configuration
    @ComponentScan
    @EnableAutoConfiguration
    public class Application extends SpringBootServletInitializer {
        private static Class<Application> applicationClass = Application.class;
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(applicationClass);
        }
        public static void main(String[] args) {
            SpringApplication.run(applicationClass, args);
        }
    }
    
    @RestController
    class GreetingController {
    
        @RequestMapping("/hello/{name}")
        String hello(@PathVariable String name) {
            
            StringBuffer sb=new StringBuffer();
            Connection c=GreetingController.getConnection();
            String sqlr="select * from company";
            PreparedStatement ps=null;
             
            try {
                ps = c.prepareStatement(sqlr);
                ResultSet rs= ps.executeQuery();
                sb.append("<table style='border-1px;border-color:#666666;color:#f4f4f4'>");
                
                while(rs.next()){
                    System.out.println(rs.getString(1)+"~~~~"+rs.getString(2)+"~~~~"+rs.getString(3)+"~~~~"+rs.getString(4)+"~~~~"+rs.getString(5));
                    sb.append("<tr>")    
                    
                    .append("<td>").append(rs.getString(1))
                    .append("</td>")
                    .append("<td>").append(rs.getString(2))
                    .append("</td>")
                    .append("<td>").append(rs.getString(3))
                    .append("</td>")
                    .append("<td>").append(rs.getString(4))
                    .append("</td>")
                    .append("<td>").append(rs.getString(5))
                    .append("</td>")
                    
                    .append("</tr>");
                }
                sb.append("</table>");
                
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                try {
                    ps.close();
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return "Hello, " + name + "!"+"<br>"+sb.toString();
        }
        
        public static Connection getConnection(){
            Connection conn = null;
            Context initCtx = null;
            try {
                initCtx = (Context) new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                DataSource ds = (DataSource)envCtx.lookup("jdbc/pg");
                conn=ds.getConnection();
                System.out.println("获取数据库连接成功!");
            } catch (NamingException e) {
                System.out.println("命名空间连接失败!");
                e.printStackTrace();
            }catch (SQLException e){
                System.out.println("SQL异常!");
                e.printStackTrace();
            }
            return conn;
        }
    } 

    [3]pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">
        
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>spring-boot-web-thymeleaf</artifactId>
        <packaging>war</packaging>
        <name>Spring Boot Web Thymeleaf Example</name>
        <description>Spring Boot Web Thymeleaf Example</description>
        <url>https://www.mkyong.com</url>
        <version>1.0</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.2.RELEASE</version>
        </parent>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
        
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            
     
            <!-- hot swapping, disable cache for template, enable live reload -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
    
            <!-- Optional, for bootstrap -->
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>3.3.7</version>
            </dependency>
            
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
           
            <dependency>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-legacy</artifactId>
                <version>1.1.0.RELEASE</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <!-- Package as an executable jar/war -->
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

     [4] mark error

    javax.naming.NamingException: Could not load resource factory class [Root exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]

    The name of the default factory changed between Tomcat 7 and Tomcat 8. A couple of attribute names also changed.
    Please switching from DBCP 1.x to DBCP 2.x in Tomcat 8.
    factory="org.apache.tomcat.dbcp.BasicDataSourceFactory" Tomcat7 OR early
    factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" ------>Tomcat8 OR 9

     

  • 相关阅读:
    C#替换双引号
    Oracle 12c创建用户时出现“ORA-65096: invalid common user or role name”的错误
    Oracle 12c中文乱码,修改字符集的方法
    ORACLE 12C PDB 维护基础介绍
    spilt用法简介
    Log4net简介
    Log4net创建日志及简单扩展
    [转]ASP.NET MVC 入门11、使用AJAX
    对象池简单实现
    Android webview “location.replace” 不起作用
  • 原文地址:https://www.cnblogs.com/rojas/p/9340885.html
Copyright © 2020-2023  润新知