spring 阻止在thymleaf电子邮件模板中提交表单时重定向

2eafrhcq  于 2023-02-28  发布在  Spring
关注(0)|答案(2)|浏览(124)

我有一个使用REST API的Spring Boot应用程序,运行良好。在同一个项目中,我有一个API用于向客户发送电子邮件通知,它使用thymleaf创建HTML电子邮件模板,我需要提供"是"和"否"按钮的选项,客户将单击其中一个按钮,我需要基于此单击REST API。
为此,我创建了一个表单,点击按钮,它会将我重定向到一个新的页面,URL为空,当我刷新页面时,它会点击REST API。我想阻止重定向到新页面,并点击按钮时点击REST API。我已经通过了许多StackOverflow的例子,并尝试了,但它不工作。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:lang="${#locale.language}" lang="en">
<head>
    <title th:text="#{email.notification.title}">Notification Alert</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<script>
$('#submit-decline').on('click', function() {
    var form = $('#decline-form');
    $.ajax({
        url: http://localhost:8082/decline,
        data: form.serialize(),
        type: get,
        success: function(result) {
            // Do something with the response.
            // Might want to check for errors here.
        }, error: function(error) {
            // Here you can handle exceptions thrown by the server or your controller.
        }
    })
}
</script>

<body>
    <p>
        Hi Team,<br>
        Below are the changes found in the table
    </p>

    <table border="1" style="width:750px">
        <tr>
            <td><b>File</b></td>
            <td><b>Entity</b></td>
            <td><b>Client</b></td>
            <td><b>Timestamp</b></td>
            <td><b>Changes</b></td>
        </tr>
        <tr>
            <td th:text="${notification.fileName}"></td>
            <td th:text="${notification.entity}"></td>
            <td th:text="${notification.client}"></td>
            <td th:text="${notification.timestamp}"></td>
            <td th:text="${notification.changes}"></td>
        </tr>
    </table>

    <p>
        Would you like to approve the changes -
    </p>

    <form id="decline-form" th:action="@{http://localhost:8082/decline}" th:method="get" >
        <input id="submit-decline" type="submit" value="No"/>
    </form>

    <p>
        <span>Regards, </span>
        <br/>
        <em>Team.</em>
    </p>

</body>
</html>
@Override
    public void sendNotificationEmail(NotificationDTO notificationDTO) throws MessagingException {
        NotificationDTO notificationDTOWithDetail= fileUtil.getFieldsFromFileName(notificationDTO);
        System.out.println("65 " + notificationDTOWithDetail);
        String lang = defaultThymeleafLang;
        Locale locale = Locale.forLanguageTag(lang);
        Context context = new Context(locale);
        context.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            new ThymeleafEvaluationContext(applicationContext, null));
        context.setVariable(NOTIFICATION, notificationDTOWithDetail);
        context.setVariable("emailApproveService",emailApproveService);
        context.setVariable("emailDeclineService",emailDeclineService);
        String content = templateEngine.process("notificationEmail", context);
        String subject =
                messageSource.getMessage(
                        "email.notification.subject",
                        new Object[] {
                                notificationUtil.getNotificationSubject(
                                        notificationDTOWithDetail.getApplicationName())
                        },
                        locale);
        String primaryNotifiers = notificationUtil.getPrimaryNotifiers(notificationDTOWithDetail.getApplicationName());
        String ccNotifiers =  notificationUtil.getCcNotifiers(notificationDTOWithDetail.getApplicationName());

        sendEmail(primaryNotifiers, ccNotifiers, subject, content, false, true);
    }
package com.rwg.web;

import com.rwg.service.EmailDeclineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class EmailDeclineResource {

    private final EmailDeclineService emailDeclineService;
    EmailDeclineResource(
            EmailDeclineService emailDeclineService){
        this.emailDeclineService=emailDeclineService;
    }

    @GetMapping("/decline")
    public String decline() {
        ...
        return "success message";
    }

}

编辑:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:lang="${#locale.language}" lang="en">
<head>
    <title th:text="#{email.notification.title}">Notification Alert</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<script>
$("#decline-form").submit(function (event) {
    .get("http://localhost:8082/decline").done(function (data) {
        console.log('success')
    });
    event.preventDefault();
});
</script>

<body>
    <p>
        Hi Team,<br>
        Below are the changes found in the table
    </p>

    <table border="1" style="width:750px">
        <tr>
            <td><b>File</b></td>
            <td><b>Entity</b></td>
            <td><b>Client</b></td>
            <td><b>Timestamp</b></td>
            <td><b>Changes</b></td>
        </tr>
        <tr>
            <td th:text="${notification.fileName}"></td>
            <td th:text="${notification.entity}"></td>
            <td th:text="${notification.client}"></td>
            <td th:text="${notification.timestamp}"></td>
            <td th:text="${notification.changes}"></td>
        </tr>
    </table>

    <p>
        Would you like to approve the changes -
    </p>

    <form id="decline-form" th:action="@{http://localhost:8082/decline}" th:method="get" >
        <input id="submit-decline" type="submit" value="No"/>
    </form>

    <p>
        <span>Regards, </span>
        <br/>
        <em>Team.</em>
    </p>

</body>
</html>
inn6fuwd

inn6fuwd1#

Thymeleaf的行为和普通的HTML页面一样。每个表单都会自动重定向到“action”属性。防止它的唯一方法是使用 AJAX 。

aiazj4mn

aiazj4mn2#

当你提交一个HTML格式的表单时,默认情况下,它会重定向到action属性中提到的URL。为了防止这种情况,请使用 AJAX 发送拒绝请求。

$("#decline-form").submit(function (event) {
    $.ajax({
       url: http://localhost:8082/decline,
       data: form.serialize(),
       type: get,
       success: function(result) {
          // Do something with the response.
          // Might want to check for errors here.
       }, error: function(error) {
           // Here you can handle exceptions thrown by the server or your controller.
       }
   });
   event.preventDefault();
});

event.preventDefault()将阻止提交时的默认重定向。

相关问题