springboot創建
1.controller
@RestController
public class BaseController {
@RequestMapping(value = "/health_check")
public String healthCheck() {
return "everything is ok";
}
}
2.enum
public enum ApplyIsApprovalStateEnum {
NO(0,"no"),
YES(3,"yes");
ApplyIsApprovalStateEnum(Integer code, String name){
this.code = code;
this.name = name;
}
public Integer getCode(){
return this.code;
}
private Integer code;
private String name;
}
3.Application.java
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.sun.metadata.mapper")
@EnableTransactionManagement
@EnableScheduling
@EnableAsync
public class MetadataApplication {
public static void main(String[] args) {
SpringApplication.run(MetadataApplication.class, args);
}
}
4.application.yml
spring:
profiles:
active: @profiles.active@
# active: qa
#log:
# dir: /opt/logs/self_access
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
5.application-dev.yml
server:
port: 8080
thymeleaf:
template-loader-path: classpath:/templates
charset: UTF-8
cache: false
suffix: .html
servlet:
content-type: text/html
aop:
auto: true
spring:
datasource:
url: jdbc:mysql://100.100.1:3308/data?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
username: root
password: D
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
redis:
host : 100.100.1
port : 600
password :
timeout : 3000
mybatis:
type-aliaases-pocket: com.sun.metadata.entity
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
6.pom.xml
<build>
<finalName>metadata</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<!--重要 如果不設置resource 會導致application.yaml中的@@找不到pom文件中的配置-->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<!--重要 如果不設置resource 會導致application.yaml中的@@找不到pom文件中的配置-->
</build>
<!-- 選取不同的配置文件,dev或者pro -->
<profiles>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profiles.active>dev</profiles.active>
</properties>
</profile>
</profiles>
7.logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %contextName [%thread] %-5level %logger{36} - %L%msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
//正常運行日誌
<logger name="com.soul.metadata" additivity="true" level="DEBUG">
<appender-ref ref="console"/>
</logger>
</configuration>
8.工具類
8.1 從session中獲得信息
public static String getNickName(HttpServletRequest request){
UserEntity user = (UserEntity) request.getSession().getAttribute("session_user");
if(null != user && StringUtils.isNotBlank(user.getName())){
return user.getName();
}
return "";
}
8.2 從cookie中獲得信息
public static String getUserId(HttpServletRequest request) {
String userId = "";
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
log.info("cookie"+cookie.getName()+":value"+cookie.getValue());
if (cookie.getName().equalsIgnoreCase("userId")) {
userId = cookie.getValue();
}
}
}
return userId;
}
8.3 解決跨域問題
@Configuration
public class GlobalCorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重寫父類提供的跨域請求處理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路徑
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否發送Cookie信息
.allowCredentials(true)
//放行哪些原始域(請求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(頭部信息)
.allowedHeaders("*")
//暴露哪些頭部信息(因爲跨域訪問默認不能獲取全部頭部信息)
.exposedHeaders("Header1", "Header2");
}
};
}
}
8.4 攔截器處理
@Component
public class WebInterceptor implements HandlerInterceptor {
/**
* 預處理回調方法,實現處理器的預處理
* 返回值:true表示繼續流程;false表示流程中斷,不會繼續調用其他的攔截器或處理器
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("開始攔截.........");
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport,Sign-Auth,set-cookie,soul-request-type");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setContentType("text/html;charset=UTF-8");
String userId = "";
if (request.getMethod().equals("GET") || request.getMethod().equals("POST")) {
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equalsIgnoreCase("userId")) {
userId = cookie.getValue();
}
}
}
} else
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(200);
return true;
}
StringBuffer requestURL = request.getRequestURL();
if (requestURL.toString().contains("health_check")) {
return true;
} else if (userId.equals("")) {
response.setStatus(200);
JSONObject resoutJson = new JSONObject();
resoutJson.put("success", false);
resoutJson.put("code", 20001);
OutputStream out = response.getOutputStream();
out.write(resoutJson.toJSONString().getBytes());
return false;
} else {
return true;
}
}
}
8.5 http的url連接
public static String post(String url, String json) throws IOException {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(json, JSON); // new
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
8.6 JSON處理
jsonObject 轉字符串 jsonObject.toJSONString()
轉對象 RoleModel param = jsonObject.getObject("param",RoleModel.class);
轉數組 JSONArray jsonArray = jsonObject.getJSONArray("requestParam");