springboot项目
- **中国加油,武汉加油!**
- 篇幅较长,配合目录观看
- 案例准备
- 1. java发送邮件
- 2 注册功能
- 2.1 shop-web新建shop-sso(module-springboot)
- 2.2 导入静态资源
- 2.3 编写register.html
- 2.4 编写yml
- 2.5 编写WebMVCConfig
- 2.6 修改程序入口
- 2.7 启动程序入口访问
- 2.8 修改shop-front的index.html
- 2.9 shop-entity编写Email类
- 2.9 shop-service-api编写Service接口
- 2.10 shop-service-iml新建email-service(module-springboot)
- 2.11 导相关依赖
- 2.12 配置yml
- 2.13 编写ServiceImpl实现类
- 2.14 修改程序入口
- 2.15 Test
- 2.16 修改EmailServiceImpl的@Service为Dubbo的
- 2.17 配置yml
- 2.18 修改程序入口
- 2.19 编写RabbitMQConfig
- 2.20 编写EmailQueueListener
- 2.21 shop-web中的shop-sso导相关依赖
- 2.22 编写RabbitMQConfig
- 2.23 编写Controller
- 2.24 配置yml
- 2.25 修改程序入口
- 2.26 启动程序入口Test
- 3 完善验证码功能和注册功能
中国加油,武汉加油!
篇幅较长,配合目录观看
案例准备
1. java发送邮件
1.1 shop-temp新建java-mail(module-maven)
1.2 导相关依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
1.3 Test
package com.wpj;
import org.junit.Test;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception {
SendEmailInfoUser("1196557363@qq.com", "测试标题", "测试内容", "1196557363@qq.com");
}
private static Message createSimpleMail(Session session, String sendAddress, String title, String content, String copysendAddress) throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("1196557363@qq.com"));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendAddress));
// 邮件的标题
message.setSubject(title);
// 邮件的内容
message.setContent(content, "text/html;charset=UTF-8");
// 设置抄送人
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copysendAddress));
return message;
}
public static void SendEmailInfoUser(String sendAddress, String title, String content, String copySendAddress) throws Exception {
Properties properties = new Properties();
// 设置服务器名称
properties.setProperty("mail.host", "smtp.qq.com");
// 设置邮件传输协议
properties.setProperty("mail.transport.protocol", "smtp");
//设置是否要验证服务器用户名和密码
properties.setProperty("mail.smtp.auth", "true");
// 1.创建客户端与邮箱服务器的Session对象
Session session = Session.getInstance(properties);
// 2.开启session的debug模式,方便查看发送email的运行状态
session.setDebug(true);
// 3.通过session得到transport传输对象
Transport transport = session.getTransport();
// 4.使用用户名密码连接上邮箱服务器,此处的密码需要到邮箱开启服务设置
transport.connect("smtp.qq.com", "1196557363@qq.com", "授权码");
// 5.创建邮件
Message message = createSimpleMail(session, sendAddress, title, content, copySendAddress);
// 6.发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
2 注册功能
2.1 shop-web新建shop-sso(module-springboot)
- Spring Boot Devtools
- Spring Web
- Thymeleaf
- Spring Data Redis(Access+Driver)
2.2 导入静态资源
2.3 编写register.html
2.4 编写yml
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
2.5 编写WebMVCConfig
package com.wpj.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("toRegister").setViewName("register");
registry.addViewController("toLogin").setViewName("login");
registry.addViewController("toInputUsername").setViewName("inputUsername");
registry.addViewController("toUpdatePassword").setViewName("updatePassword");
}
}
2.6 修改程序入口
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.wpj")
public class ShopSsoApplication {
public static void main(String[] args) {
SpringApplication.run(ShopSsoApplication.class, args);
}
}
2.7 启动程序入口访问
2.8 修改shop-front的index.html
<a href="http://localhost:8084/toRegister">
<button class="btn1-l">注册</button>
</a>
2.9 shop-entity编写Email类
package com.wpj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Email implements Serializable {
private String title;
private String content;
private String to;
}
2.9 shop-service-api编写Service接口
package com.wpj.service;
import com.wpj.entity.Email;
public interface IEmailService {
void sendEmail(Email email);
}
2.10 shop-service-iml新建email-service(module-springboot)
2.11 导相关依赖
<dependency>
<groupId>com.wpj</groupId>
<artifactId>shop-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.12 配置yml
spring:
mail:
username: 1196557363@qq.com
password: 授权码
host: smtp.qq.com
2.13 编写ServiceImpl实现类
package com.wpj.service.impl;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class EmailServiceImpl implements IEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendEmail(Email email) {
System.out.println("邮件发送。。。。");
// 创建一个MimeMessage
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 发送邮件的一个工具类
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
try {
// 设置邮件的内容
mimeMessageHelper.setSubject(email.getTitle());
mimeMessageHelper.setText(email.getContent(),true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(email.getTo());
// 发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
2.14 修改程序入口
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(scanBasePackages = "com.wpj", exclude = DataSourceAutoConfiguration.class)
public class EmailServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmailServiceApplication.class, args);
}
}
2.15 Test
package com.wpj;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
class EmailServiceApplicationTests {
@Autowired
private IEmailService emailService;
@Test
public void contextLoads() {
Email email = new Email();
email.setTitle("标题");
email.setContent("<a href='www.baidu.com'>点击</a>");
email.setTo("1196557363@qq.com");
emailService.sendEmail(email);
}
}
2.16 修改EmailServiceImpl的@Service为Dubbo的
import com.alibaba.dubbo.config.annotation.Service;
@Service
public class EmailServiceImpl implements IEmailService {
...
}
2.17 配置yml
spring:
mail:
username: 1196557363@qq.com
password: bruvlwonkbtshecb
host: smtp.qq.com
rabbitmq:
host: 192.168.59.100
virtual-host: /
dubbo:
application:
name: email-service
registry:
address: zookeeper://192.168.59.100:2181
check: false
protocol:
port: -1
2.18 修改程序入口
package com.wpj;
import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@DubboComponentScan(basePackages = "com.wpj.service")
public class EmailServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmailServiceApplication.class, args);
}
}
2.19 编写RabbitMQConfig
package com.wpj.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public FanoutExchange emailExchange(){
return new FanoutExchange("email-exchange");
}
@Bean
public Queue emailQueue(){
return new Queue("email-queue");
}
@Bean
public Binding emailQueueToEmailExchange(){
return BindingBuilder.bind(emailQueue()).to(emailExchange());
}
}
2.20 编写EmailQueueListener
package com.wpj.listener;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration
public class EmailQueueListener {
private ExecutorService service = Executors.newFixedThreadPool(10);
@Autowired
private IEmailService emailService;
@RabbitListener(queues= "email-queue")
public void sendEmail(Email email){
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("监听器中获取到邮件");
emailService.sendEmail(email);
}
});
}
}
2.21 shop-web中的shop-sso导相关依赖
<dependency>
<groupId>com.wpj</groupId>
<artifactId>shop-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
2.22 编写RabbitMQConfig
package com.wpj.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public FanoutExchange emailExchange(){
return new FanoutExchange("email-exchange");
}
@Bean
public Queue emailQueue(){
return new Queue("email-queue");
}
@Bean
public Binding emailQueueToEmailExchange(){
return BindingBuilder.bind(emailQueue()).to(emailExchange());
}
}
2.23 编写Controller
package com.wpj.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/sso")
public class SSOController {
@Reference
private IEmailService emailService;
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("/sendEmail")
@ResponseBody
public String sendEmail(String emailStr){
Email email = new Email();
email.setTo(emailStr);
email.setTitle("宅客微购注册验证码");
email.setContent("验证码: + xxx");
emailService.sendEmail(email);
// 给交换机发送信息
rabbitTemplate.convertAndSend("email-exchange", "", email);
return "ok";
}
}
2.24 配置yml
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
rabbitmq:
host: 192.168.59.100
virtual-host: /
dubbo:
application:
name: shop-sso
registry:
address: zookeeper://192.168.59.100:2181
check: false
consumer:
retries: 3
check: false
2.25 修改程序入口
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(scanBasePackages = "com.wpj", exclude = DataSourceAutoConfiguration.class)
public class ShopSsoApplication {
public static void main(String[] args) {
SpringApplication.run(ShopSsoApplication.class, args);
}
}
2.26 启动程序入口Test
3 完善验证码功能和注册功能
3.1 shop-common编写CodeUtils
package com.wpj.common.utils;
import java.util.Random;
public class CodeUtils {
public static String getCode(){
String doubleStr = new Random().nextDouble()+"";
int indexOf = doubleStr.indexOf(".");
return doubleStr.substring(indexOf +1,indexOf+7);
}
}
3.6 shop-service-api的IUserService添加方法
package com.wpj.service;
import com.wpj.entity.User;
public interface IUserService extends IBaseService<User> {
int register(User user);
User selectByUsername(String username);
}
3.7 user-service实现方法
@Override
public int register(User user) {
// 1.先判断用户名是否被注册 有返回1
User dbUser = this.selectByUsername(user.getUsername());
if(dbUser != null){
return 1;
}
// 2.在判断邮箱是否被注册 有返回2
EntityWrapper wrapper = new EntityWrapper<User>();
wrapper.eq("email",user.getEmail());
Integer emailCount = userMapper.selectCount(wrapper);
if(emailCount > 0){
return 2; // 邮箱已存在
}
// 3.注册成功 成功返回3
userMapper.insert(user);
return 3;
}
@Override
public User selectByUsername(String username) {
User user = new User();
user.setUsername(username);
return userMapper.selectOne(user);
}
3.8 shop-sso配置yml
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
rabbitmq:
host: 192.168.59.100
virtual-host: /
redis:
password: admin
host: 192.168.59.100
dubbo:
application:
name: shop-sso
registry:
address: zookeeper://192.168.59.100:2181
check: false
consumer:
retries: 3
check: false
3.9 Controller添加方法
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/sendEmail")
@ResponseBody
public String sendEmail(String emailStr){
String code = CodeUtils.getCode();
Email email = new Email();
email.setTo(emailStr);
email.setTitle("注册验证码");
email.setContent("验证码:"+code);
System.out.println(code);
// key 唯一
redisTemplate.opsForValue().set(emailStr + "_code", code,60, TimeUnit.SECONDS);
emailService.sendEmail(email);
// 给交换机发送信息
rabbitTemplate.convertAndSend("email-exchange", "", email);
return "ok";
}
@RequestMapping(value = "/register")
@ResponseBody
public ResultEntity register(User user, String code){
// 1.判断code是否有效
String redisCode= (String)redisTemplate.opsForValue().get(user.getEmail()+ "_code");
System.out.println(redisCode);
if(redisCode != null && redisCode.equals(code)){
int result = userService.register(user);
if(result == 1){
return ResultEntity.FALL("用户名已被注册");
}else if(result == 2){
return ResultEntity.FALL("邮箱已被注册");
}else if(result == 3){
return ResultEntity.SUCCESS();
}
}else{
return ResultEntity.FALL("验证码错误");
}
return ResultEntity.FALL();
}
3.10 启动程序入口测试
localhost:8084/toRegister
3.11 编写login.html
3.11 注册完直接跳转到login.html
else if(result == 3){
return ResultEntity.SUCCESS("http://localhost:8084/toLogin");
}