spring与jndi(数据库连接)SpringBoot打war包并整合jsp
spring与jndi(数据库连接)SpringBoot打war包并整合jsp,这里的jndi指的是jdbc连接,不是其他的。有传统servlet+spring和springboot的jndi连接操作,并整合jsp和thymeleaf。下面我以他们两个为例子演示。
一、servlet+spring下的jndi
一个普通servlet项目整合spring 5.14
后,在运行的tomcat/conf/context.xml的Context
标签里配置jndi:
<Resource name="localhostJndiName"
validationQuery="select 1"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url=" jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT"
username="root"
password="123456" maxActive="60" maxIdle="1"/>
注入xml中配置jndi的bean
<bean id="jndiObjectFactoryBean" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<!-- Weblogic数据源配置格式
<value>jndi_name</value> -->
<!-- Tomcat数据源配置格式 -->
<value>java:comp/env/localhostJndiName</value>
</property>
</bean>
获取DataSource进行数据操作
@Configuration
@Controller
public class WebController {
@Autowired
private JndiObjectFactoryBean jndiObjectFactoryBean;
@Bean
public DataSource dataSource() {
return (DataSource) jndiObjectFactoryBean.getObject();
}
@GetMapping(value = {"/index", ""})
public String index() {
try {
Connection connection = dataSource().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from opr_cluster limit 1");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(
resultSet.getString(1) + " " +
// resultSet.getString(2) + " " +
resultSet.getString(3) + " " +
resultSet.getString(4) + " " +
resultSet.getString(5) + " " +
resultSet.getString(6)
);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return "index";
}
}
效果:
可进一步对DataSource注入mybatis、hibernate等框架进行SQL操作!
二、在springboot中进行jndi操作
是不是有点奇怪?不奇怪,我就遇到甲方要求springboot打包war进行部署,数据源要求使用jndi。爸爸最大,我们得搞出来呢。
首先创建一个普通的springboot项目,重写springboot servlet的初始化SpringBootServletInitializer
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
}
修改pom.xml,主要是把打包改为war,插件设置无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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.lingkang</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>top.lingkang.demo.DemoApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>springboot-jndi</warName>
<!-- 不外部打包 web.xml -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
编写一个controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* @author lingkang
* Created by 2021/12/20
*/
@Configuration
@RestController
public class WebController {
@Bean
public JndiObjectFactoryBean jndiObjectFactoryBean() {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
// tomcat一定要配置这个数据源
bean.setJndiName("java:comp/env/localhostJndiName");
return bean;
}
@Autowired
private JndiObjectFactoryBean jndiObjectFactoryBean;
@Bean
public DataSource dataSource() {
return (DataSource) jndiObjectFactoryBean.getObject();
}
@Autowired
private DataSource dataSource;
@GetMapping()
public Object index() {
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from opr_cluster limit 1");
ResultSet resultSet = preparedStatement.executeQuery();
String result = "empty";
while (resultSet.next()) {
result = String.format("%s--%s--%s--%s",
resultSet.getString(1),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getString(5)
);
System.out.println(result);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
然后选择配置了jndi数据源的tomcat来运行它,数据库配置参考第一节的配置内容。
效果:
mvn package
能够正常打war包,并且丢war能正常运行。
2.1 添加jsp测试
我们添加jsp测试会如何:
先添加jsp需要的依赖
<!--用于jsp页面 jstl表达式-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--用于编译jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
application.properties
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
改造控制类
// 将类注解改为@Controller
@Configuration
@Controller
public class WebController {
// ...
@Autowired
private HttpServletRequest request;
@GetMapping()
public Object index() {
String result = "empty";
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from opr_cluster limit 1");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
result = String.format("%s--%s--%s--%s",
resultSet.getString(1),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getString(5)
);
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("result",result);
return "index";
}
webapps/WEB-INF/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>lingkang</title>
</head>
<body>
查询结果:<br>
<%
out.println(request.getAttribute("result"));
%>
</body>
</html>
设置一下jsp解析路径,否则找不到解析的template
运行它,效果如下:
2.2 使用thymeleaf
基于2.1,将依赖改为
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.properties
# 应用名称
spring.application.name=demo
# 应用服务 WEB 访问端口
server.port=8080
spring.thymeleaf.prefix=classpath:/templates/
添加resources/templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
查询结果:[[${result}]]
</body>
</html>
tomcat运行项目查看
至此,spring常见整合完毕,特别是整合jsp,jsp挺经典的emm,可以在jsp里写java代码666,觉得不错就点个赞吧!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!