Join two tables in thymeleaf - spring

I have two tables:
userOrganization (userId, OrganizationId)
user (userId, name, age, ...)
The two tables are linked by userId.
I passed to the model via the controller a list of userOrganization.
In Thymeleaf, I can easily loop on the users to display the userId: it works now.
However, I would also like to display the name of the user table.
Do you have any ideas ?
What I have now:
<div>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
</tr>
</div>
and what I have done but which does not display anything:
<div>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
</tr>
</div>
and controller
#GetMapping("/add")
public String pageCreateCompany(final Model model, Principal principal) {
if (!model.containsAttribute("companyForm")) {
CompanyForm companyForm = new CompanyForm();
model.addAttribute("companyForm", companyForm);
final User userConnected = (User) ((Authentication) principal).getPrincipal();
model.addAttribute("users", this.userOrganizationService.getActiveUsersForOrganization(userConnected));
}
return "company/createCompanyPage";
}
thanks in advance :)

It simply worked with :
<div class="createCompany__container-form-input">
<td> Affectation du personnel </td>
<th:block th:each="user : ${users}">
<input type="checkbox" name="userChecked" th:value="${user.id}"/>
<label th:text="${user.id}"></label><label th:text="${user.user.firstName}"></label>
<br>
</th:block>

Related

Controller does not recieve data from jsp page

I have sent data from jsp page to controller. It shows error.
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists.
This is my controller::::
#GetMapping(value = "/createdistrict")
public ModelAndView createdistrict(Locale locale, Model model) {
List<Division> allDivisionList = new ArrayList<Division>();
allDivisionList = this.districtService.listdivisions() ;
Map<Integer,String> allDivision = new LinkedHashMap<Integer,String>();
for( int i=0 ; i < allDivisionList.size() ; i++) {
//System.out.println(" division id ::::::::::" + allDivisionList.get(i).getId() + " division name:::::::::" + allDivisionList.get(i).getName());
allDivision.put(allDivisionList.get(i).getId() , allDivisionList.get(i).getName());
}
return new ModelAndView("createdistrict" , "allDivision" , allDivision);
}
#RequestMapping(value="/adddistrict/{division}")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {
System.out.println("id:::::::::::::::::::" + division);
this.districtService.adddistrict(district, division);
return "redirect:districtlist";
}
This is my jsp page::::
<form method="POST" action="/farmvill/adddistrict" modelAtribute="district">
<table class="create-table table table-hover">
<tr>
<td>
Division
</td>
<td>
<select id="division" name="division">
<c:forEach items="${allDivision}" var="allDivision">
<option class="dropdivision" value="${allDivision.key}">${allDivision.value }</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<input type="text" id="name" name="name" path="name"></input>
</td>
</tr>
<!-- End of single tr -->
</table>
<!-- End of table -->
<div class="button-set text-right">
<button type="submit" class="btn site-btn filled-btn" id="savebutton">save</button>
cancel
reset
</div>
<!-- End of button-set -->
</form>
What I should do now?
Remove division from mapping path. it's a regular request parameter
#RequestMapping(value="/adddistrict")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {

spring mvc mapping - send value between controllers

I have got webapp in spring 3 mvc. The case is that I have index page with url, when user click on them should be display another page with details of choosed information. Now the details page is shown but without any information (on index page is creating model with correct variable but not in details controller - in debug mode).
index controller method:
#RequestMapping(value="/{site}", method = RequestMethod.GET)
public String showDetails(#RequestParam(value = "site", required = true) String site, Model model){
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
return "details";
}
index html:
<form action="#" th:object="${product}" method="post" th:action="#{/details}">
<table border="0" width="600" th:each="sb, poz : ${product}" >
<tr >
<td rowspan="3" width="20"><span th:text="${poz.count}"></span></td>
<td>
<a th:href="#{/details/(site=${sb.tytul})}" th:value="${site}"><span th:text="${sb.tytul}"></span></a>
</td>
</tr>
<tr >
<td><span th:text="${sb.adres}"></span></td>
</tr>
<tr>
<td>category:<b><span th:text="${sb.category.name}"></span></b></td>
</tr>
</table>
</form>
details controller method:
#RequestMapping(value = "details/{site}", method = RequestMethod.GET)
public String showHomePage(#PathVariable(value = "site") String site, Model model){
model.addAttribute("product");
return "details";
}
details html:
<form th:object="${product}" method="get" th:action="#{/details}">
<table border="1" width="600" >
<tr >
<td ><span th:text="${tytul}"></span></td>
<td>
<span th:text="${opis}"></span>
</td>
<td><span th:text="${adres}"></span></td>
</tr>
</table>
</form>
I don't have any ideas how to map the details site (I tried a lot of solution but nothing). Thanks for help.
With thymeleaf, using th:object, you need to reference the fields of that object with *{}
<form th:object="${product}" method="get" th:action="#{/details}">
<table border="1" width="600" >
<tr >
<td ><span th:text="*{tytul}"></span></td>
<td>
<span th:text="*{opis}"></span>
</td>
<td><span th:text="*{adres}"></span></td>
</tr>
</table>
</form>
assuming tytul, opis, and adres are fields of product. Unless it's a type, don't forget
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
in your details controller method, otherwise you won't have a Catalog model attribute.
inside your details controller where are you setting product object in your model ?
model.addAttribute("product");
is just settingstring object "product", fetch the product object and set it in details controller like you have done in showDetails method
Change
model.addAttribute("product");
To
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
in "showPage" method.

How to send back the model data from jsp to controller

I have a controller which sets few values to a model and sends to jsp. In jsp i need to show those values(as labels) along with additional values from user as input values. When i submit the jsp i only get valid values that user has entered and the values set earlier by controller is null.
JSP
<form:form
action="${pageContext.request.contextPath}/admin/deviceAction.html"
modelAttribute="deviceData">
<table class="gridtable" width="500px">
<tr>
<td>Device Name : </td>
<td>${deviceData.deviceName}</td>
</tr>
<tr>
<td>Model Name : </td>
<td>${deviceData.modelName}</td>
</tr>
<tr>
<td>Serial No : </td>
<td>${deviceData.serialNo}</td>
</tr>
<tr>
<td>Device Id : </td>
<td>${deviceData.deviceId}</td>
</tr>
<tr>
<td>Status : </td>
<td>${deviceData.statusCode}</td>
</tr>
<tr>
<td>Action : <span class="required">*</span></td>
<td>
<form:select path="deviceAction" >
<form:option value="" label="--- Select ---" />
<form:options items="${model.actionList}" />
</form:select>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="btn_submit">
</form:form>
Controller:
public ModelAndView beforeSubmit() {
ModelAndView modelView = new ModelAndView();
DeviceData deviceData = new DeviceData();
deviceData.setDevicePk("123");
deviceData.setAccessToken("abcwetrwertewrtetr");
deviceData.setDeviceId("deferterterterterwtetetertg");
deviceData.setDeviceName("test");
deviceData.setEnrolledDate("7-8-13");
deviceData.setModelName("test1");
deviceData.setSerialNo("test2dsfgdfgdfg");
deviceData.setStatusCode("test3");
List<String> actionList = getActionList();
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("actionList", actionList);
modelView.addObject("deviceData", deviceData);
modelView.addObject("model", model);
modelView.setViewName("admin/tokenSearchResult");
}
public ModelAndView afterSubmit() {
#ModelAttribute("deviceData") DeviceData deviceData, BindingResult result) {
logger.info("#################device datas are : " + deviceData.getDevicePk() + "###### " + deviceData.getDeviceAction());
return new ModelAndView();
}
deviceData.getDevicePk() is null
Only the drop down value is having valid value. Other values displayed in the screen are received as null.
Edit:
Till now i have found only one solution:
<form:input path="deviceName" readonly="true" />
But this way UI does not looks good. The editable and non editable values mixup in the screen. Looking for a better answer
Finally i am using hidden parameters to solve the problem.
Example:
<td>${deviceData.deviceName}</td>
is replaced by:
<td><form:hidden path="deviceName"</td>
By this way it helps me to avoid any css work(which i am not much comfortable)
If anyone get a better solution kindly post it here
You need to make them into form inputs using the Spring form tags in much the same way as you have for the form:select. If they are not editable by the user, you can always disable them.
You can simple hide those input. For example :
<input type="hidden" name="VehSeriesModelId" value="${vehDetailsVM.id }">
This way, you can get the data to the controller and the user will also not be able to edit the value. On the other hand, your form will also not show it :)

How to get data from two classes that are many-to-many, in the same edit form?

I am working with two classes that have a relationship many-to-many. I insert data in both tables, the relationship is usually registered in JoinTable. My question is, how to display the data from both tables in the same form?
Here is my controller:
#Controller
public class RecipeController {
#Autowired
private ReceitaService receitaService;
#RequestMapping(value = "/novaReceita.do", method = RequestMethod.POST)
public String createRecipes(#ModelAttribute("Receita") Receita receita, BindingResult resultReceita,
#ModelAttribute("Tag") Tag tag, BindingResult resultTag, #RequestParam String action, Map<String, Object> map) {
receita.getTag().add(tag);
receitaService.addReceita(receita);
map.put("receita", receita);
map.put("receitaList", receitaService.getAllReceita());
return "listRecipes";
}
Here is where I am having problems because I can only show data for a single table.
public String editForm(#PathVariable("id") int id, ModelMap map) {
map.addAttribute("receita", receitaService.getReceita(id));
return "updateRecipes";
}
Finally, the JSP page to display the data entered:
<c:url var="url" value="/receita/${receita.id}"/>
<form:form action="${url}" method="GET" commandName="receita">
<table width=80% >
<tr>
<td><strong>ID </strong></td>
<td><form:input path="id" disabled="true" class="input-small"/></td>
</tr>
<tr>
<td><strong>Title </strong></td>
<td><form:input path="titulo" class="input-xlarge"/></td>
</tr>
<tr>
<td valign=top><strong>Desc probl</strong></td>
<td><form:textarea path="desc_prob" class="input-xlarge" rows="3" /></td>
</tr>
<tr>
<td valign=top><strong>Desc soluc</strong></td>
<td><form:textarea path="desc_soluc" class="input-xlarge" rows="6" /></td>
</tr>
<tr>
<td><strong>Tag</strong></td>
<td> <form:input path="tag" disabled="true" class="input-small"/></td>
</tr>
</table>
</form:form>
What is missing to be able to show the data from both tables?
Thank's.
For single column/property you can use <form:input/>For Many to One you can use <form:select/>For One to Many you can use <form:select multiple='true'>In your case, you have to select a single ID first for the one side of the relationship which is receita and then display all the tags in that receita, so i think it counts as One to Many at that point. So in your case, try to use this tag:<form:select path="tag" multiple="true"/>

How to modify a record displaying a form in a view

I am trying to accomplish the following:
I have a list of fruits, that are stored in a table with two columns "id", "name" and "color".
Next to each fruit, I got a "modify" button. What I want to do here is being able to display the fruit in a form and being able to modify the "name" and "color" attributes.
I don't understand why, but when I click the "modify" button, the form is being displayed but the properties of the fruits that I clicked are not.
Here is the code:
Controller:
#RequestMapping(value = "/fruit/modify", method = RequestMethod.POST)
public String modifyFruit( #RequestParam("id") int id, ModelMap model) {
Fruit fruit = fruitManager.getFruitById(id);
model.addAttribute("fruit", fruit);
return "redirect:/modifyfruit";
}
#RequestMapping(value = "/modifyfruit", method = RequestMethod.GET)
public String showAddForm(#ModelAttribute("fruit") Fruit fruit, ModelMap model) {
model.addAttribute("fruit", fruit);
return "/secure/modifyfruit";
}
Here is the modify button that I am displaying next to each fruit in my list:
<td>
<c:url var="modifyUrl" value="/fruit/modify.html"/>
<form id="${fruitForm}" action="${modifyUrl}" method="POST">
<input id="id" name="id" type="hidden" value="${fruit.id}"/>
<input type="submit" value="modify"/>
</form>
</td>
Here is the modifyfruit.jsp that I am using to display the form that I want to populate:
<body>
<form:form method="post" commandName="fruit">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0"
cellpadding="5">
<tr>
<td align="right">Name:</td>
<td><form:input path="title" value="${fruit.name}"/></td>
</tr>
<tr>
<td align="right">Color:</td>
<td><form:input path="color" value="${fruit.color}"/></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Post Ad">
</form:form>
</body>
Your redirect is simply going to that new URL without any request params being added. Therefore your fruit ID is being discarded, which is why nothing gets displayed.
The redirect seems pointless - why not return the same view name string as the GET version instead?
To redirect with the params, try:
return "redirect:/modifyfruit?id=" + id;
EDIT: just noticed you have added the Fruit to the model - this does not get transferred in a redirect and wouldn't work anyway.

Resources