add servlet init

This commit is contained in:
dzj 2023-12-18 06:41:44 +08:00
parent ae178da88f
commit bbf9c50cbe
5 changed files with 315 additions and 35 deletions

39
pom.xml
View File

@ -3,23 +3,26 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>net.risesoft</groupId>
<artifactId>demo01</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>demo01</name>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version> <version>3.2.0</version>
<relativePath /> <!-- lookup parent from repository --> <relativePath /> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>net.risesoft</groupId>
<artifactId>demo01</artifactId>
<version>1.0</version>
<name>demo01</name>
<description>Demo project for Spring Boot</description>
<repositories> <repositories>
<repository> <repository>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url> <url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots> <snapshots>
<enabled>true</enabled>
</snapshots>
</repository> </repository>
<repository> <repository>
<id>spring-milestones</id> <id>spring-milestones</id>
@ -40,10 +43,10 @@
<properties> <properties>
<java.version>21</java.version> <java.version>21</java.version>
<spring-cloud.version>2023.0.0-RC1</spring-cloud.version> <spring-cloud.version>2023.0.0</spring-cloud.version>
</properties> </properties>
<!--<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
@ -53,7 +56,7 @@
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement>--> </dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
@ -64,6 +67,12 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -98,9 +107,19 @@
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId> <artifactId>spring-cloud-starter-consul-discovery</artifactId>
<version>4.0.3</version>
</dependency> </dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!--<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
</dependency>-->
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,40 @@
package net.risesoft.demo;
import jakarta.servlet.ServletContext;
import jakarta.servlet.SessionCookieConfig;
import jakarta.servlet.SessionTrackingMode;
import java.util.Collections;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.core.env.Environment;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
public class ServletInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {
@Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) {
setRegisterErrorPageFilter(false);
builder.sources(Demo01Application.class);
return builder;
}
/*@Override
protected WebApplicationContext run(SpringApplication application) {
WebApplicationContext ctx = super.run(application);
Environment env = ctx.getEnvironment();
String sessionTimeout = env.getProperty("server.servlet.session.timeout", "300");
String cookieSecure = env.getProperty("server.servlet.session.cookie.secure", "false");
ServletContext servletContext = ctx.getServletContext();
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
servletContext.setSessionTimeout(Integer.valueOf(sessionTimeout));
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setSecure(Boolean.valueOf(cookieSecure));
return ctx;
}*/
}

View File

@ -0,0 +1,14 @@
package net.risesoft.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = true)
public class Y9Config {
@Bean
public Y9Context y9Context() {
return new Y9Context();
}
}

View File

@ -0,0 +1,207 @@
package net.risesoft.demo.config;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ServletContextAware;
/**
* 获取WebApplicationContext的一条途径
*/
public class Y9Context implements ApplicationContextAware, EnvironmentAware, ServletContextAware {
private static ApplicationContext applicationContext;
private static Environment environment;
private static ServletContext servletContext;
private static String hostName;
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义则返回true
*
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static ApplicationContext getAc() {
return applicationContext;
}
/**
* 如果给定的bean名字在bean定义中有别名则返回这些别名
*
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
/**
* 获取类型为requiredType的对象
*
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = applicationContext.getBean(clz);
return result;
}
/**
* 获取对象
*
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
*
* @throws org.springframework.beans.BeansException
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T)applicationContext.getBean(name);
}
public static String getContextPath() {
return servletContext.getContextPath();
}
public static Environment getEnvironment() {
return environment;
}
public static String getHostName() {
if (Y9Context.hostName == null) {
try {
Y9Context.hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return Y9Context.hostName;
}
/**
* 获取访问者IP
*
* 在一般情况下使用Request.getRemoteAddr()即可但是经过nginx等反向代理软件后这个方法会失效
*
* 本方法先从Header中获取X-Real-IP如果不存在再从X-Forwarded-For获得第一个IP(,分割) 如果还不存在则调用Request .getRemoteAddr()
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String addr = null;
String[] ADDR_HEADER = {"X-Real-IP", "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP"};
for (String header : ADDR_HEADER) {
if (StringUtils.isEmpty(addr) || "unknown".equalsIgnoreCase(addr)) {
addr = request.getHeader(header);
} else {
break;
}
}
if (StringUtils.isEmpty(addr) || "unknown".equalsIgnoreCase(addr)) {
addr = request.getRemoteAddr();
} else {
int i = addr.indexOf(",");
if (i > 0) {
addr = addr.substring(0, i);
}
}
return addr;
}
public static String getLogoutUrl(String path) {
String logoutUrl = path + servletContext.getContextPath();
return logoutUrl;
}
public static String getProperty(String key) {
return environment.getProperty(key);
}
public static String getRealPath(String path) {
return servletContext.getRealPath(path);
}
public static ServletContext getServletContext() {
return servletContext;
}
public static ServletContext getServletContext(String uripath) {
return servletContext.getContext(uripath);
}
public static String getSystemName() {
return getProperty("systemName");
}
/**
* @param name
* @return Class 注册对象的类型
*
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
public static String getWebRootRealPath() {
return servletContext.getRealPath("/");
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype 如果与给定名字相应的bean定义没有被找到将会抛出一个异常NoSuchBeanDefinitionException
*
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
public static void publishEvent(ApplicationEvent event) {
applicationContext.publishEvent(event);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Y9Context.applicationContext = applicationContext;
}
@Override
public void setEnvironment(Environment environment) {
Y9Context.environment = environment;
}
@Override
public void setServletContext(ServletContext servletContext) {
Y9Context.servletContext = servletContext;
}
}

View File

@ -7,7 +7,7 @@ management:
exposure: exposure:
include: '*' include: '*'
server: server:
port: 7055 port: 7099
servlet: servlet:
context-path: /demo01 context-path: /demo01
encoding: encoding:
@ -33,7 +33,7 @@ spring:
compatibility-verifier: compatibility-verifier:
enabled: false enabled: false
consul: consul:
host: host.docker.internal host: localhost
port: 8500 port: 8500
discovery: discovery:
register-health-check: true register-health-check: true
@ -46,7 +46,7 @@ spring:
tags: test,y9 tags: test,y9
datasource: datasource:
driverClassName: com.mysql.cj.jdbc.Driver driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://host.docker.internal:3306/y9_public?serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&useCompression=true&useSSL=false&allowPublicKeyRetrieval=true url: jdbc:mysql://localhost:3306/y9_public?serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&useCompression=true&useSSL=false&allowPublicKeyRetrieval=true
username: root username: root
password: '12345678' password: '12345678'
hikari: hikari:
@ -68,7 +68,7 @@ spring:
allow-circular-references: false allow-circular-references: false
docker: docker:
compose: compose:
enabled: true enabled: false
file: compose-dev.yml file: compose-dev.yml
readiness: readiness:
#wait: NEVER #wait: NEVER