I am creating a web application and have a question is it possible to write multiple ModelAttribute in Spring or not?
I tried something like this but I always get a 0. I also tried with spring binding but I get a 0 again. Thanks.
This is my controller.
@RequestMapping(value="/assignguesttohotel",method = RequestMethod.GET)
public ModelAndView assignguesttohotel_form(HttpServletResponse response) throws IOException {
return new ModelAndView("assignguesttohotel");
}
@RequestMapping(value="/assign",method = RequestMethod.POST)
public ModelAndView assigning(Guest guest, Hotel hotel) {
ModelAndView m = new ModelAndView();
System.out.println(guest.getId() + " " + hotel.getId());
m.addObject("guestid", guest.getId());
m.addObject("hotelid", hotel.getId());
HotelDAO dao = new HotelDAO();
dao.assignGuestToHotel(guest.getId(), hotel.getId());
m.setViewName("temp");
return m;
}
And the JSP (assignguesttohotel.jsp).
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Guest register</title>
</head>
<body>
<div align="center">
<h1>Search Guest by name</h1>
<form:form action="assign" method="post">
<table>
<tr>
<td>Guest id:</td>
<td>
<%-- <spring:bind path="guestid.id">--%>
<%-- <input name="${status.expression}" type="number" value="${status.value}">--%>
<%-- </spring:bind>--%>
<input name="guestid" type="number">
</td>
</tr>
<tr>
<td>Hotel id:</td>
<td>
<%-- <spring:bind path="hotelid.id">--%>
<%-- <input name="${status.expression}" type="number" value="${status.value}">--%>
<%-- </spring:bind>--%>
<input name="hotelid" type="number">
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Seach"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Yes, you can use multiple Model Attributes to receive multiple objects in the controller and we can also send multiple objects to the view page.
<form action="" method="post">
<div>
<label>Leave a comment below</label>
<textarea th:field="${rootComment.text}" rows="3"></textarea>
</div>
<textarea th:field="${anotherObject.text}" rows="3"></textarea>
</div>
</form>
Controller
@PostMapping("/receive")
String receiveObjects(Comment rootComment, Object2 anotherObject){
........
}
I am using thymeleaf so I have mentioned "th" thymeleaf tags.
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.