1.web application.properties
server.port= 9090
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.servlet.multipart.max-file-size=10000
spring.servlet.multipart.max-request-size=10000
spring.devtools.livereload.port=35730
2.core application.properties
server.port=9091
spring.datasource.url= jdbc:mysql://:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username= root
spring.datasource.password=
spring.jpa.show-sql= true
spring.jpa.open-in-view = false
spring.jpa.properties.hibernate.hbm2ddl.auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
interval=300000
spring.servlet.multipart.max-file-size=10000
spring.servlet.multipart.max-request-size=10000
3.WebConfigurer 跨域
package com.example.core.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Author: ChenZhiYu
* @Date: 2019/9/3 20:35
*/
@Configuration
public class CORSConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedHeaders("*").allowedOrigins("*").allowedMethods("*");
}
}
4.Student.java
package com.example.core.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "student")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Basic
@Column(name = "name")
private String name;
@Basic
@Column(name = "phone")
private String phone;
@Basic
@Column(name = "age")
private int age;
@Basic
@Column(name = "delFlag")
private int delFlag;
}
- mysql
CREATE TABLE `student` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`phone` varchar(32) DEFAULT NULL,
`age` int(4) unsigned DEFAULT NULL,
`del_flag` int(2) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=114 DEFAULT CHARSET=utf8;
6 controller
package com.example.core.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.core.common.Student;
import com.example.core.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {
// protected HttpServletRequest request;
// protected HttpServletResponse response;
// protected HttpSession session;
//
// public HttpServletRequest getRequest() {
// return request;
// }
//
// public void setRequest(HttpServletRequest request) {
// this.request = request;
// }
//
// public HttpServletResponse getResponse() {
// return response;
// }
//
// public void setResponse(HttpServletResponse response) {
// this.response = response;
// }
//
// public HttpSession getSession() {
// return session;
// }
//
// public void setSession(HttpSession session) {
// this.session = session;
// }
//
// @ModelAttribute
// public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
// this.request = request;
// this.response = response;
// this.session = request.getSession();
// response.setHeader("Access-Control-Allow-Origin", "*");
// }
private StudentService service;
@Autowired
public StudentController(StudentService service){
this.service = service;
}
@GetMapping("/query")
public List<Student> query(){
return service.getStudentList();
}
// @PostMapping("/add")
// public String add(@RequestParam Student student){ //同update
// service.updateStudent(student);
// return null;
// }
@PostMapping("remove")
public String remove(@RequestParam int id){
service.remove(id);
return null;
}
@PostMapping("delete")
public String delete(@RequestParam int id){
return null;
}
@PostMapping("update")
public String update(@RequestBody Student student){
// JSONObject json = JSONObject.parseObject(param);
// System.out.println(student);
service.updateStudent(student);
return null;
}
}
- service
package com.example.core.service;
import com.example.core.common.Student;
import com.example.core.dao.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.beans.Transient;
import java.util.List;
@Slf4j
@Service
public class StudentService {
private StudentRepository dao;
@Autowired
public StudentService(StudentRepository dao){
this.dao = dao;
}
public List<Student> getStudentList(){
return dao.findByDelFlag(0);
}
// public void addStudent(List<Student> studentList){
// dao.saveAll(studentList);
// }
@Transactional
public void remove(int id){
dao.remove(id);
}
@Transactional
public void deleteStudent(int id){
dao.deleteById(id);
}
@Transactional
public void updateStudent(Student student){
dao.save(student);
}
}
- dao
package com.example.core.dao;
import com.example.core.common.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface StudentRepository extends JpaRepository<Student, Integer> {
List<Student> findByDelFlag(int delFlag);
@Modifying
@Query("update Student s set s.delFlag = 1 where s.id = ?1 ")
void remove(int id);
}
- web controller
package com.example.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
- index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta content="always" name="referrer">
<meta name="theme-color" content="#2932e1">
<script type="text/javascript" src="/vue/vue.js"></script>
<script type="text/javascript" src="/vue/vue-resource.js"></script>
<!--<script type="text/javascript" src="/axios/axios.min.js"></script>-->
<!--<script type="text/javascript" src="/jquery/jquery-3.4.1.min.js"></script>-->
<link href="/bootstrap/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" />
<link href="/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<div id="table" v-cloak>
<div v-show="addOrUpdate==0">
<button class="btn btn-default" v-on:click="add()">新增</button>
<table class="table table-striped">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>电话</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(student,index) in studentList">
<th>
{{student.id}}
</th>
<th>
{{student.name}}
</th>
<th>
{{student.phone}}
</th>
<th>
{{student.age}}
</th>
<th class="flex">
<button v-on:click="remove(student.id)">删除</button>
<button v-on:click="update(student)">修改</button>
</th>
</tr>
</tbody>
</table>
</div>
<div v-show="addOrUpdate!=0">
<div class="flex">
<div>姓名: </div>
<input class="form-control" type="text" v-model="student.name">
</div>
<div class="flex">
<div>手机: </div>
<input class="form-control" type="text" v-model="student.phone">
</div>
<div class="flex">
<div>年龄: </div>
<input class="form-control" type="text" v-model="student.age">
</div>
<button class="btn btn-default" v-on:click="submitAddOrUpdate()">提交</button>
<button class="btn btn-default" v-on:click="back()">返回</button>
</div>
</div>
</div>
<script>
var vm = new Vue({
el:'#table',
data:{
addOrUpdate:0, // 0无操作 1 add 2 update
studentList: [],
student:{
name:'',
phone:'',
age:''
}
},
mounted:function () {
this.init();
},
methods:{
init:function () {
var that = this;
this.$http.get('http://localhost:9091/student/query').then(function(res){
this.studentList = res.body;
},function(){
});
},
add:function () {
this.student = {
name:'',
phone:'',
age:''
};
this.addOrUpdate = 1;
},
update:function (student) {
this.student = student;
this.addOrUpdate = 2;
},
submitAddOrUpdate:function () {
var that = this;
//VUE HTTP
this.$http.post('http://localhost:9091/student/update',JSON.stringify(that.student),{contentType:'application/json'}).then(function(res){
that.init();
that.back();
},function(res){
});
//JQuery Ajax HTTP
// $.ajax({
// url:'http://localhost:9091/student/update',
// data:JSON.stringify(that.student),
// type:'POST',
// dataType:'json',
// contentType: "application/json",
// success:function(data){
// that.init();
// that.back();
// },
// error:function(reason){
// }
// });
},
remove:function (id) {
var that = this;
this.$http.post('http://localhost:9091/student/remove',{'id':id},{emulateJSON:true,contentType:'application/json'}).then(function(res){
console.log(res.status);
that.init();
},function(res){
console.log(res.status);
});
},
back:function () {
this.student = {
name:'',
phone:'',
age:''
};
this.addOrUpdate = 0;
}
}
})
</script>
</body>
</html>
- parent pom
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<packaging>pom</packaging>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- core pom
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- web pom
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>web</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- RestTemplate 注册
package com.ustcinfo.sdnCloud.collectPerf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfigCore {
/*@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SslClientHttpRequestFactory factory = new SslClientHttpRequestFactory();
factory.setReadTimeout(15000);
factory.setConnectTimeout(15000);
return factory;
}
}
- ssl 注册
package com.ustcinfo.sdnCloud.collectPerf.config;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
/**
* {@link SimpleClientHttpRequestFactory} that skips SSL certificate verification.
*
* @author Madhura Bhave
*/
public class SslClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
throws IOException {
if (connection instanceof HttpsURLConnection) {
prepareHttpsConnection((HttpsURLConnection) connection);
}
super.prepareConnection(connection, httpMethod);
}
private void prepareHttpsConnection(HttpsURLConnection connection) {
connection.setHostnameVerifier(new SkipHostnameVerifier());
try {
connection.setSSLSocketFactory(createSslSocketFactory());
}
catch (Exception ex) {
// Ignore
}
}
private SSLSocketFactory createSslSocketFactory() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new SkipX509TrustManager() },
new SecureRandom());
return context.getSocketFactory();
}
private class SkipHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
private static class SkipX509TrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}
}
- redisTemplate 注册
package com.ustcinfo.sdnCloud.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
//自定义缓存key生成策略
// @Bean
// public KeyGenerator keyGenerator() {
// return new KeyGenerator(){
// @Override
// public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
// StringBuffer sb = new StringBuffer();
// sb.append(target.getClass().getName());
// sb.append(method.getName());
// for(Object obj:params){
// sb.append(obj.toString());
// }
// return sb.toString();
// }
// };
// }
//缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
// cacheManager.setDefaultExpiration(999999999999999999L);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);//设置序列化工具
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template){
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
package com.ustcinfo.sdnCloud.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfigSingel {
@Bean
public <T> RedisTemplate<String, T> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}