java - 单击电子邮件激活链接时如何登录用户?(JSF 2.0)

标签 java jsf jakarta-ee jsf-2 jakarta-mail

我使用 javamail 向我的用户发送帐户激活邮件。在那封电子邮件中,有一个链接,单击该链接后,用户应激活他们的帐户,重定向到应用程序的主页并让他们登录。我该怎么做?我可以在作为 HTML 模板发送的链接中添加对托管 bean 的方法调用吗?

这是我用于发送电子邮件模板的 EJB:

@Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB implements IEmailServiceEJB {

    @Resource(name = "mail/myMailSession")
    private Session mailSession;

    public void sendAccountActivationLinkToBuyer(String destinationEmail,
            String name) {

        // Destination of the email
        String to = destinationEmail;
        String from = "dontreply2thismessage@gmail.com";

        try {
            Message message = new MimeMessage(mailSession);
            // From: is our service
            message.setFrom(new InternetAddress(from));
            // To: destination given
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            message.setSubject("Uspijesna registracija");
            // How to found at http://www.rgagnon.com/javadetails/java-0321.html
            message.setContent(generateActivationLinkTemplate(), "text/html");

            Date timeStamp = new Date();
            message.setSentDate(timeStamp);

            // Prepare a multipart HTML
            Multipart multipart = new MimeMultipart();
            // Prepare the HTML
            BodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(generateActivationLinkTemplate(), "text/html");
            htmlPart.setDisposition(BodyPart.INLINE);

            // PREPARE THE IMAGE
            BodyPart imgPart = new MimeBodyPart();

            String fileName = "logoemailtemplate.png";

            ClassLoader classLoader = Thread.currentThread()
                    .getContextClassLoader();
            if (classLoader == null) {
                classLoader = this.getClass().getClassLoader();
                if (classLoader == null) {
                    System.out.println("IT IS NULL AGAIN!!!!");
                }
            }

            DataSource ds = new URLDataSource(classLoader.getResource(fileName));

            imgPart.setDataHandler(new DataHandler(ds));
            imgPart.setHeader("Content-ID", "<logoimg_cid>");
            imgPart.setDisposition(MimeBodyPart.INLINE);
            imgPart.setFileName("logomailtemplate.png");

            multipart.addBodyPart(htmlPart);
            multipart.addBodyPart(imgPart);
            // Set the message content!
            message.setContent(multipart);

            System.out.println("MIME!!!!");
            System.out.println(multipart.getContentType());

            Transport.send(message);

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }    


    private String generateActivationLinkTemplate() {
        String htmlText = "";
        htmlText = "<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">  <tr>    <td><img src=\"cid:logoimg_cid\"/></td>  </tr>  <tr>    <td height=\"220\"> <p>Thanks for Joining Site.com</p>      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>    <p>Username:<br />      Password: </p>    <p>To confirm your email click <a href=\"#\">here</a>.</p></td>  </tr>  <tr>    <td height=\"50\" align=\"center\" valign=\"middle\" bgcolor=\"#CCCCCC\">www.site.com | contact@site.com | +38200 123 456</td>  </tr></table>";
        return htmlText;
    }


}

这是将在 session 中保存用户状态(登录)的 EJB:

public class AuthentificationEJB implements IAuthentificationEJB {

    @PersistenceContext
    private EntityManager em;

    // Login
    public boolean saveUserState(String email, String password) {
        // 1-Send query to database to see if that user exist
        Query query = em
                .createQuery("SELECT r FROM Role r WHERE r.email=:emailparam AND r.password=:passwordparam");
        query.setParameter("emailparam", email);
        query.setParameter("passwordparam", password);
        // 2-If the query returns the user(Role) object, store it somewhere in
        // the session
        List<Object> tmpList = query.getResultList();
        if (tmpList.isEmpty() == false) {
            Role role = (Role) tmpList.get(0);
            if (role != null && role.getEmail().equals(email)
                    && role.getPassword().equals(password)) {
                FacesContext.getCurrentInstance().getExternalContext()
                        .getSessionMap().put("userRole", role);
                // 3-return true if the user state was saved
                System.out.println(role.getEmail() + role.getPassword());
                return true;
            }
        }
        // 4-return false otherwise
        return false;
    }

我可以从我在方法 generateActivationLinkTemplate() 中手动创建的模板调用方法 saveUserState(email,password) 吗?所以用户被重定向到应用程序的主页,用户被保存到 session 中

最佳答案

如果您在类似 http://example.com/activate.xhtml?key=somelonganduniquekey 的链接中将激活 key 作为请求参数传递,然后只需使用 @ManagedProperty 让 JSF 在 bean 中设置请求参数,并在 @PostConstruct 中执行验证和登录工作。

@ManagedBean
@RequestScoped
public class Activation {

    @ManagedProperty(value="#{param.key}")
    private String key;

    private boolean valid;

    @PostConstruct
    public void init() {
        // Get User based on activation key.
        // Delete activation key from database.
        // Login user.
    }

    // ...
}

activate.xhtml 看起来像这样

<h:head>
    <ui:fragment rendered="#{activation.valid}">
        <meta http-equiv="refresh" content="3;url=home.xhtml" />
    </ui:fragment>
</h:head>
<h:body>
    <h:panelGroup layout="block" rendered="#{activation.valid}">
        <p>Your account is successfully activated!</p>
        <p>You will in 3 seconds be redirected to <h:link outcome="home">home page</h:link></p>
    </h:panelGroup>
    <h:panelGroup layout="block" rendered="#{!activation.valid}">
        <p>Activation failed! Please enter your email address to try once again.</p> 
        <h:form>
            ...
        </h:form>
    </h:panelGroup>
</h:body>

关于java - 单击电子邮件激活链接时如何登录用户?(JSF 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5696725/

相关文章:

java - 带有请求正文问题的 HTTP 删除

java - 使用itext将文本文件转换为pdf时设置编码

java - 获取jboss的信息

java - Crypto JS AES-128 密码 - 等效的 Javascript 代码

java - MLKit BarCode Sanner Implementation 在执行 ML Kit 任务时导致内部错误

jsf - 在 TomEE 7 Plume 中升级 JSF 库的正确方法是什么?

java - Spring MVC 3.1 RedirectAttributes 不工作

java - JSF 和 Facebook

jsf - 如何呈现一个特定节点已经展开的 RichFaces 树

Java 可变参数在扩展时的奇怪行为