Issue
I have passed a modelAttribute "authRequest" from controller to "dashboard.html". From "dashboard.html" I want to call another service on clicking "view Cards" button. Also want to pass modelAttribute "authRequest" back to view cards controller, so that I will get the modelAttribute "authRequest" in "viewCards.html". I tried giving th:href and form-action but not able to get value of "authRequest" in view cards controller and hence in "viewCards.html". How to pass the modelAttribute "authRequest" to viewCards controller? Tried to pass modelAttribute as below
<form action="#" th:action="@{/viewCards}" th:object="${authRequest}" method="post">
<input type="submit" value="View cards" /></form>
Also tried href
<a th:href="@{/viewCards}" th:object="${authRequest}">view Cards</a>
dashboard.html -Here I am able to get value for ${authRequest.userName}"
<form action="#" th:action="@{/viewCards}" th:object="${authRequest}" method="post">
<input type="submit" value="View cards" />
</form>
<p th:text="'User Name: ' + ${authRequest.userName}" />
viewCards.html -Not able to get value for ${authRequest.userName}
<script type="text/javascript" th:src="@{/webjars/jquery/1.9.1/jquery.min.js/}"></script>
<script th:inline="javascript">
var user= [[${authRequest.userName}]];
</script>
<script type="text/javascript" th:src="@{/vCards.js}"></script>
<p th:text="'User Name: ' + ${authRequest.userName}" />
controllers
@RequestMapping(value= "/virtualWallet/login" , method= RequestMethod.POST)
public String getAuthResponse(
@ModelAttribute AuthRequest authRequest,
Model model
){
String resp = authService.getAuthResponse(authRequest);
if(resp.equals("Success")) {
return "dashboard";
}
return null;
}
@RequestMapping(value= "/viewCards" , method = RequestMethod.POST)
public String viewCards(
@ModelAttribute AuthRequest authRequest
) {
return "viewCards";}
Expected to get "authRequest" value in "viewCards.html". I am getting null.
Solution
Your first approach was almost right.
<form th:action="@{/viewCards}" th:object="${authRequest}" method="post">
<input type="text" th:value="*{authRequestAttr1}" th:field="*{authRequestAttr1}" hidden/>
<!-- Add the rest of authRequest attributes here in the same fashion -->
<button type="submit"></button>
</form>
For the object in th:object
to be submitted you need to have inputs that contain the values of the attributes in that object. You also need to bind them with th:field
.
Since you just want to pass that object to a controller, in the example I've hidden the inputs, but that is not neccesary.
Answered By - Jorge.V
Answer Checked By - David Marino (JavaFixing Volunteer)