Springboot use tomcat JNDI

Springboot use tomcat JNDI

[1]apache-tomcat-9.0.0.M9\conf\context.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="" />
    -->
    
    <Resource name="jdbc/pg"
              auth="Container"
              factory="org.apache.commons.dbcp.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"    
    />

</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-width: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>

猜你喜欢

转载自www.cnblogs.com/rojas/p/9340885.html
今日推荐