簡體   English   中英

Spring Thymeleaf-如何映射到需要從HTML傳遞到控制器的ID的URL?

[英]Spring Thymeleaf - How to map to a URL that requires an ID that is passed from HTML to the controller?

在我的應用程序中,用戶單擊鏈接以編輯他們選擇的考試。

當他們單擊鏈接時,它應該打開editExam.html,並且URL包含他們選擇的考試的ID。

當我單擊鏈接時,URL是正確的(包含考試ID),但是不顯示editExam.html頁面,而僅顯示我的主頁(默認的localhost頁面)。

在此處輸入圖片說明

allSubjects.html(用戶選擇要編輯的考試的頁面)

    <h4> exams:</h4>
<div th:each="exam : ${subject.exam}"> 
<h4 th:text="${exam.examTitle}"/>
    <a th:href="@{/editExam.html(id=${exam.examId})}">Edit Exam</a> 

editExam.html(這是我無法顯示的頁面)

<form action="#"th:action="@{/editExam.html{examId}}"  th:object="${exam}" method="put">


    <table>
        <tr>
        <td> Exam Title:</td>
         <td><input type="text" th:field="*{examTitle}" th:text="${exam.examTitle}"/></td>
    <!--    <td th:if="${#fields.hasErrors('examTitlee')}" th:errors="*{examTitle}">error message</td>  --> 
        </tr>  
        <tr>
            <td> Exam grade worth </td>
            <td><input th:field="*{examGradeWorth}" /></td>
        <!--    <td th:if="${#fields.hasErrors('examGradeWorth')}" th:errors="*{examGradeWorth}">error message</td> -->
            </tr>  
            <tr>
                <td>examGradeAchieved</td>
                <td><input th:field="*{examGradeAchieved}"/></td>
                </tr>
            <tr>
                <td><button type="submit">Submit post</button></td>
                </tr>
    </table>
    </div>
</form>  

我的控制器:

//Update an exam
@RequestMapping(value = "/editExam.html{examId}", method = { RequestMethod.POST, RequestMethod.PUT})
public String editExam(@ModelAttribute("exam") @PathVariable(value = "examId")Long examId, @RequestBody Exam exam,Model model, BindingResult result) {

            examRepository.findOne(examId);
            model.addAttribute("examTitle", exam.getExamTitle());
            model.addAttribute("examGradeWorth", exam.getExamGradeWorth());
            model.addAttribute("examGradeAchieved", exam.getExamGradeAchieved());


        exam.setExamTitle(exam.getExamTitle());
         exam.setExamGradeWorth(exam.getExamGradeWorth());
         exam.setExamGradeAchieved(exam.getExamGradeAchieved());

          examRepository.save(exam);

    return "editExam";
}

在將“ RequestMethod.POST”添加到控制器之前,此代碼顯示了editExam頁面。

嘗試改變

<a th:href="@{/editExam.html(id=${exam.examId})}">Edit Exam</a> 

<a th:href="@{/exam/{id}(id=${exam.examId})}">Edit Exam</a> 

並在您的控制器中

@RequestMapping(value = "/editExam.html{examId}", method = { RequestMethod.POST, RequestMethod.PUT})

@RequestMapping(value = "/exam/{examId}", method = { RequestMethod.POST, RequestMethod.PUT})

該網址看起來不正確。 應該是/editExam.html?id=1 ,不帶/

我注意到您正在混合請求參數和路徑變量。 在控制器中,您期望使用@PathVariable(value = "examId")但在視圖中,您將指定請求參數而不是路徑變量。

檢查這篇文章: @RequestParam vs @PathVariable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM