1. 通过InetAddress类动态获取主机的ip地址 2. 折叠 catch 块

This commit is contained in:
gaohanghang 2020-05-07 20:00:36 +08:00
parent 3316c98326
commit 06e05abd6f
2 changed files with 103 additions and 98 deletions

View File

@ -4,9 +4,12 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
/** /**
* @Description 动态获取tomcat启动端口控制台打印项目访问地址 * @Description 通过实现ApplicationListener接口动态获取tomcat启动端口和访问路径通过InetAddress类获取主机的ip地址最后控制台打印项目访问地址
* @Author Gao Hang Hang * @Author Gao Hang Hang
* @Date 2019-12-27 14:37 * @Date 2019-12-27 14:37
**/ **/
@ -14,15 +17,20 @@ import org.springframework.stereotype.Component;
@Slf4j @Slf4j
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> { public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
private int serverPort;
private String serverPath;
@Override @Override
public void onApplicationEvent(WebServerInitializedEvent event) { public void onApplicationEvent(WebServerInitializedEvent event) {
this.serverPort = event.getWebServer().getPort(); try {
InetAddress inetAddress = Inet4Address.getLocalHost();
// 主机ip地址
String hostAddress = inetAddress.getHostAddress();
// tomcat启动端口
int serverPort = event.getWebServer().getPort();
// 新增动态path by zhengkai // 新增动态path by zhengkai
this.serverPath = event.getApplicationContext().getApplicationName(); String serverPath = event.getApplicationContext().getApplicationName();
log.info("项目启动启动成功!访问地址: http://localhost:{}{}", serverPort,serverPath); log.info("项目启动启动成功!访问地址: http://{}:{}{}", hostAddress, serverPort, serverPath);
} catch (UnknownHostException e) {
e.printStackTrace();
}
} }
} }

View File

@ -77,10 +77,7 @@ public class IndexController {
Map<String, String> result = generatorService.getResultByParams(params); Map<String, String> result = generatorService.getResultByParams(params);
return new ReturnT<>(result); return new ReturnT<>(result);
} catch (IOException | TemplateException e) { } catch (IOException | TemplateException | CodeGenerateException e) {
log.error(e.getMessage(), e);
return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
} catch (CodeGenerateException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage()); return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
} }