├── README.md ├── pom.xml └── src ├── main ├── java │ └── top │ │ └── javahai │ │ └── chatroom │ │ ├── ChatroomApplication.java │ │ ├── config │ │ ├── AliyunOssConfig.java │ │ ├── MultiHttpSecurityConfig.java │ │ ├── MyAuthenticationFailureHandler.java │ │ ├── MyLogoutSuccessHandler.java │ │ ├── SecurityConfig.java │ │ ├── VerificationCode.java │ │ ├── VerificationCodeFilter.java │ │ └── WebSocketConfig.java │ │ ├── controller │ │ ├── AdminController.java │ │ ├── ChatController.java │ │ ├── FileController.java │ │ ├── GroupMsgContentController.java │ │ ├── LoginController.java │ │ ├── MailController.java │ │ ├── UserController.java │ │ ├── UserStateController.java │ │ └── WsController.java │ │ ├── converter │ │ └── DateConverter.java │ │ ├── dao │ │ ├── AdminDao.java │ │ ├── GroupMsgContentDao.java │ │ ├── UserDao.java │ │ └── UserStateDao.java │ │ ├── entity │ │ ├── Admin.java │ │ ├── GroupMsgContent.java │ │ ├── Message.java │ │ ├── RespBean.java │ │ ├── RespPageBean.java │ │ ├── User.java │ │ └── UserState.java │ │ ├── exception │ │ └── GlobalExceptionHandler.java │ │ ├── service │ │ ├── AdminService.java │ │ ├── GroupMsgContentService.java │ │ ├── UserService.java │ │ ├── UserStateService.java │ │ └── impl │ │ │ ├── AdminServiceImpl.java │ │ │ ├── GroupMsgContentServiceImpl.java │ │ │ ├── UserServiceImpl.java │ │ │ └── UserStateServiceImpl.java │ │ └── utils │ │ ├── AliyunOssUtil.java │ │ ├── FastDFSUtil.java │ │ ├── TuLingUtil.java │ │ └── UserUtil.java └── resources │ ├── application-dev.properties │ ├── application.properties │ ├── fastdfs-client.properties │ └── mapper │ ├── AdminDao.xml │ ├── GroupMsgContentDao.xml │ ├── UserDao.xml │ └── UserStateDao.xml └── test └── java └── top └── javahai └── chatroom └── ChatroomApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # subtlechat-mini 2 | 微言聊天室的简化版 3 | 4 | 项目完整版:https://github.com/JustCoding-Hai/subtlechat 5 | 6 | 为了简化部署,取消了分模块,删去了邮件发送部分的RabbitMQ、Redis的使用 7 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.1.RELEASE 9 | 10 | 11 | top.javahai 12 | subtlechat-mini 13 | 0.0.1-SNAPSHOT 14 | subtlechat-mini 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-websocket 33 | 34 | 35 | org.mybatis.spring.boot 36 | mybatis-spring-boot-starter 37 | 2.1.3 38 | 39 | 40 | 41 | com.alibaba 42 | druid-spring-boot-starter 43 | 1.1.10 44 | 45 | 46 | mysql 47 | mysql-connector-java 48 | runtime 49 | 50 | 51 | net.oschina.zcx7878 52 | fastdfs-client-java 53 | 1.27.0.0 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-test 58 | test 59 | 60 | 61 | org.junit.vintage 62 | junit-vintage-engine 63 | 64 | 65 | 66 | 67 | org.springframework.security 68 | spring-security-test 69 | test 70 | 71 | 72 | mysql 73 | mysql-connector-java 74 | 5.1.44 75 | 76 | 77 | com.github.binarywang 78 | java-emoji-converter 79 | 0.1.1 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-starter-mail 84 | 85 | 86 | 87 | com.aliyun.oss 88 | aliyun-sdk-oss 89 | 3.10.2 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | src/main/resources 99 | 100 | **/* 101 | 102 | 103 | 104 | 105 | org.springframework.boot 106 | spring-boot-maven-plugin 107 | 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/ChatroomApplication.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | /** 8 | * @author Hai 9 | * @date 2020/6/16 - 12:45 10 | */ 11 | @SpringBootApplication 12 | @MapperScan("top.javahai.chatroom.dao") 13 | public class ChatroomApplication { 14 | public static void main(String[] args) { 15 | SpringApplication.run(ChatroomApplication.class, args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/AliyunOssConfig.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @author Hai 8 | * @program: subtlechat-mini 9 | * @description: 10 | * @create 2021/12/5 - 19:25 11 | **/ 12 | @Component 13 | @ConfigurationProperties(prefix="aliyun.oss") 14 | public class AliyunOssConfig { 15 | private String endpoint; 16 | private String keyid; 17 | private String keysecret; 18 | private String bucketname; 19 | 20 | 21 | public String getEndpoint() { 22 | return endpoint; 23 | } 24 | 25 | public void setEndpoint(String endpoint) { 26 | this.endpoint = endpoint; 27 | } 28 | 29 | public String getKeyid() { 30 | return keyid; 31 | } 32 | 33 | public void setKeyid(String keyid) { 34 | this.keyid = keyid; 35 | } 36 | 37 | public String getKeysecret() { 38 | return keysecret; 39 | } 40 | 41 | public void setKeysecret(String keysecret) { 42 | this.keysecret = keysecret; 43 | } 44 | 45 | public String getBucketname() { 46 | return bucketname; 47 | } 48 | 49 | public void setBucketname(String bucketname) { 50 | this.bucketname = bucketname; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/MultiHttpSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.messaging.simp.SimpMessagingTemplate; 9 | import org.springframework.security.authentication.*; 10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 12 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.core.Authentication; 16 | import org.springframework.security.core.AuthenticationException; 17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 18 | import org.springframework.security.crypto.password.PasswordEncoder; 19 | import org.springframework.security.web.AuthenticationEntryPoint; 20 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 21 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 22 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 23 | import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 24 | import top.javahai.chatroom.entity.Admin; 25 | import top.javahai.chatroom.entity.RespBean; 26 | import top.javahai.chatroom.entity.User; 27 | import top.javahai.chatroom.service.impl.AdminServiceImpl; 28 | import top.javahai.chatroom.service.impl.UserServiceImpl; 29 | 30 | import javax.servlet.ServletException; 31 | import javax.servlet.http.HttpServletRequest; 32 | import javax.servlet.http.HttpServletResponse; 33 | import java.io.IOException; 34 | import java.io.PrintWriter; 35 | 36 | /** 37 | * @author Hai 38 | * @date 2020/6/19 - 12:37 39 | */ 40 | @EnableWebSecurity 41 | public class MultiHttpSecurityConfig { 42 | //密码加密方案 43 | @Bean 44 | PasswordEncoder passwordEncoder(){ 45 | return new BCryptPasswordEncoder(); 46 | } 47 | @Configuration 48 | @Order(1) 49 | public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{ 50 | @Autowired 51 | AdminServiceImpl adminService; 52 | @Autowired 53 | VerificationCodeFilter verificationCodeFilter; 54 | @Autowired 55 | SimpMessagingTemplate simpMessagingTemplate; 56 | @Autowired 57 | MyAuthenticationFailureHandler myAuthenticationFailureHandler; 58 | @Autowired 59 | MyLogoutSuccessHandler myLogoutSuccessHandler; 60 | 61 | //用户名和密码验证服务 62 | @Override 63 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 64 | auth.userDetailsService(adminService); 65 | } 66 | 67 | //忽略"/login","/verifyCode"请求,该请求不需要进入Security的拦截器 68 | @Override 69 | public void configure(WebSecurity web) throws Exception { 70 | web.ignoring().antMatchers("/css/**","/fonts/**","/img/**","/js/**","/favicon.ico","/index.html","/admin/login","/admin/mailVerifyCode"); 71 | } 72 | //http请求验证和处理规则,响应处理的配置 73 | @Override 74 | protected void configure(HttpSecurity http) throws Exception { 75 | //将验证码过滤器添加在用户名密码过滤器的前面 76 | http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class); 77 | http.antMatcher("/admin/**").authorizeRequests() 78 | .anyRequest().authenticated() 79 | .and() 80 | .formLogin() 81 | .usernameParameter("username") 82 | .passwordParameter("password") 83 | .loginPage("/admin/login") 84 | .loginProcessingUrl("/admin/doLogin") 85 | //成功处理 86 | .successHandler(new AuthenticationSuccessHandler() { 87 | @Override 88 | public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 89 | resp.setContentType("application/json;charset=utf-8"); 90 | PrintWriter out=resp.getWriter(); 91 | Admin admin=(Admin) authentication.getPrincipal(); 92 | admin.setPassword(null); 93 | RespBean ok = RespBean.ok("登录成功", admin); 94 | String s = new ObjectMapper().writeValueAsString(ok); 95 | out.write(s); 96 | out.flush(); 97 | out.close(); 98 | } 99 | }) 100 | //失败处理 101 | .failureHandler(myAuthenticationFailureHandler) 102 | .permitAll()//返回值直接返回 103 | .and() 104 | //登出处理 105 | .logout() 106 | .logoutUrl("/admin/logout") 107 | .logoutSuccessHandler(myLogoutSuccessHandler) 108 | .permitAll() 109 | .and() 110 | .csrf().disable()//关闭csrf防御方便调试 111 | //没有认证时,在这里处理结果,不进行重定向到login页 112 | .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() { 113 | @Override 114 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 115 | httpServletResponse.setStatus(401); 116 | } 117 | }); 118 | } 119 | } 120 | @Configuration 121 | @Order(2) 122 | public static class UserSecurityConfig extends WebSecurityConfigurerAdapter { 123 | @Autowired 124 | UserServiceImpl userService; 125 | @Autowired 126 | VerificationCodeFilter verificationCodeFilter; 127 | @Autowired 128 | SimpMessagingTemplate simpMessagingTemplate; 129 | @Autowired 130 | MyAuthenticationFailureHandler myAuthenticationFailureHandler; 131 | 132 | //验证服务 133 | @Override 134 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 135 | auth.userDetailsService(userService); 136 | } 137 | 138 | // //密码加密 139 | // @Bean 140 | // PasswordEncoder passwordEncoder(){ 141 | // return new BCryptPasswordEncoder(); 142 | // } 143 | 144 | 145 | //忽略"/login","/verifyCode"请求,该请求不需要进入Security的拦截器 146 | @Override 147 | public void configure(WebSecurity web) throws Exception { 148 | web.ignoring().antMatchers("/login","/verifyCode","/file","/ossFileUpload","/user/register","/user/checkUsername","/user/checkNickname"); 149 | } 150 | //登录验证 151 | @Override 152 | protected void configure(HttpSecurity http) throws Exception { 153 | //将验证码过滤器添加在用户名密码过滤器的前面 154 | http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class); 155 | http.authorizeRequests() 156 | .anyRequest().authenticated() 157 | .and() 158 | .formLogin() 159 | .usernameParameter("username") 160 | .passwordParameter("password") 161 | .loginPage("/login") 162 | .loginProcessingUrl("/doLogin") 163 | //成功处理 164 | .successHandler(new AuthenticationSuccessHandler() { 165 | @Override 166 | public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 167 | resp.setContentType("application/json;charset=utf-8"); 168 | PrintWriter out=resp.getWriter(); 169 | User user=(User) authentication.getPrincipal(); 170 | user.setPassword(null); 171 | //更新用户状态为在线 172 | userService.setUserStateToOn(user.getId()); 173 | user.setUserStateId(1); 174 | //广播系统通知消息 175 | simpMessagingTemplate.convertAndSend("/topic/notification","系统消息:用户【"+user.getNickname()+"】进入了聊天室"); 176 | RespBean ok = RespBean.ok("登录成功", user); 177 | String s = new ObjectMapper().writeValueAsString(ok); 178 | out.write(s); 179 | out.flush(); 180 | out.close(); 181 | } 182 | }) 183 | //失败处理 184 | .failureHandler(myAuthenticationFailureHandler) 185 | .permitAll()//返回值直接返回 186 | .and() 187 | //登出处理 188 | .logout() 189 | .logoutUrl("/logout") 190 | .logoutSuccessHandler(new LogoutSuccessHandler() { 191 | @Override 192 | public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 193 | //更新用户状态为离线 194 | User user = (User) authentication.getPrincipal(); 195 | userService.setUserStateToLeave(user.getId()); 196 | //广播系统消息 197 | simpMessagingTemplate.convertAndSend("/topic/notification","系统消息:用户【"+user.getNickname()+"】退出了聊天室"); 198 | resp.setContentType("application/json;charset=utf-8"); 199 | PrintWriter out=resp.getWriter(); 200 | out.write(new ObjectMapper().writeValueAsString(RespBean.ok("成功退出!"))); 201 | out.flush(); 202 | out.close(); 203 | } 204 | }) 205 | .permitAll() 206 | .and() 207 | .csrf().disable()//关闭csrf防御方便调试 208 | //没有认证时,在这里处理结果,不进行重定向到login页 209 | .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() { 210 | @Override 211 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 212 | httpServletResponse.setStatus(401); 213 | } 214 | }); 215 | } 216 | } 217 | 218 | } 219 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/MyAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.*; 6 | import org.springframework.security.core.AuthenticationException; 7 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 8 | import top.javahai.chatroom.entity.RespBean; 9 | 10 | import javax.servlet.ServletException; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.io.IOException; 14 | import java.io.PrintWriter; 15 | 16 | /** 17 | * @author Hai 18 | * @date 2020/6/19 - 13:13 19 | */ 20 | @Configuration 21 | public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { 22 | @Override 23 | public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException { 24 | resp.setContentType("application/json;charset=utf-8"); 25 | PrintWriter out=resp.getWriter(); 26 | RespBean error = RespBean.error("登录失败!"); 27 | if (exception instanceof LockedException){ 28 | error.setMsg("账户已锁定,请联系管理员!"); 29 | }else if (exception instanceof CredentialsExpiredException){ 30 | error.setMsg("密码已过期,请联系管理员!"); 31 | }else if (exception instanceof AccountExpiredException){ 32 | error.setMsg("账户已过期,请联系管理员!"); 33 | }else if (exception instanceof DisabledException){ 34 | error.setMsg("账户被禁用,请联系管理员!"); 35 | }else if (exception instanceof BadCredentialsException){ 36 | error.setMsg("用户名或密码错误,请重新输入!"); 37 | } 38 | String s = new ObjectMapper().writeValueAsString(error); 39 | out.write(s); 40 | out.flush(); 41 | out.close(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/MyLogoutSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.core.Authentication; 6 | import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 7 | import top.javahai.chatroom.entity.RespBean; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | import java.io.PrintWriter; 14 | 15 | /** 16 | * @author Hai 17 | * @date 2020/6/19 - 13:18 18 | */ 19 | @Configuration 20 | public class MyLogoutSuccessHandler implements LogoutSuccessHandler { 21 | 22 | @Override 23 | public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 24 | resp.setContentType("application/json;charset=utf-8"); 25 | PrintWriter out=resp.getWriter(); 26 | out.write(new ObjectMapper().writeValueAsString(RespBean.ok("成功退出!"))); 27 | out.flush(); 28 | out.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | //package top.javahai.chatroom.config; 2 | // 3 | //import com.fasterxml.jackson.databind.ObjectMapper; 4 | //import org.springframework.beans.factory.annotation.Autowired; 5 | //import org.springframework.context.annotation.Bean; 6 | //import org.springframework.context.annotation.Configuration; 7 | //import org.springframework.messaging.simp.SimpMessagingTemplate; 8 | //import org.springframework.security.authentication.*; 9 | //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | //import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | //import org.springframework.security.config.annotation.web.builders.WebSecurity; 12 | //import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | //import org.springframework.security.core.Authentication; 14 | //import org.springframework.security.core.AuthenticationException; 15 | //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | //import org.springframework.security.crypto.password.PasswordEncoder; 17 | //import org.springframework.security.web.AuthenticationEntryPoint; 18 | //import org.springframework.security.web.authentication.AuthenticationFailureHandler; 19 | //import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 20 | //import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 21 | //import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 22 | //import top.javahai.chatroom.entity.RespBean; 23 | //import top.javahai.chatroom.entity.User; 24 | //import top.javahai.chatroom.service.impl.UserServiceImpl; 25 | // 26 | //import javax.servlet.ServletException; 27 | //import javax.servlet.http.HttpServletRequest; 28 | //import javax.servlet.http.HttpServletResponse; 29 | //import java.io.IOException; 30 | //import java.io.PrintWriter; 31 | // 32 | ///** 33 | // * @author Hai 34 | // * @date 2020/6/16 - 12:31 35 | // */ 36 | ////@Configuration 37 | //public class SecurityConfig extends WebSecurityConfigurerAdapter { 38 | // @Autowired 39 | // UserServiceImpl userService; 40 | // @Autowired 41 | // VerificationCodeFilter verificationCodeFilter; 42 | // @Autowired 43 | // SimpMessagingTemplate simpMessagingTemplate; 44 | // 45 | // //验证服务 46 | // @Override 47 | // protected void configure(AuthenticationManagerBuilder auth) throws Exception { 48 | // auth.userDetailsService(userService); 49 | // } 50 | // 51 | // //密码加密 52 | // @Bean 53 | // PasswordEncoder passwordEncoder(){ 54 | // return new BCryptPasswordEncoder(); 55 | // } 56 | // 57 | // 58 | // //忽略"/login","/verifyCode"请求,该请求不需要进入Security的拦截器 59 | // @Override 60 | // public void configure(WebSecurity web) throws Exception { 61 | // web.ignoring().antMatchers("/login","/verifyCode"); 62 | // } 63 | // //登录验证 64 | // @Override 65 | // protected void configure(HttpSecurity http) throws Exception { 66 | // //将验证码过滤器添加在用户名密码过滤器的前面 67 | // http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class); 68 | // http.authorizeRequests() 69 | // .anyRequest().authenticated() 70 | // .and() 71 | // .formLogin() 72 | // .usernameParameter("username") 73 | // .passwordParameter("password") 74 | // .loginPage("/login") 75 | // .loginProcessingUrl("/doLogin") 76 | // //成功处理 77 | // .successHandler(new AuthenticationSuccessHandler() { 78 | // @Override 79 | // public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 80 | // resp.setContentType("application/json;charset=utf-8"); 81 | // PrintWriter out=resp.getWriter(); 82 | // User user=(User) authentication.getPrincipal(); 83 | // user.setPassword(null); 84 | // //更新用户状态为在线 85 | // userService.setUserStateToOn(user.getId()); 86 | // user.setUserStateId(1); 87 | // //广播系统通知消息 88 | // simpMessagingTemplate.convertAndSend("/topic/notification","系统消息:用户【"+user.getNickname()+"】进入了聊天室"); 89 | // RespBean ok = RespBean.ok("登录成功", user); 90 | // String s = new ObjectMapper().writeValueAsString(ok); 91 | // out.write(s); 92 | // out.flush(); 93 | // out.close(); 94 | // } 95 | // }) 96 | // //失败处理 97 | // .failureHandler(new AuthenticationFailureHandler() { 98 | // @Override 99 | // public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException { 100 | // resp.setContentType("application/json;charset=utf-8"); 101 | // PrintWriter out=resp.getWriter(); 102 | // RespBean error = RespBean.error("登录失败!"); 103 | // if (exception instanceof LockedException){ 104 | // error.setMsg("账户已锁定,请联系管理员!"); 105 | // }else if (exception instanceof CredentialsExpiredException){ 106 | // error.setMsg("密码已过期,请联系管理员!"); 107 | // }else if (exception instanceof AccountExpiredException){ 108 | // error.setMsg("账户已过期,请联系管理员!"); 109 | // }else if (exception instanceof DisabledException){ 110 | // error.setMsg("账户被禁用,请联系管理员!"); 111 | // }else if (exception instanceof BadCredentialsException){ 112 | // error.setMsg("用户名或密码错误,请重新输入!"); 113 | // } 114 | // String s = new ObjectMapper().writeValueAsString(error); 115 | // out.write(s); 116 | // out.flush(); 117 | // out.close(); 118 | // } 119 | // }) 120 | // .permitAll()//返回值直接返回 121 | // .and() 122 | // //登出处理 123 | // .logout() 124 | // .logoutUrl("/logout") 125 | // .logoutSuccessHandler(new LogoutSuccessHandler() { 126 | // @Override 127 | // public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException { 128 | // //更新用户状态为离线 129 | // User user = (User) authentication.getPrincipal(); 130 | // userService.setUserStateToLeave(user.getId()); 131 | // //广播系统消息 132 | // simpMessagingTemplate.convertAndSend("/topic/notification","系统消息:用户【"+user.getNickname()+"】退出了聊天室"); 133 | // resp.setContentType("application/json;charset=utf-8"); 134 | // PrintWriter out=resp.getWriter(); 135 | // out.write(new ObjectMapper().writeValueAsString(RespBean.ok("成功退出!"))); 136 | // out.flush(); 137 | // out.close(); 138 | // } 139 | // }) 140 | // .permitAll() 141 | // .and() 142 | // .csrf().disable()//关闭csrf防御方便调试 143 | // //没有认证时,在这里处理结果,不进行重定向到login页 144 | // .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() { 145 | // @Override 146 | // public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 147 | // httpServletResponse.setStatus(401); 148 | // } 149 | // }); 150 | // } 151 | //} 152 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/VerificationCode.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import javax.imageio.ImageIO; 4 | import java.awt.*; 5 | import java.awt.image.BufferedImage; 6 | import java.io.IOException; 7 | import java.io.OutputStream; 8 | import java.util.Random; 9 | 10 | /** 11 | * @author Hai 12 | * @date 2020/6/16 - 17:24 13 | * 生成验证码的工具类 14 | */ 15 | public class VerificationCode { 16 | 17 | private int width = 100;// 生成验证码图片的宽度 18 | private int height = 30;// 生成验证码图片的高度 19 | private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" }; 20 | private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色 21 | private Random random = new Random(); 22 | private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 23 | private String text;// 记录随机字符串 24 | 25 | /** 26 | * 获取一个随意颜色 27 | * 28 | * @return 29 | */ 30 | private Color randomColor() { 31 | int red = random.nextInt(150); 32 | int green = random.nextInt(150); 33 | int blue = random.nextInt(150); 34 | return new Color(red, green, blue); 35 | } 36 | 37 | /** 38 | * 获取一个随机字体 39 | * 40 | * @return 41 | */ 42 | private Font randomFont() { 43 | String name = fontNames[random.nextInt(fontNames.length)]; 44 | int style = random.nextInt(4); 45 | int size = random.nextInt(5) + 24; 46 | return new Font(name, style, size); 47 | } 48 | 49 | /** 50 | * 获取一个随机字符 51 | * 52 | * @return 53 | */ 54 | private char randomChar() { 55 | return codes.charAt(random.nextInt(codes.length())); 56 | } 57 | 58 | /** 59 | * 创建一个空白的BufferedImage对象 60 | * 61 | * @return 62 | */ 63 | private BufferedImage createImage() { 64 | BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 65 | Graphics2D g2 = (Graphics2D) image.getGraphics(); 66 | g2.setColor(bgColor);// 设置验证码图片的背景颜色 67 | g2.fillRect(0, 0, width, height); 68 | return image; 69 | } 70 | 71 | public BufferedImage getImage() { 72 | BufferedImage image = createImage(); 73 | Graphics2D g2 = (Graphics2D) image.getGraphics(); 74 | StringBuffer sb = new StringBuffer(); 75 | for (int i = 0; i < 4; i++) { 76 | String s = randomChar() + ""; 77 | sb.append(s); 78 | g2.setColor(randomColor()); 79 | g2.setFont(randomFont()); 80 | float x = i * width * 1.0f / 4; 81 | g2.drawString(s, x, height - 8); 82 | } 83 | this.text = sb.toString(); 84 | drawLine(image); 85 | return image; 86 | } 87 | 88 | /** 89 | * 绘制干扰线 90 | * 91 | * @param image 92 | */ 93 | private void drawLine(BufferedImage image) { 94 | Graphics2D g2 = (Graphics2D) image.getGraphics(); 95 | int num = 5; 96 | for (int i = 0; i < num; i++) { 97 | int x1 = random.nextInt(width); 98 | int y1 = random.nextInt(height); 99 | int x2 = random.nextInt(width); 100 | int y2 = random.nextInt(height); 101 | g2.setColor(randomColor()); 102 | g2.setStroke(new BasicStroke(1.5f)); 103 | g2.drawLine(x1, y1, x2, y2); 104 | } 105 | } 106 | 107 | public String getText() { 108 | return text; 109 | } 110 | 111 | public static void output(BufferedImage image, OutputStream out) throws IOException { 112 | ImageIO.write(image, "JPEG", out); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/VerificationCodeFilter.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.stereotype.Component; 5 | import top.javahai.chatroom.entity.RespBean; 6 | 7 | import javax.servlet.*; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | import java.io.PrintWriter; 12 | 13 | /** 14 | * 拦截登录请求,验证输入的验证码是否正确 15 | * @author Hai 16 | * @date 2020/5/28 - 17:31 17 | */ 18 | @Component 19 | public class VerificationCodeFilter extends GenericFilter { 20 | 21 | @Override 22 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 23 | HttpServletRequest request = (HttpServletRequest) servletRequest; 24 | HttpServletResponse response = (HttpServletResponse) servletResponse; 25 | //如果是登录请求则拦截 26 | if ("POST".equals(request.getMethod())&&"/doLogin".equals(request.getServletPath())){ 27 | //用户输入的验证码 28 | String code = request.getParameter("code"); 29 | //session中保存的验证码 30 | String verify_code = (String) request.getSession().getAttribute("verify_code"); 31 | response.setContentType("application/json;charset=utf-8"); 32 | PrintWriter writer = response.getWriter(); 33 | //验证session中保存是否存在 34 | try { 35 | //验证是否相同 36 | if (!code.toLowerCase().equals(verify_code.toLowerCase())){ 37 | //输出json 38 | writer.write(new ObjectMapper().writeValueAsString( RespBean.error("验证码错误!"))); 39 | return; 40 | }else { 41 | filterChain.doFilter(request,response); 42 | } 43 | }catch (NullPointerException e){ 44 | writer.write(new ObjectMapper().writeValueAsString(RespBean.error("请求异常,请重新请求!"))); 45 | }finally { 46 | writer.flush(); 47 | writer.close(); 48 | } 49 | } 50 | //管理端登录请求 51 | // else if ("POST".equals(request.getMethod())&&"/admin/doLogin".equals(request.getServletPath())){ 52 | // //获取输入的验证码 53 | // String mailCode = request.getParameter("mailCode"); 54 | // //获取session中保存的验证码 55 | // String verifyCode = ((String) request.getSession().getAttribute("mail_verify_code")); 56 | // //构建响应输出流 57 | // response.setContentType("application/json;charset=utf-8"); 58 | // PrintWriter printWriter =response.getWriter(); 59 | // try { 60 | // if(!mailCode.equals(verifyCode)){ 61 | // printWriter.write(new ObjectMapper().writeValueAsString(RespBean.error("验证码错误!"))); 62 | // }else { 63 | // filterChain.doFilter(request,response); 64 | // } 65 | // }catch (NullPointerException e){ 66 | // printWriter.write(new ObjectMapper().writeValueAsString(RespBean.error("请求异常,请重新请求!"))); 67 | // }finally { 68 | // printWriter.flush(); 69 | // printWriter.close(); 70 | // } 71 | // } 72 | else { 73 | filterChain.doFilter(request,response); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 5 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 6 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 7 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 8 | 9 | /** 10 | * @author Hai 11 | * @date 2020/6/16 - 23:31 12 | */ 13 | @Configuration 14 | @EnableWebSocketMessageBroker 15 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 16 | /** 17 | * 注册stomp站点 18 | * @param registry 19 | */ 20 | @Override 21 | public void registerStompEndpoints(StompEndpointRegistry registry) { 22 | 23 | registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS(); 24 | 25 | } 26 | 27 | /** 28 | * 注册拦截"/topic","/queue"的消息 29 | * @param registry 30 | */ 31 | @Override 32 | public void configureMessageBroker(MessageBrokerRegistry registry) { 33 | registry.enableSimpleBroker("/topic","/queue"); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import top.javahai.chatroom.entity.Admin; 4 | import top.javahai.chatroom.service.AdminService; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | import javax.annotation.Resource; 8 | 9 | /** 10 | * (Admin)表控制层 11 | * 12 | * @author makejava 13 | * @since 2020-06-16 11:35:59 14 | */ 15 | @RestController 16 | @RequestMapping("admin") 17 | public class AdminController { 18 | /** 19 | * 服务对象 20 | */ 21 | @Resource 22 | private AdminService adminService; 23 | 24 | /** 25 | * 通过主键查询单条数据 26 | * 27 | * @param id 主键 28 | * @return 单条数据 29 | */ 30 | @GetMapping("selectOne") 31 | public Admin selectOne(Integer id) { 32 | return this.adminService.queryById(id); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/ChatController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | import top.javahai.chatroom.entity.User; 8 | import top.javahai.chatroom.service.UserService; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * @author Hai 14 | * @date 2020/6/16 - 21:32 15 | */ 16 | @RestController 17 | @RequestMapping("/chat") 18 | public class ChatController { 19 | @Autowired 20 | UserService userService; 21 | 22 | @GetMapping("/users") 23 | public List getUsersWithoutCurrentUser(){ 24 | return userService.getUsersWithoutCurrentUser(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/FileController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import org.csource.common.MyException; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestParam; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import org.springframework.web.multipart.MultipartFile; 10 | import top.javahai.chatroom.utils.FastDFSUtil; 11 | import top.javahai.chatroom.utils.AliyunOssUtil; 12 | 13 | import java.io.IOException; 14 | 15 | /** 16 | * @author Hai 17 | * @date 2020/6/21 - 16:47 18 | */ 19 | @RestController 20 | public class FileController { 21 | 22 | @Value("${fastdfs.nginx.host}") 23 | String nginxHost; 24 | 25 | @Autowired 26 | AliyunOssUtil aliyunOssUtil; 27 | 28 | @PostMapping("/file") 29 | public String uploadFlie(MultipartFile file) throws IOException, MyException { 30 | String fileId= FastDFSUtil.upload(file); 31 | return nginxHost+fileId; 32 | } 33 | 34 | @PostMapping("/ossFileUpload") 35 | public String ossFileUpload(@RequestParam("file")MultipartFile file,@RequestParam("module") String module) throws IOException, MyException { 36 | return aliyunOssUtil.upload(file.getInputStream(),module,file.getOriginalFilename()); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/GroupMsgContentController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import top.javahai.chatroom.entity.GroupMsgContent; 4 | import top.javahai.chatroom.entity.RespBean; 5 | import top.javahai.chatroom.entity.RespPageBean; 6 | import top.javahai.chatroom.service.GroupMsgContentService; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | /** 14 | * (GroupMsgContent)表控制层 15 | * 16 | * @author makejava 17 | * @since 2020-06-17 10:51:13 18 | */ 19 | @RestController 20 | @RequestMapping("/groupMsgContent") 21 | public class GroupMsgContentController { 22 | /** 23 | * 服务对象 24 | */ 25 | @Resource 26 | private GroupMsgContentService groupMsgContentService; 27 | 28 | @GetMapping("/") 29 | private List getAllGroupMsgContent(){ 30 | return groupMsgContentService.queryAllByLimit(null,null); 31 | } 32 | 33 | /** 34 | * 通过主键查询单条数据 35 | * 36 | * @param id 主键 37 | * @return 单条数据 38 | */ 39 | @GetMapping("selectOne") 40 | public GroupMsgContent selectOne(Integer id) { 41 | return this.groupMsgContentService.queryById(id); 42 | } 43 | 44 | /** 45 | * 分页返回数据 46 | * @author luo 47 | * @param page 页数 48 | * @param size 单页大小 49 | * @param nickname 发送者昵称 50 | * @param type 消息类型 51 | * @param dateScope 发送时间范围 52 | * @return 53 | */ 54 | @GetMapping("/page") 55 | public RespPageBean getAllGroupMsgContentByPage(@RequestParam(value = "page",defaultValue = "1") Integer page, 56 | @RequestParam(value = "size",defaultValue = "10") Integer size, 57 | String nickname, Integer type, 58 | Date[] dateScope){ 59 | return groupMsgContentService.getAllGroupMsgContentByPage(page,size,nickname,type,dateScope); 60 | } 61 | 62 | /** 63 | * 根据id删除单条记录 64 | * @author luo 65 | * @param id 66 | * @return 67 | */ 68 | @DeleteMapping("/{id}") 69 | public RespBean deleteGroupMsgContentById(@PathVariable Integer id){ 70 | if (groupMsgContentService.deleteById(id)){ 71 | return RespBean.ok("删除成功!"); 72 | }else{ 73 | return RespBean.error("删除失败!"); 74 | } 75 | } 76 | @DeleteMapping("/") 77 | public RespBean deleteGroupMsgContentByIds(Integer[] ids){ 78 | if (groupMsgContentService.deleteGroupMsgContentByIds(ids)==ids.length){ 79 | return RespBean.ok("删除成功!"); 80 | }else { 81 | return RespBean.error("删除失败!"); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.mail.SimpleMailMessage; 5 | import org.springframework.mail.javamail.JavaMailSender; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | import top.javahai.chatroom.config.VerificationCode; 9 | import top.javahai.chatroom.entity.RespBean; 10 | 11 | import javax.servlet.http.HttpServletResponse; 12 | import javax.servlet.http.HttpSession; 13 | import java.awt.image.BufferedImage; 14 | import java.io.IOException; 15 | import java.util.Date; 16 | import java.util.Random; 17 | 18 | /** 19 | * @author Hai 20 | * @date 2020/6/16 - 17:33 21 | */ 22 | @RestController 23 | public class LoginController { 24 | /** 25 | * 获取验证码图片写到响应的输出流中,保存验证码到session 26 | * @param response 27 | * @param session 28 | * @throws IOException 29 | */ 30 | @GetMapping("/verifyCode") 31 | public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException { 32 | VerificationCode code = new VerificationCode(); 33 | BufferedImage image = code.getImage(); 34 | String text = code.getText(); 35 | session.setAttribute("verify_code",text); 36 | VerificationCode.output(image,response.getOutputStream()); 37 | } 38 | 39 | @Autowired 40 | JavaMailSender javaMailSender; 41 | /** 42 | * 获取邮箱验证码,并保存到本次会话 43 | * @param session 44 | */ 45 | @GetMapping("/admin/mailVerifyCode") 46 | public RespBean getMailVerifyCode(HttpSession session){ 47 | //获取随机的四个数字 48 | StringBuilder code=new StringBuilder(); 49 | for (int i = 0; i <4; i++) { 50 | code.append(new Random().nextInt(10)); 51 | } 52 | //邮件内容 53 | SimpleMailMessage msg = new SimpleMailMessage(); 54 | msg.setSubject("微言聊天室管理端验证码验证"); 55 | msg.setText("本次登录的验证码:"+code); 56 | msg.setFrom("发送者的邮箱地址"); 57 | msg.setSentDate(new Date()); 58 | msg.setTo("接受者的邮箱地址"); 59 | //保存验证码到本次会话 60 | session.setAttribute("mail_verify_code",code.toString()); 61 | //发送到邮箱 62 | try { 63 | javaMailSender.send(msg); 64 | return RespBean.ok("验证码已发送到邮箱,请注意查看!"); 65 | }catch (Exception e){ 66 | e.printStackTrace(); 67 | return RespBean.error("服务器出错啦!请稍后重试!"); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/MailController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.mail.SimpleMailMessage; 5 | import org.springframework.mail.javamail.JavaMailSender; 6 | import org.springframework.web.bind.annotation.*; 7 | import top.javahai.chatroom.entity.GroupMsgContent; 8 | import top.javahai.chatroom.entity.RespBean; 9 | 10 | import java.util.Date; 11 | 12 | /** 13 | * 邮箱服务控制器 14 | * @author Hai 15 | * @date 2020/6/29 - 18:42 16 | */ 17 | @RestController 18 | @RequestMapping("/mail") 19 | public class MailController { 20 | 21 | @Autowired 22 | JavaMailSender javaMailSender; 23 | /** 24 | * 发送反馈消息给系统管理员 25 | * @param msg 26 | * @return 27 | */ 28 | @PostMapping("/feedback") 29 | public RespBean sendFeedbackToMail(@RequestBody GroupMsgContent msg){ 30 | SimpleMailMessage message = new SimpleMailMessage(); 31 | message.setSubject("来自用户的意见反馈"); 32 | //读取信息 33 | StringBuilder formatMessage = new StringBuilder(); 34 | formatMessage.append("用户编号:"+msg.getFromId()+"\n"); 35 | formatMessage.append("用户昵称:"+msg.getFromName()+"\n"); 36 | formatMessage.append("反馈内容:"+msg.getContent()); 37 | System.out.println(">>>>>>>>>>>>>>"+formatMessage+"<<<<<<<<<<<<<<<<<<"); 38 | //设置邮件消息 39 | message.setText(formatMessage.toString()); 40 | message.setFrom("1258398543@qq.com"); 41 | message.setTo("jinhaihuang824@aliyun.com"); 42 | message.setSentDate(new Date()); 43 | try { 44 | javaMailSender.send(message); 45 | return RespBean.ok("邮件发送成功!感谢你的反馈~"); 46 | }catch (Exception e){ 47 | return RespBean.error("系统异常,请稍后重试!"); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import org.yaml.snakeyaml.events.Event; 4 | import top.javahai.chatroom.entity.RespBean; 5 | import top.javahai.chatroom.entity.RespPageBean; 6 | import top.javahai.chatroom.entity.User; 7 | import top.javahai.chatroom.service.UserService; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.List; 12 | 13 | /** 14 | * (User)表控制层 15 | * 16 | * @author makejava 17 | * @since 2020-06-16 11:37:09 18 | */ 19 | @RestController 20 | @RequestMapping("/user") 21 | public class UserController { 22 | /** 23 | * 服务对象 24 | */ 25 | @Resource 26 | private UserService userService; 27 | 28 | /** 29 | * 注册操作 30 | */ 31 | @PostMapping("/register") 32 | public RespBean addUser(@RequestBody User user){ 33 | if (userService.insert(user)==1){ 34 | return RespBean.ok("注册成功!"); 35 | }else{ 36 | return RespBean.error("注册失败!"); 37 | } 38 | } 39 | 40 | /** 41 | * 注册操作,检查用户名是否已被注册 42 | * @param username 43 | * @return 44 | */ 45 | @GetMapping("/checkUsername") 46 | public Integer checkUsername(@RequestParam("username")String username){ 47 | return userService.checkUsername(username); 48 | } 49 | 50 | /** 51 | * 注册操作,检查昵称是否已被注册 52 | * @param nickname 53 | * @return 54 | */ 55 | @GetMapping("/checkNickname") 56 | public Integer checkNickname(@RequestParam("nickname") String nickname){ 57 | return userService.checkNickname(nickname); 58 | } 59 | 60 | /** 61 | * 通过主键查询单条数据 62 | * 63 | * @param id 主键 64 | * @return 单条数据 65 | */ 66 | @GetMapping("selectOne") 67 | public User selectOne(Integer id) { 68 | return this.userService.queryById(id); 69 | } 70 | 71 | /** 72 | * @author luo 73 | * @param page 页数,对应数据库查询的起始行数 74 | * @param size 数据量,对应数据库查询的偏移量 75 | * @param keyword 关键词,用于搜索 76 | * @param isLocked 是否锁定,用于搜索 77 | * @return 78 | */ 79 | @GetMapping("/") 80 | public RespPageBean getAllUserByPage(@RequestParam(value = "page",defaultValue = "1") Integer page, 81 | @RequestParam(value = "size",defaultValue = "10") Integer size, 82 | String keyword,Integer isLocked){ 83 | return userService.getAllUserByPage(page,size,keyword,isLocked); 84 | } 85 | 86 | /** 87 | * 更新用户的锁定状态 88 | * @author luo 89 | * @param id 90 | * @param isLocked 91 | * @return 92 | */ 93 | @PutMapping("/") 94 | public RespBean changeLockedStatus(@RequestParam("id") Integer id,@RequestParam("isLocked") Boolean isLocked){ 95 | if (userService.changeLockedStatus(id,isLocked)==1){ 96 | return RespBean.ok("更新成功!"); 97 | }else { 98 | return RespBean.error("更新失败!"); 99 | } 100 | } 101 | 102 | /** 103 | * 删除单一用户 104 | * @author luo 105 | * @param id 106 | * @return 107 | */ 108 | @DeleteMapping("/{id}") 109 | public RespBean deleteUser(@PathVariable Integer id){ 110 | if (userService.deleteById(id)){ 111 | return RespBean.ok("删除成功!"); 112 | } 113 | else{ 114 | return RespBean.error("删除失败!"); 115 | } 116 | } 117 | 118 | /** 119 | * 批量删除用户 120 | * @author luo 121 | * @param ids 122 | * @return 123 | */ 124 | @DeleteMapping("/") 125 | public RespBean deleteUserByIds(Integer[] ids){ 126 | if (userService.deleteByIds(ids)==ids.length){ 127 | return RespBean.ok("删除成功!"); 128 | }else{ 129 | return RespBean.error("删除失败!"); 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/UserStateController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import top.javahai.chatroom.entity.UserState; 4 | import top.javahai.chatroom.service.UserStateService; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | import javax.annotation.Resource; 8 | 9 | /** 10 | * (UserState)表控制层 11 | * 12 | * @author makejava 13 | * @since 2020-06-16 11:36:02 14 | */ 15 | @RestController 16 | @RequestMapping("userState") 17 | public class UserStateController { 18 | /** 19 | * 服务对象 20 | */ 21 | @Resource 22 | private UserStateService userStateService; 23 | 24 | /** 25 | * 通过主键查询单条数据 26 | * 27 | * @param id 主键 28 | * @return 单条数据 29 | */ 30 | @GetMapping("selectOne") 31 | public UserState selectOne(Integer id) { 32 | return this.userStateService.queryById(id); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/controller/WsController.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.controller; 2 | 3 | import com.github.binarywang.java.emoji.EmojiConverter; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.messaging.handler.annotation.MessageMapping; 6 | import org.springframework.messaging.simp.SimpMessagingTemplate; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.stereotype.Controller; 9 | import top.javahai.chatroom.entity.GroupMsgContent; 10 | import top.javahai.chatroom.entity.Message; 11 | import top.javahai.chatroom.entity.User; 12 | import top.javahai.chatroom.service.GroupMsgContentService; 13 | import top.javahai.chatroom.utils.TuLingUtil; 14 | 15 | import java.io.IOException; 16 | import java.text.SimpleDateFormat; 17 | import java.util.Date; 18 | 19 | /** 20 | * @author Hai 21 | * @date 2020/6/16 - 23:34 22 | */ 23 | @Controller 24 | public class WsController { 25 | @Autowired 26 | SimpMessagingTemplate simpMessagingTemplate; 27 | 28 | /** 29 | * 单聊的消息的接受与转发 30 | * @param authentication 31 | * @param message 32 | */ 33 | @MessageMapping("/ws/chat") 34 | public void handleMessage(Authentication authentication, Message message){ 35 | User user= ((User) authentication.getPrincipal()); 36 | message.setFromNickname(user.getNickname()); 37 | message.setFrom(user.getUsername()); 38 | message.setCreateTime(new Date()); 39 | simpMessagingTemplate.convertAndSendToUser(message.getTo(),"/queue/chat",message); 40 | } 41 | 42 | @Autowired 43 | GroupMsgContentService groupMsgContentService; 44 | EmojiConverter emojiConverter = EmojiConverter.getInstance(); 45 | 46 | SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 47 | /** 48 | * 群聊的消息接受与转发 49 | * @param authentication 50 | * @param groupMsgContent 51 | */ 52 | @MessageMapping("/ws/groupChat") 53 | public void handleGroupMessage(Authentication authentication, GroupMsgContent groupMsgContent){ 54 | User currentUser= (User) authentication.getPrincipal(); 55 | //处理emoji内容,转换成unicode编码 56 | groupMsgContent.setContent(emojiConverter.toHtml(groupMsgContent.getContent())); 57 | //保证来源正确性,从Security中获取用户信息 58 | groupMsgContent.setFromId(currentUser.getId()); 59 | groupMsgContent.setFromName(currentUser.getNickname()); 60 | groupMsgContent.setFromProfile(currentUser.getUserProfile()); 61 | groupMsgContent.setCreateTime(new Date()); 62 | //保存该条群聊消息记录到数据库中 63 | groupMsgContentService.insert(groupMsgContent); 64 | //转发该条数据 65 | simpMessagingTemplate.convertAndSend("/topic/greetings",groupMsgContent); 66 | } 67 | 68 | /** 69 | * 接受前端发来的消息,获得图灵机器人回复并转发回给发送者 70 | * @param authentication 71 | * @param message 72 | * @throws IOException 73 | */ 74 | @MessageMapping("/ws/robotChat") 75 | public void handleRobotChatMessage(Authentication authentication, Message message) throws IOException { 76 | User user = ((User) authentication.getPrincipal()); 77 | //接收到的消息 78 | message.setFrom(user.getUsername()); 79 | message.setCreateTime(new Date()); 80 | message.setFromNickname(user.getNickname()); 81 | message.setFromUserProfile(user.getUserProfile()); 82 | //发送消息内容给机器人,获得回复 83 | String result = TuLingUtil.replyMessage(message.getContent()); 84 | //构建返回消息JSON字符串 85 | Message resultMessage = new Message(); 86 | resultMessage.setFrom("瓦力"); 87 | resultMessage.setCreateTime(new Date()); 88 | resultMessage.setFromNickname("瓦力"); 89 | resultMessage.setContent(result); 90 | //回送机器人回复的消息给发送者 91 | simpMessagingTemplate.convertAndSendToUser(message.getFrom(),"/queue/robot",resultMessage); 92 | 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/converter/DateConverter.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.converter; 2 | 3 | import org.springframework.core.convert.converter.Converter; 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.text.ParseException; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | /** 11 | * @author Hai 12 | * @date 2020/6/23 - 16:28 13 | */ 14 | @Component 15 | public class DateConverter implements Converter { 16 | 17 | SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 18 | @Override 19 | public Date convert(String s) { 20 | Date date = null; 21 | if (s!=null&&!"".equals(s)){ 22 | try { 23 | date= simpleDateFormat.parse(s); 24 | } catch (ParseException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | return date; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/dao/AdminDao.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.dao; 2 | 3 | import top.javahai.chatroom.entity.Admin; 4 | import org.apache.ibatis.annotations.Param; 5 | import java.util.List; 6 | 7 | /** 8 | * (Admin)表数据库访问层 9 | * 10 | * @author makejava 11 | * @since 2020-06-16 11:35:57 12 | */ 13 | public interface AdminDao { 14 | 15 | 16 | Admin loadUserByUsername(String username); 17 | 18 | /** 19 | * 通过ID查询单条数据 20 | * 21 | * @param id 主键 22 | * @return 实例对象 23 | */ 24 | Admin queryById(Integer id); 25 | 26 | /** 27 | * 查询指定行数据 28 | * 29 | * @param offset 查询起始位置 30 | * @param limit 查询条数 31 | * @return 对象列表 32 | */ 33 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 34 | 35 | 36 | /** 37 | * 通过实体作为筛选条件查询 38 | * 39 | * @param admin 实例对象 40 | * @return 对象列表 41 | */ 42 | List queryAll(Admin admin); 43 | 44 | /** 45 | * 新增数据 46 | * 47 | * @param admin 实例对象 48 | * @return 影响行数 49 | */ 50 | int insert(Admin admin); 51 | 52 | /** 53 | * 修改数据 54 | * 55 | * @param admin 实例对象 56 | * @return 影响行数 57 | */ 58 | int update(Admin admin); 59 | 60 | /** 61 | * 通过主键删除数据 62 | * 63 | * @param id 主键 64 | * @return 影响行数 65 | */ 66 | int deleteById(Integer id); 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/dao/GroupMsgContentDao.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.dao; 2 | 3 | import top.javahai.chatroom.entity.GroupMsgContent; 4 | import org.apache.ibatis.annotations.Param; 5 | import top.javahai.chatroom.entity.RespPageBean; 6 | 7 | import java.util.Date; 8 | import java.util.List; 9 | 10 | /** 11 | * (GroupMsgContent)表数据库访问层 12 | * 13 | * @author makejava 14 | * @since 2020-06-17 10:51:13 15 | */ 16 | public interface GroupMsgContentDao { 17 | 18 | /** 19 | * 通过ID查询单条数据 20 | * 21 | * @param id 主键 22 | * @return 实例对象 23 | */ 24 | GroupMsgContent queryById(Integer id); 25 | 26 | /** 27 | * 查询指定行数据 28 | * 29 | * @param offset 查询起始位置 30 | * @param limit 查询条数 31 | * @return 对象列表 32 | */ 33 | List queryAllByLimit(@Param("offset") Integer offset, @Param("limit") Integer limit); 34 | 35 | 36 | /** 37 | * 通过实体作为筛选条件查询 38 | * 39 | * @param groupMsgContent 实例对象 40 | * @return 对象列表 41 | */ 42 | List queryAll(GroupMsgContent groupMsgContent); 43 | 44 | /** 45 | * 新增数据 46 | * 47 | * @param groupMsgContent 实例对象 48 | * @return 影响行数 49 | */ 50 | int insert(GroupMsgContent groupMsgContent); 51 | 52 | /** 53 | * 修改数据 54 | * 55 | * @param groupMsgContent 实例对象 56 | * @return 影响行数 57 | */ 58 | int update(GroupMsgContent groupMsgContent); 59 | 60 | /** 61 | * 通过主键删除数据 62 | * 63 | * @param id 主键 64 | * @return 影响行数 65 | */ 66 | int deleteById(Integer id); 67 | 68 | List getAllGroupMsgContentByPage(@Param("page") Integer page, 69 | @Param("size") Integer size, 70 | @Param("nickname") String nickname, 71 | @Param("type") Integer type, 72 | @Param("dateScope") Date[] dateScope); 73 | 74 | Long getTotal(@Param("nickname") String nickname, 75 | @Param("type") Integer type, 76 | @Param("dateScope") Date[] dateScope); 77 | 78 | Integer deleteGroupMsgContentByIds(@Param("ids") Integer[] ids); 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.dao; 2 | 3 | import org.yaml.snakeyaml.events.Event; 4 | import top.javahai.chatroom.entity.User; 5 | import org.apache.ibatis.annotations.Param; 6 | import java.util.List; 7 | 8 | /** 9 | * (User)表数据库访问层 10 | * 11 | * @author makejava 12 | * @since 2020-06-16 12:06:29 13 | */ 14 | public interface UserDao { 15 | 16 | /** 17 | * 根据用户名查询用户对象 18 | * @param username 19 | * @return 20 | */ 21 | User loadUserByUsername(String username); 22 | 23 | 24 | /** 25 | * 获取除当前用户的所有用户 26 | * @param id 27 | * @return 28 | */ 29 | List getUsersWithoutCurrentUser(Integer id); 30 | 31 | /** 32 | * 通过ID查询单条数据 33 | * 34 | * @param id 主键 35 | * @return 实例对象 36 | */ 37 | User queryById(Integer id); 38 | 39 | /** 40 | * 查询指定行数据 41 | * 42 | * @param offset 查询起始位置 43 | * @param limit 查询条数 44 | * @return 对象列表 45 | */ 46 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 47 | 48 | 49 | /** 50 | * 通过实体作为筛选条件查询 51 | * 52 | * @param user 实例对象 53 | * @return 对象列表 54 | */ 55 | List queryAll(User user); 56 | 57 | /** 58 | * 新增数据 59 | * 60 | * @param user 实例对象 61 | * @return 影响行数 62 | */ 63 | int insert(User user); 64 | 65 | /** 66 | * 修改数据 67 | * 68 | * @param user 实例对象 69 | * @return 影响行数 70 | */ 71 | int update(User user); 72 | 73 | /** 74 | * 通过主键删除数据 75 | * 76 | * @param id 主键 77 | * @return 影响行数 78 | */ 79 | int deleteById(Integer id); 80 | 81 | void setUserStateToOn(Integer id); 82 | 83 | void setUserStateToLeave(Integer id); 84 | 85 | Integer checkUsername(String username); 86 | 87 | Integer checkNickname(String nickname); 88 | 89 | List getAllUserByPage(@Param("page") Integer page, @Param("size") Integer size,String keyword,Integer isLocked); 90 | 91 | Long getTotal(@Param("keyword") String keyword,@Param("isLocked") Integer isLocked); 92 | 93 | Integer changeLockedStatus(@Param("id") Integer id, @Param("isLocked") Boolean isLocked); 94 | 95 | Integer deleteByIds(@Param("ids") Integer[] ids); 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/dao/UserStateDao.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.dao; 2 | 3 | import top.javahai.chatroom.entity.UserState; 4 | import org.apache.ibatis.annotations.Param; 5 | import java.util.List; 6 | 7 | /** 8 | * (UserState)表数据库访问层 9 | * 10 | * @author makejava 11 | * @since 2020-06-16 11:36:02 12 | */ 13 | public interface UserStateDao { 14 | 15 | /** 16 | * 通过ID查询单条数据 17 | * 18 | * @param id 主键 19 | * @return 实例对象 20 | */ 21 | UserState queryById(Integer id); 22 | 23 | /** 24 | * 查询指定行数据 25 | * 26 | * @param offset 查询起始位置 27 | * @param limit 查询条数 28 | * @return 对象列表 29 | */ 30 | List queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); 31 | 32 | 33 | /** 34 | * 通过实体作为筛选条件查询 35 | * 36 | * @param userState 实例对象 37 | * @return 对象列表 38 | */ 39 | List queryAll(UserState userState); 40 | 41 | /** 42 | * 新增数据 43 | * 44 | * @param userState 实例对象 45 | * @return 影响行数 46 | */ 47 | int insert(UserState userState); 48 | 49 | /** 50 | * 修改数据 51 | * 52 | * @param userState 实例对象 53 | * @return 影响行数 54 | */ 55 | int update(UserState userState); 56 | 57 | /** 58 | * 通过主键删除数据 59 | * 60 | * @param id 主键 61 | * @return 影响行数 62 | */ 63 | int deleteById(Integer id); 64 | 65 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/Admin.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | 6 | import java.io.Serializable; 7 | import java.util.Collection; 8 | 9 | /** 10 | * (Admin)实体类 11 | * 12 | * @author makejava 13 | * @since 2020-06-16 11:35:56 14 | */ 15 | public class Admin implements Serializable, UserDetails { 16 | private static final long serialVersionUID = -75235725571250857L; 17 | 18 | private Integer id; 19 | /** 20 | * 登录账号 21 | */ 22 | private String username; 23 | /** 24 | * 昵称 25 | */ 26 | private String nickname; 27 | /** 28 | * 密码 29 | */ 30 | private String password; 31 | /** 32 | * 管理员头像 33 | */ 34 | private String userProfile; 35 | 36 | 37 | public Integer getId() { 38 | return id; 39 | } 40 | 41 | public void setId(Integer id) { 42 | this.id = id; 43 | } 44 | 45 | public String getUsername() { 46 | return username; 47 | } 48 | 49 | @Override 50 | public boolean isAccountNonExpired() { 51 | return true; 52 | } 53 | 54 | @Override 55 | public boolean isAccountNonLocked() { 56 | return true; 57 | } 58 | 59 | @Override 60 | public boolean isCredentialsNonExpired() { 61 | return true; 62 | } 63 | 64 | @Override 65 | public boolean isEnabled() { 66 | return true; 67 | } 68 | 69 | public void setUsername(String username) { 70 | this.username = username; 71 | } 72 | 73 | public String getNickname() { 74 | return nickname; 75 | } 76 | 77 | public void setNickname(String nickname) { 78 | this.nickname = nickname; 79 | } 80 | 81 | @Override 82 | public Collection getAuthorities() { 83 | return null; 84 | } 85 | 86 | public String getPassword() { 87 | return password; 88 | } 89 | 90 | public void setPassword(String password) { 91 | this.password = password; 92 | } 93 | 94 | public String getUserProfile() { 95 | return userProfile; 96 | } 97 | 98 | public void setUserProfile(String userProfile) { 99 | this.userProfile = userProfile; 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/GroupMsgContent.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.util.Date; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * (GroupMsgContent)实体类 10 | * 11 | * @author makejava 12 | * @since 2020-06-17 10:46:50 13 | */ 14 | public class GroupMsgContent implements Serializable { 15 | private static final long serialVersionUID = 980328865610261046L; 16 | /** 17 | * 消息内容编号 18 | */ 19 | private Integer id; 20 | /** 21 | * 发送者的编号 22 | */ 23 | private Integer fromId; 24 | /** 25 | * 发送者的昵称 26 | */ 27 | private String fromName; 28 | /** 29 | * 发送者的头像 30 | */ 31 | private String fromProfile; 32 | /** 33 | * 消息发送时间 34 | */ 35 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 36 | private Date createTime; 37 | /** 38 | * 消息内容 39 | */ 40 | private String content; 41 | /** 42 | * 消息类型编号 43 | */ 44 | private Integer messageTypeId; 45 | 46 | 47 | public Integer getId() { 48 | return id; 49 | } 50 | 51 | public void setId(Integer id) { 52 | this.id = id; 53 | } 54 | 55 | public Integer getFromId() { 56 | return fromId; 57 | } 58 | 59 | public void setFromId(Integer fromId) { 60 | this.fromId = fromId; 61 | } 62 | 63 | public String getFromName() { 64 | return fromName; 65 | } 66 | 67 | public void setFromName(String fromName) { 68 | this.fromName = fromName; 69 | } 70 | 71 | public String getFromProfile() { 72 | return fromProfile; 73 | } 74 | 75 | public void setFromProfile(String fromProfile) { 76 | this.fromProfile = fromProfile; 77 | } 78 | 79 | public Date getCreateTime() { 80 | return createTime; 81 | } 82 | 83 | public void setCreateTime(Date createTime) { 84 | this.createTime = createTime; 85 | } 86 | 87 | public String getContent() { 88 | return content; 89 | } 90 | 91 | public void setContent(String content) { 92 | this.content = content; 93 | } 94 | 95 | public Integer getMessageTypeId() { 96 | return messageTypeId; 97 | } 98 | 99 | public void setMessageTypeId(Integer messageTypeId) { 100 | this.messageTypeId = messageTypeId; 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "GroupMsgContent{" + 106 | "id=" + id + 107 | ", fromId=" + fromId + 108 | ", fromName='" + fromName + '\'' + 109 | ", fromProfile='" + fromProfile + '\'' + 110 | ", createTime=" + createTime + 111 | ", content='" + content + '\'' + 112 | ", messageTypeId=" + messageTypeId + 113 | '}'; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/Message.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * 单聊的消息实体 7 | * @author Hai 8 | * @date 2020/6/25 - 19:32 9 | */ 10 | public class Message { 11 | private String from; 12 | private String to; 13 | private String content; 14 | private Date createTime; 15 | private String fromNickname; 16 | private String fromUserProfile; 17 | private Integer messageTypeId; 18 | 19 | public String getFrom() { 20 | return from; 21 | } 22 | 23 | public void setFrom(String from) { 24 | this.from = from; 25 | } 26 | 27 | public String getTo() { 28 | return to; 29 | } 30 | 31 | public void setTo(String to) { 32 | this.to = to; 33 | } 34 | 35 | public String getContent() { 36 | return content; 37 | } 38 | 39 | public void setContent(String content) { 40 | this.content = content; 41 | } 42 | 43 | public Date getCreateTime() { 44 | return createTime; 45 | } 46 | 47 | public void setCreateTime(Date createTime) { 48 | this.createTime = createTime; 49 | } 50 | 51 | public String getFromNickname() { 52 | return fromNickname; 53 | } 54 | 55 | public void setFromNickname(String fromNickname) { 56 | this.fromNickname = fromNickname; 57 | } 58 | 59 | public String getFromUserProfile() { 60 | return fromUserProfile; 61 | } 62 | 63 | public void setFromUserProfile(String fromUserProfile) { 64 | this.fromUserProfile = fromUserProfile; 65 | } 66 | 67 | public Integer getMessageTypeId() { 68 | return messageTypeId; 69 | } 70 | 71 | public void setMessageTypeId(Integer messageTypeId) { 72 | this.messageTypeId = messageTypeId; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/RespBean.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | /** 4 | * @author Hai 5 | * @date 2020/4/19 - 23:23 6 | */ 7 | //JSON返回值的实体类 8 | public class RespBean { 9 | private Integer status;//状态码 10 | private String msg;//返回消息 11 | private Object obj;//返回实体 12 | 13 | public static RespBean build(){ 14 | return new RespBean(); 15 | } 16 | 17 | public static RespBean ok(String msg){ 18 | return new RespBean(200,msg,null); 19 | } 20 | public static RespBean ok(String msg,Object obj){ 21 | return new RespBean(200,msg,obj); 22 | } 23 | 24 | public static RespBean error(String msg){ 25 | return new RespBean(500,msg,null); 26 | } 27 | public static RespBean error(String msg,Object obj){ 28 | return new RespBean(500,msg,obj); 29 | } 30 | 31 | private RespBean(){ 32 | 33 | } 34 | 35 | private RespBean(Integer status, String msg, Object obj) { 36 | this.status = status; 37 | this.msg = msg; 38 | this.obj = obj; 39 | } 40 | 41 | public Integer getStatus() { 42 | return status; 43 | } 44 | 45 | public RespBean setStatus(Integer status) { 46 | this.status = status; 47 | return this; 48 | } 49 | 50 | public String getMsg() { 51 | return msg; 52 | } 53 | 54 | public RespBean setMsg(String msg) { 55 | this.msg = msg; 56 | return this; 57 | } 58 | 59 | public Object getObj() { 60 | return obj; 61 | } 62 | 63 | public RespBean setObj(Object obj) { 64 | this.obj = obj; 65 | return this; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/RespPageBean.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author luo 7 | * @date 2020/6/22 - 19:18 8 | */ 9 | public class RespPageBean { 10 | private Long total;//数据总数 11 | private List data;//数据实体列表 12 | 13 | public Long getTotal() { 14 | return total; 15 | } 16 | 17 | public void setTotal(Long total) { 18 | this.total = total; 19 | } 20 | 21 | public List getData() { 22 | return data; 23 | } 24 | 25 | public void setData(List data) { 26 | this.data = data; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/User.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | 6 | import java.util.Collection; 7 | 8 | /** 9 | * (User)实体类 10 | * 11 | * @author makejava 12 | * @since 2020-06-16 12:08:01 13 | */ 14 | public class User implements UserDetails { 15 | 16 | private Integer id; 17 | /** 18 | * 登录账号 19 | */ 20 | private String username; 21 | /** 22 | * 昵称 23 | */ 24 | private String nickname; 25 | /** 26 | * 密码 27 | */ 28 | private String password; 29 | /** 30 | * 用户头像 31 | */ 32 | private String userProfile; 33 | /** 34 | * 用户状态id 35 | */ 36 | private Integer userStateId; 37 | /** 38 | * 是否可用 39 | */ 40 | private Boolean isEnabled; 41 | /** 42 | * 是否被锁定 43 | */ 44 | private Boolean isLocked; 45 | 46 | 47 | public Integer getId() { 48 | return id; 49 | } 50 | 51 | public void setId(Integer id) { 52 | this.id = id; 53 | } 54 | 55 | public String getUsername() { 56 | return username; 57 | } 58 | 59 | //账号是否未过期 60 | @Override 61 | public boolean isAccountNonExpired() { 62 | return true; 63 | } 64 | 65 | //账号是否不锁定 66 | @Override 67 | public boolean isAccountNonLocked() { 68 | return !isLocked; 69 | } 70 | 71 | @Override 72 | public boolean isCredentialsNonExpired() { 73 | return true; 74 | } 75 | 76 | @Override 77 | public boolean isEnabled() { 78 | return isEnabled; 79 | } 80 | 81 | public void setUsername(String username) { 82 | this.username = username; 83 | } 84 | 85 | public String getNickname() { 86 | return nickname; 87 | } 88 | 89 | public void setNickname(String nickname) { 90 | this.nickname = nickname; 91 | } 92 | 93 | /** 94 | * 获取用户拥有的所有角色 95 | * @return 96 | */ 97 | @Override 98 | public Collection getAuthorities() { 99 | return null; 100 | } 101 | 102 | public String getPassword() { 103 | return password; 104 | } 105 | 106 | public void setPassword(String password) { 107 | this.password = password; 108 | } 109 | 110 | public String getUserProfile() { 111 | return userProfile; 112 | } 113 | 114 | public void setUserProfile(String userProfile) { 115 | this.userProfile = userProfile; 116 | } 117 | 118 | public Integer getUserStateId() { 119 | return userStateId; 120 | } 121 | 122 | public void setUserStateId(Integer userStateId) { 123 | this.userStateId = userStateId; 124 | } 125 | 126 | 127 | public void setEnabled(Boolean enabled) { 128 | isEnabled = enabled; 129 | } 130 | 131 | public void setLocked(Boolean locked) { 132 | isLocked = locked; 133 | } 134 | 135 | @Override 136 | public String toString() { 137 | return "User{" + 138 | "id=" + id + 139 | ", username='" + username + '\'' + 140 | ", nickname='" + nickname + '\'' + 141 | ", password='" + password + '\'' + 142 | ", userProfile='" + userProfile + '\'' + 143 | ", userStateId=" + userStateId + 144 | ", isEnabled=" + isEnabled + 145 | ", isLocked=" + isLocked + 146 | '}'; 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/entity/UserState.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * (UserState)实体类 7 | * 8 | * @author makejava 9 | * @since 2020-06-16 11:36:02 10 | */ 11 | public class UserState implements Serializable { 12 | private static final long serialVersionUID = -38130170610280885L; 13 | 14 | private Integer id; 15 | /** 16 | * 状态名 17 | */ 18 | private String name; 19 | 20 | 21 | public Integer getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Integer id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.exception; 2 | 3 | import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; 4 | import org.springframework.web.bind.annotation.ExceptionHandler; 5 | import org.springframework.web.bind.annotation.RestControllerAdvice; 6 | import top.javahai.chatroom.entity.RespBean; 7 | 8 | import java.sql.SQLException; 9 | 10 | /** 11 | * @author Hai 12 | * @date 2020/4/27 - 19:49 13 | * 功能:全局异常处理类 14 | */ 15 | @RestControllerAdvice 16 | public class GlobalExceptionHandler { 17 | 18 | /* 19 | 处理SQLException异常 20 | */ 21 | @ExceptionHandler(SQLException.class) 22 | public RespBean sqlExceptionHandler(SQLException e){ 23 | if (e instanceof MySQLIntegrityConstraintViolationException){ 24 | return RespBean.error("该数据与其他数据存在关联,无法删除!"); 25 | } 26 | else { 27 | e.printStackTrace(); 28 | return RespBean.error("数据库异常,操作失败!"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/AdminService.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service; 2 | 3 | import top.javahai.chatroom.entity.Admin; 4 | import java.util.List; 5 | 6 | /** 7 | * (Admin)表服务接口 8 | * 9 | * @author makejava 10 | * @since 2020-06-16 11:35:58 11 | */ 12 | public interface AdminService { 13 | 14 | /** 15 | * 通过ID查询单条数据 16 | * 17 | * @param id 主键 18 | * @return 实例对象 19 | */ 20 | Admin queryById(Integer id); 21 | 22 | /** 23 | * 查询多条数据 24 | * 25 | * @param offset 查询起始位置 26 | * @param limit 查询条数 27 | * @return 对象列表 28 | */ 29 | List queryAllByLimit(int offset, int limit); 30 | 31 | /** 32 | * 新增数据 33 | * 34 | * @param admin 实例对象 35 | * @return 实例对象 36 | */ 37 | Admin insert(Admin admin); 38 | 39 | /** 40 | * 修改数据 41 | * 42 | * @param admin 实例对象 43 | * @return 实例对象 44 | */ 45 | Admin update(Admin admin); 46 | 47 | /** 48 | * 通过主键删除数据 49 | * 50 | * @param id 主键 51 | * @return 是否成功 52 | */ 53 | boolean deleteById(Integer id); 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/GroupMsgContentService.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service; 2 | 3 | import top.javahai.chatroom.entity.GroupMsgContent; 4 | import top.javahai.chatroom.entity.RespPageBean; 5 | 6 | import java.util.Date; 7 | import java.util.List; 8 | 9 | /** 10 | * (GroupMsgContent)表服务接口 11 | * 12 | * @author makejava 13 | * @since 2020-06-17 10:51:13 14 | */ 15 | public interface GroupMsgContentService { 16 | 17 | /** 18 | * 通过ID查询单条数据 19 | * 20 | * @param id 主键 21 | * @return 实例对象 22 | */ 23 | GroupMsgContent queryById(Integer id); 24 | 25 | /** 26 | * 查询多条数据 27 | * 28 | * @param offset 查询起始位置 29 | * @param limit 查询条数 30 | * @return 对象列表 31 | */ 32 | List queryAllByLimit(Integer offset, Integer limit); 33 | 34 | /** 35 | * 新增数据 36 | * 37 | * @param groupMsgContent 实例对象 38 | * @return 实例对象 39 | */ 40 | GroupMsgContent insert(GroupMsgContent groupMsgContent); 41 | 42 | /** 43 | * 修改数据 44 | * 45 | * @param groupMsgContent 实例对象 46 | * @return 实例对象 47 | */ 48 | GroupMsgContent update(GroupMsgContent groupMsgContent); 49 | 50 | /** 51 | * 通过主键删除数据 52 | * 53 | * @param id 主键 54 | * @return 是否成功 55 | */ 56 | boolean deleteById(Integer id); 57 | 58 | RespPageBean getAllGroupMsgContentByPage(Integer page, Integer size, String nickname, Integer type, Date[] dateScope); 59 | 60 | Integer deleteGroupMsgContentByIds(Integer[] ids); 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/UserService.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service; 2 | 3 | import top.javahai.chatroom.entity.RespBean; 4 | import top.javahai.chatroom.entity.RespPageBean; 5 | import top.javahai.chatroom.entity.User; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * (User)表服务接口 11 | * 12 | * @author makejava 13 | * @since 2020-06-16 11:37:09 14 | */ 15 | public interface UserService { 16 | 17 | 18 | /** 19 | * 获取除了当前登录用户的所有user表的数据 20 | * @return 21 | */ 22 | List getUsersWithoutCurrentUser(); 23 | 24 | /** 25 | * 设置用户当前状态为在线 26 | * @param id 用户id 27 | */ 28 | public void setUserStateToOn(Integer id); 29 | 30 | /** 31 | * 设置用户当前状态为离线 32 | * @param id 33 | */ 34 | public void setUserStateToLeave(Integer id); 35 | 36 | /** 37 | * 通过ID查询单条数据 38 | * 39 | * @param id 主键 40 | * @return 实例对象 41 | */ 42 | User queryById(Integer id); 43 | 44 | /** 45 | * 查询多条数据 46 | * 47 | * @param offset 查询起始位置 48 | * @param limit 查询条数 49 | * @return 对象列表 50 | */ 51 | List queryAllByLimit(int offset, int limit); 52 | 53 | /** 54 | * 新增数据 55 | * 56 | * @param user 实例对象 57 | * @return 实例对象 58 | */ 59 | Integer insert(User user); 60 | 61 | /** 62 | * 修改数据 63 | * 64 | * @param user 实例对象 65 | * @return 实例对象 66 | */ 67 | Integer update(User user); 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | boolean deleteById(Integer id); 76 | 77 | /** 78 | * 检查用户名是否已存在 79 | * @param username 80 | * @return 81 | */ 82 | Integer checkUsername(String username); 83 | 84 | /** 85 | * 检查昵称是否存在 86 | * @param nickname 87 | * @return 88 | */ 89 | Integer checkNickname(String nickname); 90 | 91 | RespPageBean getAllUserByPage(Integer page, Integer size, String keyword,Integer isLocked); 92 | 93 | Integer changeLockedStatus(Integer id, Boolean isLocked); 94 | 95 | Integer deleteByIds(Integer[] ids); 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/UserStateService.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service; 2 | 3 | import top.javahai.chatroom.entity.UserState; 4 | import java.util.List; 5 | 6 | /** 7 | * (UserState)表服务接口 8 | * 9 | * @author makejava 10 | * @since 2020-06-16 11:36:02 11 | */ 12 | public interface UserStateService { 13 | 14 | /** 15 | * 通过ID查询单条数据 16 | * 17 | * @param id 主键 18 | * @return 实例对象 19 | */ 20 | UserState queryById(Integer id); 21 | 22 | /** 23 | * 查询多条数据 24 | * 25 | * @param offset 查询起始位置 26 | * @param limit 查询条数 27 | * @return 对象列表 28 | */ 29 | List queryAllByLimit(int offset, int limit); 30 | 31 | /** 32 | * 新增数据 33 | * 34 | * @param userState 实例对象 35 | * @return 实例对象 36 | */ 37 | UserState insert(UserState userState); 38 | 39 | /** 40 | * 修改数据 41 | * 42 | * @param userState 实例对象 43 | * @return 实例对象 44 | */ 45 | UserState update(UserState userState); 46 | 47 | /** 48 | * 通过主键删除数据 49 | * 50 | * @param id 主键 51 | * @return 是否成功 52 | */ 53 | boolean deleteById(Integer id); 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/impl/AdminServiceImpl.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service.impl; 2 | 3 | import org.springframework.security.core.userdetails.UserDetails; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import top.javahai.chatroom.entity.Admin; 7 | import top.javahai.chatroom.dao.AdminDao; 8 | import top.javahai.chatroom.service.AdminService; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.annotation.Resource; 12 | import java.util.List; 13 | 14 | /** 15 | * (Admin)表服务实现类 16 | * 17 | * @author makejava 18 | * @since 2020-06-16 11:35:58 19 | */ 20 | @Service("adminService") 21 | public class AdminServiceImpl implements AdminService, UserDetailsService { 22 | @Resource 23 | private AdminDao adminDao; 24 | 25 | /** 26 | * 根据用户名进行登录 27 | * @param username 28 | * @return 29 | * @throws UsernameNotFoundException 30 | */ 31 | @Override 32 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 33 | Admin admin=adminDao.loadUserByUsername(username); 34 | if (admin==null){ 35 | throw new UsernameNotFoundException("找不到该管理员"); 36 | } 37 | return admin; 38 | } 39 | /** 40 | * 通过ID查询单条数据 41 | * 42 | * @param id 主键 43 | * @return 实例对象 44 | */ 45 | @Override 46 | public Admin queryById(Integer id) { 47 | return this.adminDao.queryById(id); 48 | } 49 | 50 | /** 51 | * 查询多条数据 52 | * 53 | * @param offset 查询起始位置 54 | * @param limit 查询条数 55 | * @return 对象列表 56 | */ 57 | @Override 58 | public List queryAllByLimit(int offset, int limit) { 59 | return this.adminDao.queryAllByLimit(offset, limit); 60 | } 61 | 62 | /** 63 | * 新增数据 64 | * 65 | * @param admin 实例对象 66 | * @return 实例对象 67 | */ 68 | @Override 69 | public Admin insert(Admin admin) { 70 | this.adminDao.insert(admin); 71 | return admin; 72 | } 73 | 74 | /** 75 | * 修改数据 76 | * 77 | * @param admin 实例对象 78 | * @return 实例对象 79 | */ 80 | @Override 81 | public Admin update(Admin admin) { 82 | this.adminDao.update(admin); 83 | return this.queryById(admin.getId()); 84 | } 85 | 86 | /** 87 | * 通过主键删除数据 88 | * 89 | * @param id 主键 90 | * @return 是否成功 91 | */ 92 | @Override 93 | public boolean deleteById(Integer id) { 94 | return this.adminDao.deleteById(id) > 0; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/impl/GroupMsgContentServiceImpl.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service.impl; 2 | 3 | import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ; 4 | import top.javahai.chatroom.entity.GroupMsgContent; 5 | import top.javahai.chatroom.dao.GroupMsgContentDao; 6 | import top.javahai.chatroom.entity.RespPageBean; 7 | import top.javahai.chatroom.service.GroupMsgContentService; 8 | import org.springframework.stereotype.Service; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | /** 15 | * (GroupMsgContent)表服务实现类 16 | * 17 | * @author makejava 18 | * @since 2020-06-17 10:51:13 19 | */ 20 | @Service("groupMsgContentService") 21 | public class GroupMsgContentServiceImpl implements GroupMsgContentService { 22 | @Resource 23 | private GroupMsgContentDao groupMsgContentDao; 24 | 25 | /** 26 | * 通过ID查询单条数据 27 | * 28 | * @param id 主键 29 | * @return 实例对象 30 | */ 31 | @Override 32 | public GroupMsgContent queryById(Integer id) { 33 | return this.groupMsgContentDao.queryById(id); 34 | } 35 | 36 | /** 37 | * 查询多条数据 38 | * 39 | * @param offset 查询起始位置 40 | * @param limit 查询条数 41 | * @return 对象列表 42 | */ 43 | @Override 44 | public List queryAllByLimit(Integer offset, Integer limit) { 45 | return this.groupMsgContentDao.queryAllByLimit(offset, limit); 46 | } 47 | 48 | /** 49 | * 新增数据 50 | * 51 | * @param groupMsgContent 实例对象 52 | * @return 实例对象 53 | */ 54 | @Override 55 | public GroupMsgContent insert(GroupMsgContent groupMsgContent) { 56 | this.groupMsgContentDao.insert(groupMsgContent); 57 | return groupMsgContent; 58 | } 59 | 60 | /** 61 | * 修改数据 62 | * 63 | * @param groupMsgContent 实例对象 64 | * @return 实例对象 65 | */ 66 | @Override 67 | public GroupMsgContent update(GroupMsgContent groupMsgContent) { 68 | this.groupMsgContentDao.update(groupMsgContent); 69 | return this.queryById(groupMsgContent.getId()); 70 | } 71 | 72 | /** 73 | * 通过主键删除数据 74 | * 75 | * @param id 主键 76 | * @return 是否成功 77 | */ 78 | @Override 79 | public boolean deleteById(Integer id) { 80 | return this.groupMsgContentDao.deleteById(id) > 0; 81 | } 82 | 83 | @Override 84 | public RespPageBean getAllGroupMsgContentByPage(Integer page, Integer size, String nickname, Integer type, Date[] dateScope) { 85 | if (page!=null&&size!=null){ 86 | page=(page-1)*size; 87 | } 88 | List allGroupMsgContentByPage = groupMsgContentDao.getAllGroupMsgContentByPage(page, size, nickname, type, dateScope); 89 | Long total=groupMsgContentDao.getTotal(nickname, type, dateScope); 90 | RespPageBean respPageBean = new RespPageBean(); 91 | respPageBean.setData(allGroupMsgContentByPage); 92 | respPageBean.setTotal(total); 93 | return respPageBean; 94 | } 95 | 96 | @Override 97 | public Integer deleteGroupMsgContentByIds(Integer[] ids) { 98 | return groupMsgContentDao.deleteGroupMsgContentByIds(ids); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service.impl; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import top.javahai.chatroom.dao.UserDao; 11 | import top.javahai.chatroom.entity.RespBean; 12 | import top.javahai.chatroom.entity.RespPageBean; 13 | import top.javahai.chatroom.entity.User; 14 | import top.javahai.chatroom.service.UserService; 15 | import org.springframework.stereotype.Service; 16 | import top.javahai.chatroom.utils.UserUtil; 17 | 18 | import javax.annotation.Resource; 19 | import java.util.List; 20 | 21 | /** 22 | * (User)表服务实现类 23 | * 24 | * @author makejava 25 | * @since 2020-06-16 11:37:09 26 | */ 27 | @Service("userService") 28 | public class UserServiceImpl implements UserService, UserDetailsService { 29 | @Resource 30 | private UserDao userDao; 31 | 32 | /** 33 | * 根据用户名进行登录 34 | * @param username 35 | * @return 36 | * @throws UsernameNotFoundException 37 | */ 38 | @Override 39 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 40 | User user = userDao.loadUserByUsername(username); 41 | if (user==null){ 42 | throw new UsernameNotFoundException("用户不存在"); 43 | } 44 | return user; 45 | } 46 | 47 | /** 48 | * 获取除了当前用户的所有user表的数据 49 | * @return 50 | */ 51 | @Override 52 | public List getUsersWithoutCurrentUser() { 53 | return userDao.getUsersWithoutCurrentUser(UserUtil.getCurrentUser().getId()); 54 | } 55 | /** 56 | * 设置用户当前状态为在线 57 | * @param id 用户id 58 | */ 59 | @Override 60 | public void setUserStateToOn(Integer id) { 61 | userDao.setUserStateToOn(id); 62 | } 63 | /** 64 | * 设置用户当前状态为离线 65 | * @param id 用户id 66 | */ 67 | @Override 68 | public void setUserStateToLeave(Integer id) { 69 | userDao.setUserStateToLeave(id); 70 | } 71 | 72 | /** 73 | * 通过ID查询单条数据 74 | * 75 | * @param id 主键 76 | * @return 实例对象 77 | */ 78 | @Override 79 | public User queryById(Integer id) { 80 | return this.userDao.queryById(id); 81 | } 82 | 83 | /** 84 | * 查询多条数据 85 | * 86 | * @param offset 查询起始位置 87 | * @param limit 查询条数 88 | * @return 对象列表 89 | */ 90 | @Override 91 | public List queryAllByLimit(int offset, int limit) { 92 | return this.userDao.queryAllByLimit(offset, limit); 93 | } 94 | 95 | /** 96 | * 新增数据 97 | * 98 | * @param user 实例对象 99 | * @return 实例对象 100 | */ 101 | @Override 102 | public Integer insert(User user) { 103 | //对密码进行加密 104 | BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); 105 | String encodePass = encoder.encode(user.getPassword()); 106 | user.setPassword(encodePass); 107 | user.setUserStateId(2); 108 | user.setEnabled(true); 109 | user.setLocked(false); 110 | return this.userDao.insert(user); 111 | } 112 | 113 | /** 114 | * 修改数据 115 | * 116 | * @param user 实例对象 117 | * @return 实例对象 118 | */ 119 | @Override 120 | public Integer update(User user) { 121 | return this.userDao.update(user); 122 | } 123 | 124 | /** 125 | * 通过主键删除数据 126 | * 127 | * @param id 主键 128 | * @return 是否成功 129 | */ 130 | @Override 131 | public boolean deleteById(Integer id) { 132 | return this.userDao.deleteById(id) > 0; 133 | } 134 | 135 | @Override 136 | public Integer checkUsername(String username) { 137 | return userDao.checkUsername(username); 138 | } 139 | 140 | @Override 141 | public Integer checkNickname(String nickname) { 142 | return userDao.checkNickname(nickname); 143 | } 144 | 145 | @Override 146 | public RespPageBean getAllUserByPage(Integer page, Integer size,String keyword,Integer isLocked) { 147 | if (page!=null&&size!=null){ 148 | page=(page-1)*size;//起始下标 149 | } 150 | //获取用户数据 151 | List userList=userDao.getAllUserByPage(page,size,keyword,isLocked); 152 | //获取用户数据的总数 153 | Long total=userDao.getTotal(keyword,isLocked); 154 | RespPageBean respPageBean = new RespPageBean(); 155 | respPageBean.setData(userList); 156 | respPageBean.setTotal(total); 157 | return respPageBean; 158 | } 159 | 160 | @Override 161 | public Integer changeLockedStatus(Integer id, Boolean isLocked) { 162 | return userDao.changeLockedStatus(id,isLocked); 163 | } 164 | 165 | @Override 166 | public Integer deleteByIds(Integer[] ids) { 167 | return userDao.deleteByIds(ids); 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/service/impl/UserStateServiceImpl.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.service.impl; 2 | 3 | import top.javahai.chatroom.entity.UserState; 4 | import top.javahai.chatroom.dao.UserStateDao; 5 | import top.javahai.chatroom.service.UserStateService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.annotation.Resource; 9 | import java.util.List; 10 | 11 | /** 12 | * (UserState)表服务实现类 13 | * 14 | * @author makejava 15 | * @since 2020-06-16 11:36:02 16 | */ 17 | @Service("userStateService") 18 | public class UserStateServiceImpl implements UserStateService { 19 | @Resource 20 | private UserStateDao userStateDao; 21 | 22 | /** 23 | * 通过ID查询单条数据 24 | * 25 | * @param id 主键 26 | * @return 实例对象 27 | */ 28 | @Override 29 | public UserState queryById(Integer id) { 30 | return this.userStateDao.queryById(id); 31 | } 32 | 33 | /** 34 | * 查询多条数据 35 | * 36 | * @param offset 查询起始位置 37 | * @param limit 查询条数 38 | * @return 对象列表 39 | */ 40 | @Override 41 | public List queryAllByLimit(int offset, int limit) { 42 | return this.userStateDao.queryAllByLimit(offset, limit); 43 | } 44 | 45 | /** 46 | * 新增数据 47 | * 48 | * @param userState 实例对象 49 | * @return 实例对象 50 | */ 51 | @Override 52 | public UserState insert(UserState userState) { 53 | this.userStateDao.insert(userState); 54 | return userState; 55 | } 56 | 57 | /** 58 | * 修改数据 59 | * 60 | * @param userState 实例对象 61 | * @return 实例对象 62 | */ 63 | @Override 64 | public UserState update(UserState userState) { 65 | this.userStateDao.update(userState); 66 | return this.queryById(userState.getId()); 67 | } 68 | 69 | /** 70 | * 通过主键删除数据 71 | * 72 | * @param id 主键 73 | * @return 是否成功 74 | */ 75 | @Override 76 | public boolean deleteById(Integer id) { 77 | return this.userStateDao.deleteById(id) > 0; 78 | } 79 | } -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/utils/AliyunOssUtil.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.utils; 2 | 3 | import com.aliyun.oss.OSS; 4 | import com.aliyun.oss.OSSClientBuilder; 5 | import com.aliyun.oss.model.CannedAccessControlList; 6 | import org.joda.time.DateTime; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | import top.javahai.chatroom.config.AliyunOssConfig; 10 | 11 | import java.io.InputStream; 12 | import java.util.UUID; 13 | 14 | /** 15 | * @author Hai 16 | * @program: subtlechat-mini 17 | * @description: oss文件存储工具类 18 | * @create 2021/12/5 - 19:28 19 | **/ 20 | @Component 21 | public class AliyunOssUtil { 22 | 23 | @Autowired 24 | AliyunOssConfig aliyunOssConfig; 25 | 26 | public String upload(InputStream inputStream, String module, String originalFilename) { 27 | 28 | String endpoint = aliyunOssConfig.getEndpoint(); 29 | String keyId = aliyunOssConfig.getKeyid(); 30 | String keySecret = aliyunOssConfig.getKeysecret(); 31 | String bucketName = aliyunOssConfig.getBucketname(); 32 | 33 | //判断oss实例是否存在:如果不存在则创建,如果存在则获取 34 | OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret); 35 | try { 36 | if (!ossClient.doesBucketExist(bucketName)) { 37 | //创建bucket 38 | ossClient.createBucket(bucketName); 39 | //设置oss实例的访问权限:公共读 40 | ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); 41 | } 42 | 43 | //构建日期路径:avatar/2019/02/26/文件名 44 | String folder = new DateTime().toString("yyyy/MM/dd"); 45 | 46 | //文件名:uuid.扩展名 47 | String fileName = UUID.randomUUID().toString(); 48 | String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); 49 | String key = module + "/" + folder + "/" + fileName + fileExtension; 50 | 51 | //文件上传至阿里云 52 | ossClient.putObject(aliyunOssConfig.getBucketname(), key, inputStream); 53 | //返回url地址 54 | return "https://" + bucketName + "." + endpoint + "/" + key; 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | } finally { 58 | // 关闭OSSClient。 59 | ossClient.shutdown(); 60 | } 61 | return null; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/utils/FastDFSUtil.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.utils; 2 | 3 | import org.csource.common.MyException; 4 | import org.csource.fastdfs.ClientGlobal; 5 | import org.csource.fastdfs.StorageClient1; 6 | import org.csource.fastdfs.TrackerClient; 7 | import org.csource.fastdfs.TrackerServer; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import java.io.IOException; 11 | import java.io.UnsupportedEncodingException; 12 | import java.security.NoSuchAlgorithmException; 13 | 14 | /** 15 | * @author Hai 16 | * @date 2020/6/20 - 23:43 17 | */ 18 | public class FastDFSUtil { 19 | private static StorageClient1 client1; 20 | 21 | static{ 22 | try{ 23 | ClientGlobal.initByProperties("fastdfs-client.properties"); 24 | TrackerClient trackerClient=new TrackerClient(); 25 | TrackerServer trackerServer=trackerClient.getConnection(); 26 | client1=new StorageClient1(trackerServer,null); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } catch (MyException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | /** 35 | * 上传文件 36 | * @param file 37 | * @return 38 | * @throws IOException 39 | * @throws MyException 40 | */ 41 | public static String upload(MultipartFile file) throws IOException, MyException { 42 | //文件名 43 | String oldName=file.getOriginalFilename(); 44 | //返回上传到服务器的路径 45 | //文件拓展名oldName.substring(oldName.lastIndexOf(".")+1) 46 | return client1.upload_file1(file.getBytes(),oldName.substring(oldName.lastIndexOf(".")+1),null); 47 | } 48 | 49 | /** 50 | *获取访问文件的令牌 51 | * @throws UnsupportedEncodingException 52 | * @throws NoSuchAlgorithmException 53 | * @throws MyException 54 | * @return 55 | */ 56 | // public static StringBuilder getToken(String fileId) throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException { 57 | // int ts = (int) Instant.now().getEpochSecond(); 58 | // fileId=fileId.substring(7); 59 | // String token = ProtoCommon.getToken(fileId, ts, "FastDFS1234567890"); 60 | // StringBuilder sb = new StringBuilder(); 61 | // sb.append("?token=").append(token); 62 | // sb.append("&ts=").append(ts); 63 | // return sb; 64 | // } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/utils/TuLingUtil.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.utils; 2 | 3 | 4 | 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import org.json.JSONObject; 8 | 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStreamReader; 12 | import java.io.UnsupportedEncodingException; 13 | import java.net.HttpURLConnection; 14 | import java.net.URL; 15 | import java.net.URLEncoder; 16 | import java.util.HashMap; 17 | 18 | /** 19 | * 智能回复机器人工具类 20 | * @author Hai 21 | * @date 2020/6/25 - 17:53 22 | */ 23 | public class TuLingUtil { 24 | 25 | private static ObjectMapper MAPPER=new ObjectMapper(); 26 | 27 | /** 28 | * 发送消息,获得图灵机器人回复消息 29 | * @param message 30 | * @return 31 | * @throws IOException 32 | */ 33 | public static String replyMessage(String message) throws IOException { 34 | String APIKEY = "40445cf23e2144828218d7fc95d6f05a"; 35 | String INFO = URLEncoder.encode(message, "utf-8"); 36 | String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO; 37 | URL getUrl = new URL(getURL); 38 | HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 39 | connection.connect(); 40 | // 取得输入流,并使用Reader读取 41 | BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "utf-8")); 42 | StringBuffer sb = new StringBuffer(); 43 | String line = ""; 44 | while ((line = reader.readLine()) != null) { 45 | sb.append(line); 46 | } 47 | reader.close(); 48 | // 断开连接 49 | connection.disconnect(); 50 | 51 | return parseMess(sb.toString()); 52 | } 53 | 54 | /** 55 | * 解析返回的JSON字符串,获取回复字符串 56 | * @param jsonStr 57 | * @return 58 | * @throws JsonProcessingException 59 | */ 60 | public static String parseMess(String jsonStr) throws JsonProcessingException { 61 | HashMap resultMap = MAPPER.readValue(jsonStr, HashMap.class); 62 | String result = ((String) resultMap.get("text")); 63 | return result; 64 | } 65 | public static void main(String[] args) throws IOException { 66 | String jsonStr = replyMessage("http://39.108.169.57/group1/M00/00/00/J2ypOV7wP0-AEZHOAAILbcn5GEM095.jpg"); 67 | HashMap resultMap = MAPPER.readValue(jsonStr, HashMap.class); 68 | System.out.println(resultMap.get("text")); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/top/javahai/chatroom/utils/UserUtil.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom.utils; 2 | 3 | import org.springframework.security.core.context.SecurityContext; 4 | import org.springframework.security.core.context.SecurityContextHolder; 5 | import top.javahai.chatroom.entity.User; 6 | 7 | /** 8 | * @author Hai 9 | * @date 2020/6/16 - 22:56 10 | * 用户工具类 11 | */ 12 | public class UserUtil { 13 | /** 14 | * 获取当前登录用户实体 15 | * @return 16 | */ 17 | public static User getCurrentUser(){ 18 | return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | #数据库配置 2 | spring.datasource.url=jdbc:mysql://localhost/chatroom 3 | spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 4 | spring.datasource.username=#用户名 5 | #开发环境密码 6 | spring.datasource.password=#密码 7 | #sql日志显示 8 | mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 9 | #mapper文件位置配置 10 | mybatis.mapper-locations=classpath:mapper/*.xml 11 | #端口号配置 12 | server.port=8082 13 | #FastDFS文件服务器的主机名 14 | fastdfs.nginx.host=http://39.108.169.57/ 15 | #SMTP服务器地址 16 | spring.mail.host=smtp.qq.com 17 | #SMTP服务器端口 18 | spring.mail.port=587 19 | #发送者的用户名(邮箱) 20 | spring.mail.username=#你的邮箱 21 | #发送方的授权码 22 | spring.mail.password=#你的授权码 23 | #编码格式 24 | spring.mail.default-encoding=UTF-8 25 | spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory 26 | #debug,输出邮件发送的过程 27 | spring.mail.properties.mail.debug=true 28 | 29 | #oss配置 30 | aliyun.oss.endpoint=oss-cn-beijing.aliyuncs.com 31 | aliyun.oss.keyid=你的keyid 32 | aliyun.oss.keysecret=你的kysecret 33 | aliyun.oss.bucketname=subtle-chat 34 | 35 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #选择激活的配置文件 2 | spring.profiles.active=dev 3 | 4 | 5 | -------------------------------------------------------------------------------- /src/main/resources/fastdfs-client.properties: -------------------------------------------------------------------------------- 1 | ## fastdfs-client.properties 2 | 3 | fastdfs.connect_timeout_in_seconds = 5 4 | fastdfs.network_timeout_in_seconds = 30 5 | 6 | fastdfs.charset = UTF-8 7 | 8 | fastdfs.http_anti_steal_token = false 9 | fastdfs.http_secret_key = FastDFS1234567890 10 | fastdfs.http_tracker_http_port = 80 11 | 12 | fastdfs.tracker_servers =39.108.169.57:22122 13 | 14 | ## Whether to open the connection pool, if not, create a new connection every time 15 | fastdfs.connection_pool.enabled = true 16 | 17 | ## max_count_per_entry: max connection count per host:port , 0 is not limit 18 | fastdfs.connection_pool.max_count_per_entry = 500 19 | 20 | ## connections whose the idle time exceeds this time will be closed, unit: second, default value is 3600 21 | fastdfs.connection_pool.max_idle_time = 3600 22 | 23 | ## Maximum waiting time when the maximum number of connections is reached, unit: millisecond, default value is 1000 24 | fastdfs.connection_pool.max_wait_time_in_ms = 1000 25 | -------------------------------------------------------------------------------- /src/main/resources/mapper/AdminDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | 24 | 25 | 26 | 32 | 33 | 34 | 56 | 57 | 58 | 59 | insert into chatroom.admin(username, nickname, password, user_profile) 60 | values (#{username}, #{nickname}, #{password}, #{userProfile}) 61 | 62 | 63 | 64 | 65 | update chatroom.admin 66 | 67 | 68 | username = #{username}, 69 | 70 | 71 | nickname = #{nickname}, 72 | 73 | 74 | password = #{password}, 75 | 76 | 77 | user_profile = #{userProfile}, 78 | 79 | 80 | where id = #{id} 81 | 82 | 83 | 84 | 85 | delete from chatroom.admin where id = #{id} 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/resources/mapper/GroupMsgContentDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 22 | 23 | 24 | 32 | 33 | 34 | 62 | 63 | 64 | 65 | insert into chatroom.group_msg_content(from_id, from_name, from_profile, create_time, content, message_type_id) 66 | values (#{fromId}, #{fromName}, #{fromProfile}, #{createTime}, #{content}, #{messageTypeId}) 67 | 68 | 69 | 70 | 71 | update chatroom.group_msg_content 72 | 73 | 74 | from_id = #{fromId}, 75 | 76 | 77 | from_name = #{fromName}, 78 | 79 | 80 | from_profile = #{fromProfile}, 81 | 82 | 83 | create_time = #{createTime}, 84 | 85 | 86 | content = #{content}, 87 | 88 | 89 | message_type_id = #{messageTypeId}, 90 | 91 | 92 | where id = #{id} 93 | 94 | 95 | 96 | 97 | delete from chatroom.group_msg_content where id = #{id} 98 | 99 | 100 | 115 | 127 | 128 | delete from group_msg_content where id in 129 | 130 | #{id} 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 24 | 25 | 26 | 32 | 33 | 34 | 40 | 41 | 42 | 73 | 74 | 75 | 76 | insert into chatroom.user(username, nickname, password, user_profile, user_state_id, is_enabled, is_locked) 77 | values (#{username}, #{nickname}, #{password}, #{userProfile}, #{userStateId}, #{isEnabled}, #{isLocked}) 78 | 79 | 80 | 81 | 82 | update chatroom.user 83 | 84 | 85 | username = #{username}, 86 | 87 | 88 | nickname = #{nickname}, 89 | 90 | 91 | password = #{password}, 92 | 93 | 94 | user_profile = #{userProfile}, 95 | 96 | 97 | user_state_id = #{userStateId}, 98 | 99 | 100 | is_enabled = #{isEnabled}, 101 | 102 | 103 | is_locked = #{isLocked}, 104 | 105 | 106 | where id = #{id} 107 | 108 | 109 | 110 | 111 | delete from chatroom.user where id = #{id} 112 | 113 | 114 | 115 | update chatroom.user set user_state_id=1 where id=#{id} 116 | 117 | 118 | update chatroom.user set user_state_id=2 where id=#{id} 119 | 120 | 123 | 126 | 127 | 139 | 148 | 149 | update user set is_locked=#{isLocked} where id=#{id} 150 | 151 | 152 | delete from user where id in 153 | 154 | #{id} 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserStateDao.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 17 | 18 | 19 | 25 | 26 | 27 | 40 | 41 | 42 | 43 | insert into chatroom.user_state(name) 44 | values (#{name}) 45 | 46 | 47 | 48 | 49 | update chatroom.user_state 50 | 51 | 52 | name = #{name}, 53 | 54 | 55 | where id = #{id} 56 | 57 | 58 | 59 | 60 | delete from chatroom.user_state where id = #{id} 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/test/java/top/javahai/chatroom/ChatroomApplicationTests.java: -------------------------------------------------------------------------------- 1 | package top.javahai.chatroom; 2 | 3 | import com.github.binarywang.java.emoji.EmojiConverter; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.mail.SimpleMailMessage; 8 | import org.springframework.mail.javamail.JavaMailSender; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | 11 | import java.text.SimpleDateFormat; 12 | import java.util.Date; 13 | import java.util.Random; 14 | 15 | @SpringBootTest 16 | class ChatroomApplicationTests { 17 | 18 | //测试密码加密 19 | @Test 20 | void contextLoads() { 21 | BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); 22 | String encode = encoder.encode("123"); 23 | System.out.println(encode); 24 | } 25 | 26 | @Test 27 | void test01(){ 28 | SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 29 | System.out.println(simpleDateFormat.format(new Date())); 30 | System.out.println(new Date()); 31 | } 32 | //测试emoji的转码 33 | @Test 34 | void test02(){ 35 | EmojiConverter emojiConverter = EmojiConverter.getInstance(); 36 | String str="\uE423 \uE424 \uE425An ??awesome ??string with a few ??emojis!"; 37 | String html = emojiConverter.toHtml(str); 38 | System.out.println(html); 39 | } 40 | @Autowired 41 | JavaMailSender javaMailSender; 42 | //测试邮件发送 43 | @Test 44 | void test03(){ 45 | SimpleMailMessage msg=new SimpleMailMessage(); 46 | //邮件的主题 47 | msg.setSubject("这是测试邮件主题"); 48 | //邮件的内容 49 | msg.setText("这是测试邮件内容:\nsecond try"); 50 | //邮件的发送方,对应配置文件中的spring.mail.username 51 | msg.setFrom("1258398543@qq.com"); 52 | //邮件发送时间 53 | msg.setSentDate(new Date()); 54 | //邮件接收方 55 | msg.setTo("jinhaihuang824@aliyun.com"); 56 | //执行发送 57 | javaMailSender.send(msg); 58 | } 59 | //测试生成四个随机数 60 | @Test 61 | void test04(){ 62 | Random random = new Random(); 63 | StringBuilder code=new StringBuilder(); 64 | for (int i = 0; i < 4; i++) { 65 | int num = random.nextInt(10); 66 | code.append(num); 67 | } 68 | System.out.println(code); 69 | } 70 | } 71 | --------------------------------------------------------------------------------