Issue
I have a simply registration.
here is part of my jsp register page:
<form class="form-horizontal" method="post" action="RightsGroupRegister">
<div class="form-group">
<label for="Name of group" class="col-sm-2 control-label">Name of group:</label>
<div class="col-sm-10">
<input class="form-control" id="name" name="name" placeholder="Name of group">
</div>
</div>
<div class="form-group">
<label for="Rights" class="col-sm-2 control-label">Rights:</label>
<div class="col-sm-10">
<input class="form-control" id="rights" name="rights" placeholder="Rights">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default">Create</button>
</div>
</div>
</form>
And here a controller:
@Controller
public class RightsGroupController {
private static final Logger LOGGER = LoggerFactory.getLogger(RightsGroupController.class);
private final RightsGroupService rightsGroupService;
@Inject
public RightsGroupController(RightsGroupService rightsGroupService) {
this.rightsGroupService = rightsGroupService;
}
@RequestMapping(value = "RightsGroupRegister", method = RequestMethod.GET)
public ModelAndView getRightsGroupView() {
LOGGER.debug("Received request for addRight");
return new ModelAndView("RightsGroupRegister", "form", new RightsGroupForm());
}
@RequestMapping(value = "RightsGroupRegister", method = RequestMethod.POST)
public String createRightsGroup(@ModelAttribute("form") RightsGroupForm form ) {
LOGGER.debug("Received request to create {}, with result={}", form);
try {
rightsGroupService.save(new Rightsgroup(form.getName(),form.getRights()));
} catch (RightsGroupAlreadyExistsException e) {
LOGGER.debug("Tried to create rightsgroup with existing id", e);
return "right_create";
}
return "redirect:/";
}}
Now problem, I really dont understand how to work with it. How to get to this form data from another object? for example list of Rights(id,name)?
Solution
There are a couple of ways of doing this. I suppose you mean to access the data on the page that you are redirecting to in your post method. this is one way:
public String createRightsGroup(@ModelAttribute("form") RightsGroupForm form, Model model)
Add Model to your arguments in the post method. Then, i.e.:
model.addAttribute("name", form.getName());
model.addAttribute("rights", form.getRights());
and..
return "redirect:/right_create";
In your JSP (right_create.jsp) you access fields like:
<table>
<tr>
<td>${name}</td>
<td>${rights}</td>
</tr>
</table>
if you have a collection if Right
you can do:
<table>
<c:forEach items="${rights}" var="right">
<tr>
<td>${right.id}</td>
<td>${right.name}</td>
</tr>
</c:forEach>
</table>
Answered By - Jack Flamp