From bbf9c50cbe754e1e8875027c261b440db15e3180 Mon Sep 17 00:00:00 2001 From: dingzhaojun Date: Mon, 18 Dec 2023 06:41:44 +0800 Subject: [PATCH] add servlet init --- pom.xml | 81 ++++--- .../net/risesoft/demo/ServletInitializer.java | 40 ++++ .../net/risesoft/demo/config/Y9Config.java | 14 ++ .../net/risesoft/demo/config/Y9Context.java | 207 ++++++++++++++++++ src/main/resources/application.yml | 8 +- 5 files changed, 315 insertions(+), 35 deletions(-) create mode 100644 src/main/java/net/risesoft/demo/ServletInitializer.java create mode 100644 src/main/java/net/risesoft/demo/config/Y9Config.java create mode 100644 src/main/java/net/risesoft/demo/config/Y9Context.java diff --git a/pom.xml b/pom.xml index 0bd791d..6e4470a 100644 --- a/pom.xml +++ b/pom.xml @@ -3,47 +3,50 @@ 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"> 4.0.0 + net.risesoft + demo01 + war + 1.0 + demo01 + org.springframework.boot spring-boot-starter-parent 3.2.0 - net.risesoft - demo01 - 1.0 - demo01 - Demo project for Spring Boot - - - - spring-snapshots - https://repo.spring.io/snapshot - true - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-snapshots - https://repo.spring.io/snapshot - - - spring-milestones - https://repo.spring.io/milestone - - + + + spring-snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + https://repo.spring.io/milestone + + + + + + spring-snapshots + https://repo.spring.io/snapshot + + + spring-milestones + https://repo.spring.io/milestone + + 21 - 2023.0.0-RC1 + 2023.0.0 - + @@ -64,6 +67,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + @@ -98,9 +107,19 @@ org.springframework.cloud spring-cloud-starter-consul-discovery - 4.0.3 + + jakarta.servlet + jakarta.servlet-api + provided + + + + diff --git a/src/main/java/net/risesoft/demo/ServletInitializer.java b/src/main/java/net/risesoft/demo/ServletInitializer.java new file mode 100644 index 0000000..df35a80 --- /dev/null +++ b/src/main/java/net/risesoft/demo/ServletInitializer.java @@ -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; + }*/ +} \ No newline at end of file diff --git a/src/main/java/net/risesoft/demo/config/Y9Config.java b/src/main/java/net/risesoft/demo/config/Y9Config.java new file mode 100644 index 0000000..9f7db95 --- /dev/null +++ b/src/main/java/net/risesoft/demo/config/Y9Config.java @@ -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(); + } + +} diff --git a/src/main/java/net/risesoft/demo/config/Y9Context.java b/src/main/java/net/risesoft/demo/config/Y9Context.java new file mode 100644 index 0000000..e3daaca --- /dev/null +++ b/src/main/java/net/risesoft/demo/config/Y9Context.java @@ -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 getBean(Class 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 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; + } + +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 5d96e45..fac6c86 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -7,7 +7,7 @@ management: exposure: include: '*' server: - port: 7055 + port: 7099 servlet: context-path: /demo01 encoding: @@ -33,7 +33,7 @@ spring: compatibility-verifier: enabled: false consul: - host: host.docker.internal + host: localhost port: 8500 discovery: register-health-check: true @@ -46,7 +46,7 @@ spring: tags: test,y9 datasource: 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 password: '12345678' hikari: @@ -68,7 +68,7 @@ spring: allow-circular-references: false docker: compose: - enabled: true + enabled: false file: compose-dev.yml readiness: #wait: NEVER