├── README.md ├── .gitignore ├── src ├── test │ └── java │ │ └── com │ │ └── supervons │ │ └── cpj │ │ └── CpjApplicationTests.java └── main │ ├── java │ └── com │ │ └── supervons │ │ └── cpj │ │ ├── mapper │ │ └── UserMapper.java │ │ ├── repository │ │ ├── LoggerInfosRepository.java │ │ ├── UserInfoRepository.java │ │ └── NewsInfoRepository.java │ │ ├── service │ │ └── UserService.java │ │ ├── CpjApplication.java │ │ ├── entity │ │ ├── User.java │ │ ├── NewsInfo.java │ │ ├── APIResponse.java │ │ └── LoggerInfos.java │ │ ├── serviceimpl │ │ └── UserServiceImpl.java │ │ ├── config │ │ └── SwaggerConfiguration.java │ │ ├── tools │ │ └── DateUtils.java │ │ ├── DruidConfiguration.java │ │ ├── controller │ │ ├── NewsInfoController.java │ │ └── UserController.java │ │ ├── srcurity │ │ └── JWTUtil.java │ │ ├── Interceptor │ │ └── SessionInterceptor.java │ │ └── CommonConfiguration.java │ └── resources │ ├── application.yml │ ├── application.properties │ ├── mapper │ └── UserMapper.xml │ └── commonProjectManage.sql └── pom.xml /README.md: -------------------------------------------------------------------------------- 1 | #### 这是 commonProject app 的后端,app前端地址:https://github.com/supervons/commonProject 2 | #### This is the backend of the commonProject app, the app front end address: https://github.com/supervons/commonProject 3 | ## 已有功能: 4 | #### 1,Druid数据源监控 5 | #### 2,返回 JSON 类型改为 FastJson 6 | #### 3,添加拦截器 7 | #### 4,整合 Mybatis 8 | #### 5,整合 JPA 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /src/test/java/com/supervons/cpj/CpjApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class CpjApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.mapper; 2 | 3 | import com.supervons.cpj.entity.User; 4 | import org.apache.ibatis.annotations.Mapper; 5 | 6 | import java.util.List; 7 | 8 | @Mapper 9 | public interface UserMapper { 10 | List queryList(); 11 | 12 | User queryUserById(String loginId, String passWord); 13 | 14 | User queryUserExistById(String loginId); 15 | 16 | public int addUser(User user); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/repository/LoggerInfosRepository.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.repository; 2 | 3 | import com.supervons.cpj.entity.LoggerInfos; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.io.Serializable; 9 | 10 | /** 11 | * 基于 JPA 操作的 LoggerInfosRepository 12 | * LoggerInfosRepository based on JPA operations 13 | */ 14 | @Repository 15 | public interface LoggerInfosRepository extends JpaRepository, JpaSpecificationExecutor, Serializable { 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.service; 2 | 3 | import com.supervons.cpj.entity.User; 4 | import com.supervons.cpj.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.List; 11 | 12 | @Service 13 | public interface UserService { 14 | 15 | public List queryUserList(); 16 | 17 | public User queryUserById(String loginId,String passWord); 18 | 19 | 20 | public User queryUserExistById(String loginId); 21 | 22 | public int addUser(User user); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/repository/UserInfoRepository.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.repository; 2 | 3 | import java.io.Serializable; 4 | import java.util.List; 5 | 6 | import com.supervons.cpj.entity.User; 7 | import org.springframework.data.jpa.repository.JpaRepository; 8 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 9 | import org.springframework.data.jpa.repository.Query; 10 | import org.springframework.data.repository.query.Param; 11 | import org.springframework.stereotype.Repository; 12 | 13 | /** 14 | * 基于 JPA 操作的 UserInfoRepository 15 | * UserInfoRepository based on JPA operations 16 | */ 17 | @Repository 18 | public interface UserInfoRepository extends JpaRepository, JpaSpecificationExecutor, Serializable { 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/CpjApplication.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 7 | 8 | @SpringBootApplication 9 | public class CpjApplication extends SpringBootServletInitializer { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(CpjApplication.class, args); 13 | } 14 | 15 | // 为了打包springboot项目 16 | @Override 17 | protected SpringApplicationBuilder configure( 18 | SpringApplicationBuilder builder) { 19 | return builder.sources(this.getClass()); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.io.Serializable; 7 | 8 | @Entity 9 | @Data 10 | @Table(name = "user_info") 11 | public class User implements Serializable { 12 | 13 | @Id 14 | @GeneratedValue 15 | @Column(name = "id") 16 | private String id; 17 | 18 | @Column(name = "login_id") 19 | private String loginId; 20 | 21 | @Column(name = "pass_word") 22 | private String passWord; 23 | 24 | @Column(name = "user_name") 25 | private String userName; 26 | 27 | @Column(name = "user_sex") 28 | private String userSex; 29 | 30 | @Column(name = "user_address") 31 | private String userAddress; 32 | 33 | @Column(name = "user_cellphone") 34 | private String userCellPhone; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/repository/NewsInfoRepository.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.repository; 2 | 3 | import com.supervons.cpj.entity.NewsInfo; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.io.Serializable; 10 | import java.util.List; 11 | 12 | /** 13 | * 基于 JPA 操作的 NewsInfoRepository 14 | * NewsInfoRepository based on JPA operations 15 | */ 16 | @Repository 17 | public interface NewsInfoRepository extends JpaRepository, JpaSpecificationExecutor, Serializable { 18 | @Query(value ="select * from news_info c " 19 | + "order by c.news_time desc limit ?1,?2 ",nativeQuery = true) 20 | List findAllList(Integer pageNumber, Integer pageSize); 21 | 22 | @Query(value ="select count(*) from news_info c " 23 | + "order by c.news_time desc ",nativeQuery = true) 24 | Integer countAllList(); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/entity/NewsInfo.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.entity; 2 | 3 | import lombok.Data; 4 | import org.hibernate.annotations.GenericGenerator; 5 | 6 | import javax.persistence.*; 7 | import java.io.Serializable; 8 | 9 | @Entity 10 | @Data 11 | @Table(name = "news_info") 12 | @GenericGenerator(name = "uuid", strategy = "uuid") 13 | public class NewsInfo implements Serializable { 14 | 15 | @Id 16 | @GeneratedValue(generator = "uuid") 17 | @Column(name = "news_id") 18 | private String newsId; 19 | 20 | @Column(name = "news_title") 21 | private String newsTitle; 22 | 23 | @Column(name = "news_introduction") 24 | private String newsIntroduction; 25 | 26 | @Column(name = "news_favorite_id") 27 | private String newsFavoriteId; 28 | 29 | @Column(name = "news_comments_id") 30 | private String newsCommentsId; 31 | 32 | @Column(name = "news_time") 33 | private String newsTime; 34 | 35 | @Column(name = "news_title_image") 36 | private String newsTitleImage; 37 | 38 | @Column(name = "news_content_image") 39 | private String newsContentImage; 40 | 41 | @Column(name = "news_content") 42 | private String newsContent; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/entity/APIResponse.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.entity; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Map; 6 | 7 | @Data 8 | public class APIResponse { 9 | 10 | private static final String CODE_SUCCESS = "success"; 11 | 12 | private static final String CODE_FAIL = "fail"; 13 | 14 | private String code; 15 | private T data; 16 | private String msg; 17 | private Map auxiliaryData; 18 | 19 | public APIResponse(){ 20 | 21 | } 22 | 23 | public APIResponse(String code){ 24 | this.code = code; 25 | } 26 | 27 | public APIResponse(String code, T data){ 28 | this.code = code; 29 | this.data = data; 30 | } 31 | 32 | public APIResponse(String code, String msg){ 33 | this.code = code; 34 | this.msg = msg; 35 | } 36 | 37 | public static APIResponse success(){ 38 | return new APIResponse(CODE_SUCCESS); 39 | } 40 | 41 | public static APIResponse success(Object data){ 42 | return new APIResponse(CODE_SUCCESS, data); 43 | } 44 | 45 | public static APIResponse fail(String msg){ 46 | return new APIResponse(CODE_FAIL, msg); 47 | } 48 | 49 | public static APIResponse widthCode(String errorCode) { 50 | return new APIResponse(errorCode); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/serviceimpl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.serviceimpl; 2 | 3 | import com.supervons.cpj.entity.User; 4 | import com.supervons.cpj.mapper.UserMapper; 5 | import com.supervons.cpj.service.UserService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.List; 11 | import java.util.UUID; 12 | 13 | @Service 14 | public class UserServiceImpl implements UserService { 15 | 16 | @Resource 17 | private UserMapper userMapper; 18 | 19 | @Override 20 | public List queryUserList() { 21 | List queryList = userMapper.queryList(); 22 | return queryList; 23 | } 24 | 25 | @Override 26 | public User queryUserById(String username,String password) { 27 | User queryUser = userMapper.queryUserById(username,password); 28 | return queryUser; 29 | } 30 | 31 | @Override 32 | public User queryUserExistById(String username) { 33 | User queryUser = userMapper.queryUserExistById(username); 34 | return queryUser; 35 | } 36 | 37 | @Override 38 | public int addUser(User user){ 39 | user.setId(UUID.randomUUID().toString().replace("-","")); 40 | int result = userMapper.addUser(user); 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/entity/LoggerInfos.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.entity; 2 | 3 | import lombok.Data; 4 | import org.hibernate.annotations.GenericGenerator; 5 | 6 | import javax.persistence.*; 7 | import java.io.Serializable; 8 | import java.util.Date; 9 | 10 | @Entity 11 | @Data 12 | @Table(name = "logger_infos") 13 | @GenericGenerator(name = "uuid", strategy = "uuid") 14 | public class LoggerInfos{ 15 | 16 | @Id 17 | @GeneratedValue(generator = "uuid") 18 | @Column(name = "logger_id") 19 | private String loggerId; 20 | 21 | @Column(name = "logger_client_ip") 22 | private String loggerClientIp; 23 | 24 | @Column(name = "logger_uri") 25 | private String loggerUri; 26 | 27 | @Column(name = "logger_type") 28 | private String loggerType; 29 | 30 | @Column(name = "logger_method") 31 | private String loggerMethod; 32 | 33 | @Column(name = "logger_param_date") 34 | private String loggerParamDate; 35 | 36 | @Column(name = "logger_session_ud") 37 | private String loggerSessionUd; 38 | 39 | @Column(name = "logger_time") 40 | private java.util.Date loggerTime; 41 | 42 | @Column(name = "logger_return_time") 43 | private String loggerReturnTime; 44 | 45 | @Column(name = "logger_return_data") 46 | private String loggerReturnData; 47 | 48 | @Column(name = "logger_http_status_code") 49 | private String loggerHttpStatusCode; 50 | 51 | @Column(name = "logger_time_consuming") 52 | private Long loggerTimeConsuming; 53 | 54 | } 55 | 56 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | spring: 3 | datasource: 4 | type: com.alibaba.druid.pool.DruidDataSource 5 | druid: 6 | driver-class-name: com.mysql.cj.jdbc.Driver 7 | url: jdbc:mysql://xx.xx.xx.xx:3306/commonProject?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai 8 | username: xxxxxx 9 | password: xxxxxx 10 | #最大活跃数 11 | maxActive: 20 12 | #初始化数量 13 | initialSize: 1 14 | #最大连接等待超时时间 15 | maxWait: 60000 16 | #打开PSCache,并且指定每个连接PSCache的大小 17 | poolPreparedStatements: true 18 | maxPoolPreparedStatementPerConnectionSize: 20 19 | #通过connectionProperties属性来打开mergeSql功能;慢SQL记录 20 | #connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 21 | minIdle: 1 22 | timeBetweenEvictionRunsMillis: 60000 23 | minEvictableIdleTimeMillis: 300000 24 | validationQuery: select 1 from dual 25 | testWhileIdle: true 26 | testOnBorrow: false 27 | testOnReturn: false 28 | #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙 29 | filters: stat, wall, log4j2 30 | jpa: 31 | properties: 32 | hibernate: 33 | show_sql: true 34 | format_sql: true 35 | mvc: 36 | servlet: 37 | path: /commonProject 38 | jackson: 39 | time-zone: GMT+8 40 | serialization: 41 | write-dates-as-timestamps: true 42 | mybatis: 43 | mapper-locations: classpath*:mapper/**Mapper.xml 44 | type-aliases-package: com.supervons.cpj.entity 45 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | ##服务端口 2 | ##server.port=8080 3 | #server.servlet.context-path=/commonProject 4 | # 5 | ##mysql数据连接 6 | #spring.datasource.url=jdbc:mysql://yourmysqldatabase:3306/commonProject?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC 7 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 8 | #spring.datasource.username=databaseusername 9 | #spring.datasource.password=databasepassword 10 | #spring.datasource.max-active=20 11 | #spring.datasource.max-idle=8 12 | #spring.datasource.min-idle=8 13 | ##初始化数量 14 | #spring.datasource.initial-size=1 15 | ##最大连接等待超时时间 16 | #spring.datasource.tomcat.max-wait=60000 17 | #spring.datasource.dbcp2.pool-prepared-statements=true 18 | #spring.datasource.max-pool-prepared-statement-perconnection-size=20 19 | #spring.datasource.dbcp2.time-between-eviction-runs-millis=60000 20 | #spring.datasource.dbcp2.min-evictable-idle-time-millis=300000 21 | #spring.datasource.dbcp2.validation-query=select 1 from dual 22 | #spring.datasource.dbcp2.test-while-idle=true 23 | #spring.datasource.dbcp2.test-on-borrow=false 24 | #spring.datasource.dbcp2.test-on-return=false 25 | #spring.datasource.filters=stat, wall, log4j 26 | ##mybatis 配置 27 | ## 配置映射文件加载 28 | #mybatis.mapper-locations=classpath*:mapper/**Mapper.xml 29 | #mybatis.type-aliases-package=com.supervons.cpj.entity 30 | ## 实体类通过别名使用 31 | ##mybatis.type-aliases-package=com.example.springboot.mybatis.entity 32 | # 33 | #spring.jpa.database=MySQL 34 | #spring.jpa.show-sql=true 35 | #spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl 36 | #spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/config/SwaggerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.service.Contact; 11 | import springfox.documentation.spi.DocumentationType; 12 | import springfox.documentation.spring.web.plugins.Docket; 13 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 14 | 15 | /** 16 | * swagger 配置类 17 | * Created by supervons on 2019/08/09. 18 | */ 19 | @Configuration 20 | @EnableSwagger2 21 | public class SwaggerConfiguration extends WebMvcConfigurationSupport{ 22 | @Bean 23 | public Docket createRestApi() { 24 | return new Docket(DocumentationType.SWAGGER_2) 25 | .apiInfo(apiInfo()) 26 | .select() 27 | // 为当前包路径 28 | .apis(RequestHandlerSelectors.basePackage("com.supervons.cpj.controller")) 29 | .paths(PathSelectors.any()) 30 | .build(); 31 | } 32 | 33 | //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | // 页面标题 37 | .title("CommonProject API接口") 38 | // 创建人 39 | .contact(new Contact("supervons", "https://github.com/supervons/commonProject", "supervons@sina.com")) 40 | // 版本号 41 | .version("1.0") 42 | // 描述 43 | .description("暂无描述") 44 | .build(); 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/tools/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.tools; 2 | 3 | import org.apache.commons.net.ntp.NTPUDPClient; 4 | import org.apache.commons.net.ntp.TimeInfo; 5 | 6 | import java.io.IOException; 7 | import java.net.InetAddress; 8 | import java.net.SocketException; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | 12 | /** 13 | * 日期工具类 14 | */ 15 | public class DateUtils { 16 | 17 | //设置NET服务器时间地址,这里是阿里云的服务器. 18 | public static String ServerIP = "120.25.115.20"; 19 | 20 | //获取服务器的标准北京时间 21 | public static Date getStandardTime() throws IOException { 22 | 23 | NTPUDPClient client = new NTPUDPClient(); 24 | //响应延迟时间 25 | client.setDefaultTimeout(10000); 26 | try { 27 | client.open(); 28 | InetAddress hostAddr = InetAddress.getByName(ServerIP); 29 | TimeInfo info = client.getTime(hostAddr); 30 | Date date = new java.util.Date(info.getReturnTime()); 31 | return date; 32 | // processResponse(info); 33 | } catch (SocketException e) { 34 | e.printStackTrace(); 35 | } 36 | client.close(); 37 | return null; 38 | } 39 | 40 | public static void main(String[] args) throws IOException { 41 | System.out.println(DateUtils.getStandardTime()); 42 | System.out.println(DateUtils.getFormatDate()); 43 | } 44 | 45 | private DateUtils(){} 46 | 47 | private static DateUtils dateUtils = new DateUtils(); 48 | 49 | public static DateUtils getInstance(){ 50 | return dateUtils; 51 | } 52 | 53 | public static String getFormatDate() throws IOException { 54 | //yyyy-MM-dd HH:mm:ss 大小写错误可能会导致日期转换错误 MM是月份,mm是分 55 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 56 | return sdf.format(DateUtils.getStandardTime()); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/DruidConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | import com.alibaba.druid.support.http.WebStatFilter; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 7 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | 12 | @Configuration 13 | public class DruidConfiguration implements WebMvcConfigurer { 14 | 15 | @Bean 16 | public ServletRegistrationBean statViewServlet(){ 17 | //创建servlet注册实体 18 | ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); 19 | //设置ip白名单 20 | servletRegistrationBean.addInitParameter("allow","127.0.0.1"); 21 | //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow 22 | servletRegistrationBean.addInitParameter("deny","192.168.7.13"); 23 | //设置控制台管理用户 24 | servletRegistrationBean.addInitParameter("loginUsername","druid"); 25 | servletRegistrationBean.addInitParameter("loginPassword","123456"); 26 | //是否可以重置数据 27 | servletRegistrationBean.addInitParameter("resetEnable","false"); 28 | return servletRegistrationBean; 29 | } 30 | 31 | @Bean 32 | @ConditionalOnMissingBean 33 | public FilterRegistrationBean filterRegistrationFilter(){ 34 | //创建过滤器 35 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); 36 | //设置过滤器过滤路径 37 | filterRegistrationBean.addUrlPatterns("/*"); 38 | //忽略过滤的形式 39 | filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 40 | return filterRegistrationBean; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/controller/NewsInfoController.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.controller; 2 | 3 | import com.supervons.cpj.entity.APIResponse; 4 | import com.supervons.cpj.entity.NewsInfo; 5 | import com.supervons.cpj.repository.NewsInfoRepository; 6 | import io.swagger.annotations.Api; 7 | import io.swagger.annotations.ApiOperation; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | /** 19 | * 新闻相关 controller 20 | */ 21 | @RestController 22 | @RequestMapping("/news") 23 | @Api(description = "新闻信息等相关接口") 24 | public class NewsInfoController { 25 | 26 | @Autowired 27 | private NewsInfoRepository newsInfoRepository; 28 | @ApiOperation(value = "获取新闻列表", notes="获取新闻列表,支持动态步长与分页") 29 | @RequestMapping(value = "/queryNewsInfo", method = RequestMethod.POST) 30 | public APIResponse> queryNewsInfo(@RequestBody HashMap map) { 31 | //初始页码和步长 32 | int pageNumber = Integer.parseInt(map.get("pageNo")); 33 | int pageSize = Integer.parseInt(map.get("itemNo")); 34 | int startPageNum = pageNumber * pageSize; 35 | //根据页码分页查询,前端得到数据追加 36 | List newsList = newsInfoRepository.findAllList(startPageNum,pageSize); 37 | Integer countNum=newsInfoRepository.countAllList(); 38 | Map countMap = new HashMap(); 39 | countMap.put("countNum",countNum); 40 | APIResponse apiResponse = null; 41 | if(newsList!=null){ 42 | apiResponse = APIResponse.success(); 43 | apiResponse.setData(newsList); 44 | apiResponse.setAuxiliaryData(countMap); 45 | } 46 | return apiResponse; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 24 | 25 | 26 | 29 | 30 | 31 | 34 | 35 | 36 | INSERT INTO user_info(id,login_id,pass_word,user_name,user_sex,user_address,user_cellphone) 37 | VALUES(#{id}, #{loginId}, #{passWord}, #{userName}, #{userSex}, #{userAddress}, #{userCellPhone}) 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/srcurity/JWTUtil.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.srcurity; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.interfaces.Claim; 7 | import com.auth0.jwt.interfaces.DecodedJWT; 8 | 9 | import java.util.Calendar; 10 | import java.util.Date; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | public class JWTUtil { 15 | /** token秘钥,请勿泄露,请勿随便修改 backups:JKKLJOoasdlfj */ 16 | public static final String SECRET = "JKKLJOoasdlfj"; 17 | /** token 过期时间: 10天 */ 18 | public static final int calendarField = Calendar.DATE; 19 | public static final int calendarInterval = 10; 20 | 21 | /** 22 | * JWT生成Token.
23 | * 24 | * JWT构成: header, payload, signature 25 | * 26 | * @param user_id 27 | * 登录成功后用户user_id, 参数user_id不可传空 28 | */ 29 | public static String createToken(String user_id) throws Exception { 30 | Date iatDate = new Date(); 31 | // expire time 32 | Calendar nowTime = Calendar.getInstance(); 33 | nowTime.add(calendarField, calendarInterval); 34 | Date expiresDate = nowTime.getTime(); 35 | 36 | // header Map 37 | Map map = new HashMap<>(); 38 | map.put("alg", "HS256"); 39 | map.put("typ", "JWT"); 40 | 41 | // build token 42 | // param backups {iss:Service, aud:APP} 43 | String token = JWT.create().withHeader(map) // header 44 | .withClaim("iss", "Service") // payload 45 | .withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id.toString()) 46 | .withIssuedAt(iatDate) // sign time 47 | .withExpiresAt(expiresDate) // expire time 48 | .sign(Algorithm.HMAC256(SECRET)); // signature 49 | 50 | return token; 51 | } 52 | 53 | /** 54 | * 解密Token 55 | * 56 | * @param token 57 | * @return 58 | * @throws Exception 59 | */ 60 | public static Map verifyToken(String token) { 61 | DecodedJWT jwt = null; 62 | try { 63 | JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build(); 64 | jwt = verifier.verify(token); 65 | } catch (Exception e) { 66 | // e.printStackTrace(); 67 | // token 校验失败, 抛出Token验证非法异常 68 | } 69 | return jwt.getClaims(); 70 | } 71 | 72 | /** 73 | * 根据Token获取user_id 74 | * 75 | * @param token 76 | * @return user_id 77 | */ 78 | public static boolean getAppUID(String token) { 79 | Map claims = verifyToken(token); 80 | Claim user_id_claim = claims.get("user_id"); 81 | if (null == user_id_claim || (user_id_claim.asString().equals(""))) { 82 | // token 校验失败, 抛出Token验证非法异常 83 | return false; 84 | } 85 | return true; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/resources/commonProjectManage.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 数据库文件 3 | Navicat Premium Data Transfer 4 | 5 | Source Server : Ali_Mysql_5.5 6 | Source Server Type : MySQL 7 | Source Server Version : 50562 8 | Source Host : 47.93.31.98 9 | Source Database : commonProject 10 | 11 | Target Server Type : MySQL 12 | Target Server Version : 50562 13 | File Encoding : utf-8 14 | 15 | Date: 12/26/2018 20:46:38 PM 16 | */ 17 | 18 | SET NAMES utf8; 19 | SET FOREIGN_KEY_CHECKS = 0; 20 | 21 | -- ---------------------------- 22 | -- Table structure for `user_info` 23 | -- ---------------------------- 24 | DROP TABLE IF EXISTS `user_info`; 25 | CREATE TABLE `user_info` ( 26 | `id` varchar(32) NOT NULL COMMENT '用户ID', 27 | `login_id` varchar(32) NOT NULL COMMENT '登录账户', 28 | `pass_word` varchar(32) NOT NULL COMMENT '登录密码', 29 | `user_name` varchar(32) DEFAULT NULL COMMENT '用户姓名', 30 | `user_sex` varchar(4) DEFAULT NULL COMMENT '用户性别', 31 | `user_address` varchar(32) DEFAULT NULL COMMENT '用户联系地址', 32 | `user_cellphone` varchar(11) DEFAULT NULL COMMENT '用户手机号', 33 | PRIMARY KEY (`id`) 34 | ) ENGINE=`InnoDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ROW_FORMAT=COMPACT COMMENT='' CHECKSUM=0 DELAY_KEY_WRITE=0; 35 | 36 | -- ---------------------------- 37 | -- Records of `user_info` 38 | -- ---------------------------- 39 | BEGIN; 40 | INSERT INTO `user_info` VALUES ('11111', 'supervons', 'supervons', '测试', '男', '北京', '176xxxxxxxx'); 41 | COMMIT; 42 | 43 | SET FOREIGN_KEY_CHECKS = 1; 44 | 45 | -- ---------------------------- 46 | -- Table structure for `logger_infos` 47 | -- ---------------------------- 48 | DROP TABLE IF EXISTS `logger_infos`; 49 | CREATE TABLE `logger_infos` ( 50 | `logger_id` varchar(50) NOT NULL, 51 | `logger_client_ip` varchar(30) DEFAULT NULL, 52 | `logger_uri` varchar(255) DEFAULT NULL, 53 | `logger_type` varchar(50) DEFAULT NULL, 54 | `logger_method` varchar(50) DEFAULT NULL, 55 | `logger_param_date` longtext DEFAULT NULL, 56 | `logger_session_ud` varchar(100) DEFAULT NULL, 57 | `logger_time` timestamp NULL DEFAULT NULL, 58 | `logger_return_time` varchar(50) DEFAULT NULL, 59 | `logger_return_data` longtext DEFAULT NULL, 60 | `logger_http_status_code` varchar(10) DEFAULT NULL, 61 | `logger_time_consuming` int(8) DEFAULT NULL, 62 | PRIMARY KEY (`logger_id`) 63 | ) ENGINE=`InnoDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ROW_FORMAT=COMPACT COMMENT='' CHECKSUM=0 DELAY_KEY_WRITE=0; 64 | 65 | -- ---------------------------- 66 | -- Table structure for `news_info` 67 | -- ---------------------------- 68 | DROP TABLE IF EXISTS `news_info`; 69 | CREATE TABLE `news_info` ( 70 | `news_id` varchar(50) NOT NULL COMMENT '新闻编号', 71 | `news_title` varchar(30) DEFAULT NULL COMMENT '新闻标题', 72 | `news_introduction` varchar(255) DEFAULT NULL COMMENT '新闻简介', 73 | `news_favorite_id` varchar(50) DEFAULT NULL COMMENT '点赞编号', 74 | `news_comments_id` varchar(50) DEFAULT NULL COMMENT '评论编号', 75 | `news_time` varchar(50) DEFAULT NULL COMMENT '发布时间', 76 | `news_title_image` varchar(255) DEFAULT NULL COMMENT '标题图片', 77 | `news_content_image` varchar(255) DEFAULT NULL COMMENT '内容图片', 78 | `news_content` longtext DEFAULT NULL COMMENT '新闻内容', 79 | PRIMARY KEY (`news_id`) 80 | ) ENGINE=`InnoDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ROW_FORMAT=COMPACT COMMENT='' CHECKSUM=0 DELAY_KEY_WRITE=0; 81 | 82 | BEGIN; 83 | INSERT INTO `user_info` VALUES ('11111', 'supervons', 'supervons', '测试', '男', '北京', '176xxxxxxxx'); 84 | COMMIT; -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/Interceptor/SessionInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.Interceptor; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.serializer.SerializerFeature; 5 | import com.supervons.cpj.entity.LoggerInfos; 6 | import com.supervons.cpj.repository.LoggerInfosRepository; 7 | import com.supervons.cpj.srcurity.JWTUtil; 8 | import com.supervons.cpj.tools.DateUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.servlet.HandlerInterceptor; 12 | import org.springframework.web.servlet.ModelAndView; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | /** 17 | * 拦截器类 18 | * Interceptor 19 | * 20181227 by supervons 20 | */ 21 | @Component 22 | public class SessionInterceptor implements HandlerInterceptor { 23 | 24 | @Autowired 25 | private LoggerInfosRepository loggerInfosRepository; 26 | 27 | /** 28 | * 预处理回调方法,实现处理器的预处理 29 | * 返回值:true表示继续流程;false表示流程中断,不会继续调用其他的拦截器或处理器 30 | * Pre-processing callback method to achieve processor pre-processing 31 | * Return value: true means to continue the process; false means the process is interrupted 32 | * and will not continue to call other interceptors or processors 33 | */ 34 | @Override 35 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 36 | String url = request.getRequestURI(); 37 | if(!url.contains("/user/loginAction") && !url.contains("/user/addUser") && !url.contains("swagger")){ 38 | String jwtToken = request.getHeader("jwtToken")==null?"":request.getHeader("jwtToken").toString(); 39 | if(!JWTUtil.getAppUID(jwtToken)){ 40 | throw new Exception("非法请求!"); 41 | } 42 | } 43 | //请求日志存储 44 | LoggerInfos loggerInfos = new LoggerInfos(); 45 | String paramData = JSON.toJSONString(request.getParameterMap(), 46 | SerializerFeature.DisableCircularReferenceDetect, 47 | SerializerFeature.WriteMapNullValue); 48 | loggerInfos.setLoggerClientIp(request.getRemoteHost()); 49 | loggerInfos.setLoggerParamDate(paramData); 50 | loggerInfos.setLoggerMethod(request.getMethod()); 51 | loggerInfos.setLoggerUri(request.getRequestURI()); 52 | loggerInfos.setLoggerTime(DateUtils.getStandardTime()); 53 | loggerInfos.setLoggerHttpStatusCode(response.getStatus() + ""); 54 | loggerInfosRepository.saveAndFlush(loggerInfos); 55 | //业务代码 56 | return true; 57 | } 58 | 59 | /** 60 | * 后处理回调方法,实现处理器(controller)的后处理,但在渲染视图之前 61 | * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理 62 | * Post-processing callback methods to implement post-processing of the controller, but before rendering the view 63 | * At this point we can process the model data or process the view through modelAndView 64 | */ 65 | @Override 66 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 67 | ModelAndView modelAndView) throws Exception { 68 | // TODO Auto-generated method stub 69 | 70 | } 71 | /** 72 | * 整个请求处理完毕回调方法,即在视图渲染完毕时回调, 73 | * 如性能监控中我们可以在此记录结束时间并输出消耗时间, 74 | * 还可以进行一些资源清理,类似于try-catch-finally中的finally, 75 | * 但仅调用处理器执行链中 76 | * The entire request processing callback method, that is, the callback when the view is rendered, 77 | * In performance monitoring, we can record the end time and output the consumption time. 78 | * Some resource cleanups can also be done, similar to finally in try-catch-finally. 79 | * but only call the processor in the execution chain 80 | */ 81 | @Override 82 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 83 | throws Exception { 84 | // TODO Auto-generated method stub 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/CommonConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj; 2 | 3 | import com.alibaba.fastjson.serializer.SerializerFeature; 4 | import com.alibaba.fastjson.support.config.FastJsonConfig; 5 | import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 6 | import com.supervons.cpj.Interceptor.SessionInterceptor; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.http.converter.HttpMessageConverter; 11 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 12 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 13 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * 通用 Configuration 配置 20 | * 1,拦截器配置 21 | * 2,FastJson 返回 JSON 配置 22 | */ 23 | @Configuration 24 | public class CommonConfiguration extends WebMvcConfigurationSupport { 25 | 26 | @Autowired 27 | private SessionInterceptor loginInterceptor; 28 | 29 | @Override 30 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 31 | // 配置 swagger 相关访问地址 32 | registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); 33 | registry.addResourceHandler("swagger-ui.html") 34 | .addResourceLocations("classpath:/META-INF/resources/"); 35 | registry.addResourceHandler("/webjars/**") 36 | .addResourceLocations("classpath:/META-INF/resources/webjars/"); 37 | super.addResourceHandlers(registry); 38 | } 39 | 40 | @Override 41 | public void addInterceptors(InterceptorRegistry registry) { 42 | registry.addInterceptor(loginInterceptor).addPathPatterns("/**"); 43 | } 44 | 45 | @Override 46 | protected void configureMessageConverters(List> converters) { 47 | // 调用父类配置 48 | super.configureMessageConverters(converters); 49 | // 创建 fastjson 消息转换器 50 | FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); 51 | 52 | // 升级最新版本需加支持的类型 53 | List supportedMediaTypes = new ArrayList<>(); 54 | supportedMediaTypes.add(MediaType.APPLICATION_JSON); 55 | supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); 56 | supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML); 57 | supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); 58 | supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM); 59 | supportedMediaTypes.add(MediaType.APPLICATION_PDF); 60 | supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML); 61 | supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML); 62 | supportedMediaTypes.add(MediaType.APPLICATION_XML); 63 | supportedMediaTypes.add(MediaType.IMAGE_GIF); 64 | supportedMediaTypes.add(MediaType.IMAGE_JPEG); 65 | supportedMediaTypes.add(MediaType.IMAGE_PNG); 66 | supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM); 67 | supportedMediaTypes.add(MediaType.TEXT_HTML); 68 | supportedMediaTypes.add(MediaType.TEXT_MARKDOWN); 69 | supportedMediaTypes.add(MediaType.TEXT_PLAIN); 70 | supportedMediaTypes.add(MediaType.TEXT_XML); 71 | fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes); 72 | 73 | // 创建配置类 74 | FastJsonConfig fastJsonConfig = new FastJsonConfig(); 75 | // 修改配置返回内容的过滤 76 | fastJsonConfig.setSerializerFeatures( 77 | SerializerFeature.DisableCircularReferenceDetect, 78 | SerializerFeature.WriteMapNullValue, 79 | SerializerFeature.WriteNullStringAsEmpty 80 | ); 81 | fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); 82 | // 将fastJson添加到视图消息转换器列表内 83 | converters.add(fastJsonHttpMessageConverter); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/supervons/cpj/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.supervons.cpj.controller; 2 | 3 | import com.supervons.cpj.entity.APIResponse; 4 | import com.supervons.cpj.entity.User; 5 | import com.supervons.cpj.repository.UserInfoRepository; 6 | import com.supervons.cpj.service.UserService; 7 | import com.supervons.cpj.srcurity.JWTUtil; 8 | import io.swagger.annotations.Api; 9 | import io.swagger.annotations.ApiOperation; 10 | import io.swagger.annotations.ApiParam; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.Optional; 18 | 19 | /** 20 | * User controller 21 | * Login 22 | * Register 23 | */ 24 | @RestController 25 | @RequestMapping("/user") 26 | @Api(description = "用户相关接口") 27 | public class UserController { 28 | APIResponse apiResponse = null; 29 | 30 | @Autowired 31 | private UserService userService; 32 | 33 | @Autowired 34 | private UserInfoRepository userInfoRepository; 35 | 36 | @ResponseBody 37 | @RequestMapping(value = "/addUser", method = RequestMethod.POST) 38 | @ApiOperation(value = "新增用户接口", notes = "根据手机号密码注册用户,且校验重复性") 39 | public APIResponse addUser(@ApiParam(required = true, value = "用户信息map,包含loginId与passWord两个字符串") @RequestBody HashMap map) { 40 | User tempUser = userService.queryUserExistById(map.get("loginId")); 41 | if (tempUser != null) { 42 | apiResponse = APIResponse.fail("该手机号已存在,请更换手机号后尝试!"); 43 | } else { 44 | User newUser = new User(); 45 | newUser.setLoginId(map.get("loginId")); 46 | newUser.setPassWord(map.get("passWord")); 47 | int result = userService.addUser(newUser); 48 | if (result == 1) { 49 | Map resultMap = new HashMap(); 50 | resultMap.put("resultMsg", "注册成功!"); 51 | apiResponse = APIResponse.success(resultMap); 52 | } else { 53 | apiResponse = APIResponse.fail("注册失败!"); 54 | } 55 | } 56 | return apiResponse; 57 | } 58 | 59 | @RequestMapping(value = "/deleteUser", method = RequestMethod.POST) 60 | public List deleteUser(@RequestBody User user) { 61 | userInfoRepository.delete(user); 62 | return userInfoRepository.findAll(); 63 | } 64 | 65 | @ResponseBody 66 | @RequestMapping(value = "/updateUser", method = RequestMethod.POST) 67 | public APIResponse updateUser(@RequestBody User user) { 68 | User saveUser = userInfoRepository.saveAndFlush(user); 69 | if (saveUser != null) { 70 | apiResponse = APIResponse.success(); 71 | apiResponse.setMsg("保存成功"); 72 | } else { 73 | apiResponse = APIResponse.fail("保存失败"); 74 | } 75 | return apiResponse; 76 | } 77 | 78 | @ResponseBody 79 | @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) 80 | public APIResponse updatePassword(@RequestBody HashMap map) { 81 | // 校验用户名及原密码是否正确 82 | User tempUser = userService.queryUserById(map.get("loginId"), map.get("oldPassword")); 83 | if (tempUser != null) { 84 | String newPassword = map.get("newPassword"); 85 | tempUser.setPassWord(newPassword); 86 | userInfoRepository.saveAndFlush(tempUser); 87 | apiResponse = APIResponse.success(); 88 | apiResponse.setMsg("修改密码成功!"); 89 | } else { 90 | apiResponse = APIResponse.fail("原密码不正确,请重新输入!"); 91 | } 92 | return apiResponse; 93 | } 94 | 95 | @ResponseBody 96 | @RequestMapping("/queryUserById") 97 | public Optional queryUserById(@RequestParam("id") String id) { 98 | return userInfoRepository.findById(id); 99 | } 100 | 101 | @ResponseBody 102 | @RequestMapping("/queryUserList") 103 | public List queryUserList() { 104 | return userInfoRepository.findAll(); 105 | } 106 | 107 | @ResponseBody 108 | @RequestMapping(value = "/loginAction", method = RequestMethod.POST) 109 | public APIResponse loginAction(@RequestBody HashMap map) { 110 | APIResponse apiResponse = null; 111 | System.out.println(map.get("loginId") + map.get("passWord")); 112 | User tempUser = userService.queryUserById(map.get("loginId"), map.get("passWord")); 113 | if (tempUser != null) { 114 | apiResponse = APIResponse.success(); 115 | apiResponse.setData(tempUser); 116 | try { 117 | String jwtToken = JWTUtil.createToken(map.get("loginId")); 118 | Map jwtMap = new HashMap(); 119 | jwtMap.put("jwtToken", jwtToken); 120 | apiResponse.setAuxiliaryData(jwtMap); 121 | } catch (Exception e) { 122 | e.printStackTrace(); 123 | } 124 | } else { 125 | apiResponse = APIResponse.fail("登录失败,用户名或密码错误!"); 126 | } 127 | return apiResponse; 128 | } 129 | 130 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.1.RELEASE 9 | 10 | 11 | com.supervons 12 | cpj 13 | 0.0.1-SNAPSHOT 14 | cpj 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-aop 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-jpa 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-cache 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-configuration-processor 41 | true 42 | 43 | 44 | org.mybatis.spring.boot 45 | mybatis-spring-boot-starter 46 | 1.3.2 47 | 48 | 49 | 50 | mysql 51 | mysql-connector-java 52 | runtime 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-starter-test 57 | test 58 | 59 | 60 | com.github.pagehelper 61 | pagehelper 62 | 4.1.0 63 | 64 | 69 | 70 | com.alibaba 71 | druid-spring-boot-starter 72 | 1.1.17 73 | 74 | 75 | 76 | com.alibaba 77 | fastjson 78 | 1.2.47 79 | 80 | 81 | 82 | org.springframework.data 83 | spring-data-jpa 84 | 2.1.3.RELEASE 85 | 86 | 87 | 88 | org.projectlombok 89 | lombok 90 | true 91 | 92 | 93 | 94 | org.springframework.boot 95 | spring-boot-devtools 96 | true 97 | 98 | 99 | 100 | commons-net 101 | commons-net 102 | 3.6 103 | 104 | 105 | org.springframework.boot 106 | spring-boot-starter-thymeleaf 107 | 108 | 109 | com.auth0 110 | java-jwt 111 | 3.3.0 112 | 113 | 114 | 115 | io.springfox 116 | springfox-swagger2 117 | 2.9.2 118 | 119 | 120 | 121 | io.springfox 122 | springfox-swagger-ui 123 | 2.9.2 124 | 125 | 126 | 127 | 128 | 129 | 130 | org.springframework.boot 131 | spring-boot-maven-plugin 132 | 133 | false 134 | 135 | 136 | 137 | org.springframework.boot 138 | spring-boot-maven-plugin 139 | 140 | com.supervons.cpj.CpjApplication 141 | 142 | 143 | 144 | 145 | 146 | 147 | --------------------------------------------------------------------------------