I am making a project where when a user login he will get a mail otp.I have successfully made the login page and also I am sending otp to the user mail address. Now I also want to validate the otp for that I have already created a otp column in database. But I can't figure out how to store the generated otp in the table. Here is my code.
EmailSenderService class :
public class EmailSenderService {
@Autowired
private JavaMailSender mailSender;
public void sendMail(String toEmail,
String subject,
String body) {
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom("growthgreek@gamil.com");
message.setTo(toEmail);
message.setText(body);
message.setSubject(subject);
mailSender.send(message);
System.out.println("message sent .....");
}
}
OtpEmailController Class:
@Controller
public class OtpEmailController {
@Autowired
private EmailSenderService emailService;
Random random = new Random(1000);
@PostMapping("/send-otp")
public String sendOtp(@RequestParam("email") String email) {
int otp = random.nextInt(999999);
String subject = "OTP from session-handling-proj By Harshit";
String toEmail = email;
String body = "<h1> OTP = " + otp + "</h1>";
this.emailService.sendMail(toEmail, subject, body);
return ("success");
}
Repository Class :
@Repository
@Transactional
public interface SessionHandlingRepository extends JpaRepository<SessionHandling, Integer>{
@Query(value="Select * from session_handling where email= :email",nativeQuery =true)
public SessionHandling findByEmailId(@Param("email")String email);
@Query(value="Select * from session_handling where email= :email AND password= :password",nativeQuery =true)
public SessionHandling findByEmailIdAndPassword(@Param("email")String email, @Param("password")String password);
}
Entity Class :
@Entity
public class SessionHandling {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String email;
private String password;
private String cpassword;
private static final long OTP_VALID_DURATION = 5 * 60 * 1000; // 5 minutes
@Column(name = "one_time_password")
private String oneTimePassword;
@Column(name = "otp_requested_time")
private Date otpRequestedTime;
Where and how to write the query for saving the otp in database?
You can do it with your repository, first inject the repository in your service :
@Autowired
private SessionHandlingRepository sessionHandlingRepository;
you can then create an instance of your entity at the desired location (add getter and setter to the entity first):
SessionHandling sessionHandling = new SessionHandling();
sessionHandling.setName("theName");
// call Other setters ...
you can use the following repository method to save the entity in the database :
sessionHandlingRepository.save(sessionHandling);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.